text
stringlengths
54
60.6k
<commit_before>#ifndef _PFASST_HPP_ #define _PFASST_HPP_ #include "pfasst/config.hpp" #include "pfasst/logging.hpp" namespace pfasst { inline static void init(int argc, char** argv, std::function<void()> opts = nullptr, std::function<void()> logs = nullptr) { if (opts) { opts(); } config::init(); log::start_log(argc, argv); if (logs) { logs(); } config::read_commandline(argc, argv); } } // ::pfasst #endif <commit_msg>docu: adding docu modules<commit_after>#ifndef _PFASST_HPP_ #define _PFASST_HPP_ #include "pfasst/config.hpp" #include "pfasst/logging.hpp" namespace pfasst { inline static void init(int argc, char** argv, std::function<void()> opts = nullptr, std::function<void()> logs = nullptr) { if (opts) { opts(); } config::init(); log::start_log(argc, argv); if (logs) { logs(); } config::read_commandline(argc, argv); } } // ::pfasst /** * @defgroup Controllers * Controllers represent the main entry point of PFASST++ as they ensemble the central algorithmic * logic of PFASST and related algorithms. * * @defgroup Internals * Entities listed in this module are ment to be for internal use only and should not be used * outside of PFASST++ itself. * * @defgroup Utilities * General utility functions not directly related to PFASST++ but also handy in user code. * * @defgroup Examples * A few different examples demonstrating the use and functionality of PFASST++. */ #endif <|endoftext|>
<commit_before>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" #include "Input.h" #include "BlueRayUtils.h" #include "World.h" #include "Action.h" #include "FPSRoleLocal.h" #include "StarControl.h" #include "RayControl.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); m_pRole->SetActorPosition(vec3(0, 0, 0)); //设置角色初始位置。以门处作为原点,三维坐标系vec3是向量 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //关闭游戏进程 { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { CAction* pAction = m_pRole->OrceAction("skill01"); if (pAction) { m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('3')) { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CRoleBase* pTarget = NULL; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 15.0f) { pTarget = m_vAIList[i]; break; } } if (pTarget) { CVector<int> vTarget; vTarget.Append(pTarget->GetRoleID()); pAction->SetupSkillBulletTarget(vTarget); m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1); } } } else if (g_Engine.pInput->IsKeyDown('4'))//多发子弹 { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) { vTarget.Append(m_vAIList[i]->GetRoleID()); } } if (!vTarget.Empty()) { pAction->SetupSkillBulletTarget(vTarget); } } } else if (g_Engine.pInput->IsKeyDown('5')) { CAction* pAction = m_pRole->OrceAction("skill03"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; pAction->SetupSkillTargetPoint(vPos); } } else if (g_Engine.pInput->IsKeyDown('6')) { CAction* pAction = m_pRole->OrceAction("skill06"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vPos.Append(m_vAIList[i]->GetPosition()); } pAction->SetupSkillTargetPoint(vPos); } } else if (g_Engine.pInput->IsKeyDown('7')) { CAction* pAction = m_pRole->OrceAction("skill05"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vTarget.Append(m_vAIList[i]->GetRoleID()); } if (!vTarget.Empty()) { pAction->SetupSkillBulletTarget(vTarget); } } } else if (g_Engine.pInput->IsKeyDown('8')) { CAction* pAction = m_pRole->OrceAction("skill07"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vPos.Append(m_vAIList[i]->GetPosition()); } pAction->SetupSkillBulletPosition(vPos); } } else if (g_Engine.pInput->IsKeyDown('9')) { CAction* pAction = m_pRole->OrceAction("skill08"); if (pAction) { m_pRole->StopMove(); pAction->SetupSkillBulletDirection(1); } } else if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC)) { g_Engine.pApp->Exit(); } if(g_Engine.pInput->IsLBDown()) { vec3 p0,p1; BlueRay::GetPlayerMouseDirection(p0,p1); vec3 vRetPoint,vRetNormal; int nS = -1; g_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS); if(-1 != nS) { m_pRole->MoveToPath(vRetPoint); } } for(int i = 0;i < 20;i++) { if(!m_vAIList[i]->IsMoveing()) { vec3 vPos = vec3(g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),1.1f); m_vAIList[i]->MoveToPath(vPos); } m_vAIList[i]->Update(ifps); } if (g_Engine.pInput->IsLBDown()) //shubiaozuojian { g_pSysControl->SetMouseGrab(1); m_pStarControl->Click(); } if (g_Engine.pInput->IsKeyDown(CInput::KEY_ESC)) { g_pSysControl->SetMouseGrab(0); } m_pCameraBase->SetMouseControls(g_pSysControl->GetMouseGrab()); m_pCameraBase->Update(ifps); m_pRole->SetActorDirection(m_pCameraBase->GetViewDirection()); m_pRole->UpdateActor(ifps); m_pCameraBase->SetPosition(m_pRole->GetActorPosition() + m_pRole->GetCameraOffset()); vec3 x = m_pCameraBase->GetModelview().getRow3(0); vec3 y = m_pCameraBase->GetModelview().getRow3(1); vec3 z = m_pCameraBase->GetModelview().getRow3(2); mat4 r = mat4_identity; r.setColumn3(0, -x); // r.setColumn3(1, z); // r.setColumn3(2, y); // m_pRole->UpdateTransform(r); m_pRole->Update(ifps); m_pSkillSystem->Update(ifps); return 0; } <commit_msg>Signed-off-by: mrlitong <litongtongxue@gmail.com><commit_after>#include "GameProcess.h" #include "Object.h" #include "Engine.h" #include "World.h" #include "App.h" #include "ToolsCamera.h" #include "ControlsApp.h" #include "MathLib.h" #include "Game.h" #include "Editor.h" #include "Input.h" #include "BlueRayUtils.h" #include "World.h" #include "Action.h" #include "FPSRoleLocal.h" #include "StarControl.h" #include "RayControl.h" using namespace MathLib; CGameProcess::CGameProcess(void) { } CGameProcess::~CGameProcess(void) { } int CGameProcess::Init() { g_Engine.pFileSystem->CacheFilesFormExt("char"); g_Engine.pFileSystem->CacheFilesFormExt("node"); g_Engine.pFileSystem->CacheFilesFormExt("smesh"); g_Engine.pFileSystem->CacheFilesFormExt("sanim"); g_Engine.pWorld->LoadWorld("data/scene/terrain/test/test.world"); //g_Engine.pWorld->LoadWorld("data/scene/terrain/cj/cj.world"); g_Engine.pControls->SetKeyPressFunc(KeyPress); g_Engine.pControls->SetKeyReleaseFunc(KeyRelease); m_pRole = new CFPSRoleLocal(); m_pRole->Init(10001, "data/role/hero/FpsRole/fps.char"); m_pRole->SetActorPosition(vec3(0, 0, 0)); //设置角色初始位置。以门处作为原点,三维坐标系vec3是向量 m_pSkillSystem = new CSkillSystem(this); m_pCameraBase = new CCameraBase(); m_pCameraBase->SetEnabled(1); g_pSysControl->SetMouseGrab(1); m_pStarControl = new CStarControl(); m_pRayControl = new CRayControl(); return 1; } int CGameProcess::ShutDown() //关闭游戏进程 { delete m_pRole; delete m_pSkillSystem; delete m_pCameraBase; delete m_pStarControl; delete m_pRayControl; DelAllListen(); return 0; } int CGameProcess::Update() { float ifps = g_Engine.pGame->GetIFps(); if (g_Engine.pInput->IsKeyDown('1')) { CAction* pAction = m_pRole->OrceAction("attack02"); if (pAction) { pAction->SetupSkillThrow(vec3_zero, -1.0f, 2.0f); m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('2')) { CAction* pAction = m_pRole->OrceAction("skill01"); if (pAction) { m_pRole->StopMove(); } } else if (g_Engine.pInput->IsKeyDown('3')) { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CRoleBase* pTarget = NULL; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 15.0f) { pTarget = m_vAIList[i]; break; } } if (pTarget) { CVector<int> vTarget; vTarget.Append(pTarget->GetRoleID()); pAction->SetupSkillBulletTarget(vTarget); m_pRole->SetDirection((pTarget->GetPosition() - m_pRole->GetPosition()).normalize(), 1); } } } else if (g_Engine.pInput->IsKeyDown('4'))//多发子弹 { CAction* pAction = m_pRole->OrceAction("skill02"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) { vTarget.Append(m_vAIList[i]->GetRoleID()); } } if (!vTarget.Empty()) { pAction->SetupSkillBulletTarget(vTarget); } } } else if (g_Engine.pInput->IsKeyDown('5')) { CAction* pAction = m_pRole->OrceAction("skill03"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; pAction->SetupSkillTargetPoint(vPos); } } else if (g_Engine.pInput->IsKeyDown('6')) { CAction* pAction = m_pRole->OrceAction("skill06"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vPos.Append(m_vAIList[i]->GetPosition()); } pAction->SetupSkillTargetPoint(vPos); } } else if (g_Engine.pInput->IsKeyDown('7')) { CAction* pAction = m_pRole->OrceAction("skill05"); if (pAction) { m_pRole->StopMove(); CVector<int> vTarget; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vTarget.Append(m_vAIList[i]->GetRoleID()); } if (!vTarget.Empty()) { pAction->SetupSkillBulletTarget(vTarget); } } } else if (g_Engine.pInput->IsKeyDown('8')) { CAction* pAction = m_pRole->OrceAction("skill07"); if (pAction) { m_pRole->StopMove(); CVector<vec3> vPos; for (int i = 0; i < 20; i++) { float l = (m_vAIList[i]->GetPosition() - m_pRole->GetPosition()).length(); if (l > 5.0f && l < 20.0f) vPos.Append(m_vAIList[i]->GetPosition()); } pAction->SetupSkillBulletPosition(vPos); } } else if (g_Engine.pInput->IsKeyDown('9')) { CAction* pAction = m_pRole->OrceAction("skill08"); if (pAction) { m_pRole->StopMove(); pAction->SetupSkillBulletDirection(1); } } else if (g_Engine.pInput->IsKeyUp(CInput::KEY_ESC)) { g_Engine.pApp->Exit(); } if(g_Engine.pInput->IsLBDown()) { vec3 p0,p1; BlueRay::GetPlayerMouseDirection(p0,p1); vec3 vRetPoint,vRetNormal; int nS = -1; g_Engine.pWorld->GetIntersection(p0,p1,CBRObject::MASK_SCENE,vRetPoint,vRetNormal,nS); if(-1 != nS) { m_pRole->MoveToPath(vRetPoint); } } for(int i = 0;i < 20;i++) { if(!m_vAIList[i]->IsMoveing()) { vec3 vPos = vec3(g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),g_Engine.pGame->GetRandomFloat(-20.0f,20.0f),1.1f); m_vAIList[i]->MoveToPath(vPos); } m_vAIList[i]->Update(ifps); } if (g_Engine.pInput->IsLBDown()) //shubiaozuojian { g_pSysControl->SetMouseGrab(1); m_pStarControl->Click(); } if (g_Engine.pInput->IsKeyDown(CInput::KEY_ESC)) { g_pSysControl->SetMouseGrab(0); } m_pCameraBase->SetMouseControls(g_pSysControl->GetMouseGrab()); m_pCameraBase->Update(ifps); m_pRole->SetActorDirection(m_pCameraBase->GetViewDirection()); m_pRole->UpdateActor(ifps); m_pCameraBase->SetPosition(m_pRole->GetActorPosition() + m_pRole->GetCameraOffset()); vec3 x = m_pCameraBase->GetModelview().getRow3(0); vec3 y = m_pCameraBase->GetModelview().getRow3(1); vec3 z = m_pCameraBase->GetModelview().getRow3(2); mat4 r = mat4_identity; r.setColumn3(0, -x); // r.setColumn3(1, z); // r.setColumn3(2, y); // m_pRole->UpdateTransform(r); m_pRole->Update(ifps); m_pSkillSystem->Update(ifps); m_pStarControl->Update(m_pCameraBase->GetPosition(), m_pCameraBase->GetDirection()); return 0; } <|endoftext|>
<commit_before>#/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: gluectrl.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: obo $ $Date: 2006-09-16 18:39:00 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include <string> // HACK: prevent conflict between STLPORT and Workshop headers #include <svx/dialogs.hrc> #ifndef _SVDGLUE_HXX //autogen #include <svx/svdglue.hxx> #endif #ifndef _SFXINTITEM_HXX //autogen #include <svtools/intitem.hxx> #endif #ifndef _SFXAPP_HXX //autogen #include <sfx2/app.hxx> #endif #ifndef _SFXDISPATCH_HXX //autogen #include <sfx2/dispatch.hxx> #endif #ifndef _SV_TOOLBOX_HXX //autogen #include <vcl/toolbox.hxx> #endif #ifndef _SFXVIEWFRM_HXX #include <sfx2/viewfrm.hxx> #endif #include "strings.hrc" #include "gluectrl.hxx" #include "sdresid.hxx" #include "app.hrc" using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::frame; // z.Z. werden von Joe nur die u.a. Moeglichkeiten unterstuetzt #define ESCDIR_COUNT 5 static UINT16 aEscDirArray[] = { SDRESC_SMART, SDRESC_LEFT, SDRESC_RIGHT, SDRESC_TOP, SDRESC_BOTTOM, // SDRESC_LO, // SDRESC_LU, // SDRESC_RO, // SDRESC_RU, // SDRESC_HORZ, // SDRESC_VERT, // SDRESC_ALL }; SFX_IMPL_TOOLBOX_CONTROL( SdTbxCtlGlueEscDir, SfxUInt16Item ) /************************************************************************* |* |* Konstruktor fuer Klebepunkt-Autrittsrichtungs-Listbox |* \************************************************************************/ GlueEscDirLB::GlueEscDirLB( Window* pParent, const Reference< XFrame >& rFrame ) : ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) ), m_xFrame( rFrame ) { String aStr; aStr += sal_Unicode('X'); Size aXSize( GetTextWidth( aStr ), GetTextHeight() ); //SetPosPixel( Point( aSize.Width(), 0 ) ); SetSizePixel( Size( aXSize.Width() * 12, aXSize.Height() * 10 ) ); Fill(); //SelectEntryPos( 0 ); Show(); } /************************************************************************* |* |* Dtor |* \************************************************************************/ GlueEscDirLB::~GlueEscDirLB() { } /************************************************************************* |* |* Ermittelt die Austrittsrichtung und verschickt den entspr. Slot |* \************************************************************************/ void GlueEscDirLB::Select() { UINT16 nPos = GetSelectEntryPos(); SfxUInt16Item aItem( SID_GLUE_ESCDIR, aEscDirArray[ nPos ] ); if ( m_xFrame.is() ) { Any a; Sequence< PropertyValue > aArgs( 1 ); aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "GlueEscapeDirection" )); aItem.QueryValue( a ); aArgs[0].Value = a; SfxToolBoxControl::Dispatch( Reference< XDispatchProvider >( m_xFrame->getController(), UNO_QUERY ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:GlueEscapeDirection" )), aArgs ); } /* SfxViewFrame::Current()->GetDispatcher()->Execute( SID_GLUE_ESCDIR, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aItem, (void*) NULL, 0L ); */ } /************************************************************************* |* |* Fuellen der Listbox mit Strings |* \************************************************************************/ void GlueEscDirLB::Fill() { InsertEntry( String( SdResId( STR_GLUE_ESCDIR_SMART ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_LEFT ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_RIGHT ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_TOP ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_BOTTOM ) ) ); /* InsertEntry( String( SdResId( STR_GLUE_ESCDIR_LO ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_LU ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_RO ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_RU ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_HORZ ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_VERT ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_ALL ) ) ); */ } /************************************************************************* |* |* Konstruktor fuer Klebepunkt-Autrittsrichtungs-Toolbox-Control |* \************************************************************************/ SdTbxCtlGlueEscDir::SdTbxCtlGlueEscDir( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) : SfxToolBoxControl( nSlotId, nId, rTbx ) { } /************************************************************************* |* |* Stellt Status in der Listbox des Controllers dar |* \************************************************************************/ void SdTbxCtlGlueEscDir::StateChanged( USHORT nSId, SfxItemState eState, const SfxPoolItem* pState ) { if( eState == SFX_ITEM_AVAILABLE ) { GlueEscDirLB* pGlueEscDirLB = (GlueEscDirLB*) ( GetToolBox(). GetItemWindow( GetId() ) ); if( pGlueEscDirLB ) { if( pState ) { pGlueEscDirLB->Enable(); if ( IsInvalidItem( pState ) ) { pGlueEscDirLB->SetNoSelection(); } else { UINT16 nEscDir = ( (const SfxUInt16Item*) pState )->GetValue(); pGlueEscDirLB->SelectEntryPos( GetEscDirPos( nEscDir ) ); } } else { pGlueEscDirLB->Disable(); pGlueEscDirLB->SetNoSelection(); } } } SfxToolBoxControl::StateChanged( nSId, eState, pState ); } /************************************************************************* |* |* No Comment |* \************************************************************************/ Window* SdTbxCtlGlueEscDir::CreateItemWindow( Window *pParent ) { if( GetSlotId() == SID_GLUE_ESCDIR ) { return( new GlueEscDirLB( pParent, m_xFrame ) ); } return( NULL ); } /************************************************************************* |* |* Liefert Position im Array fuer EscDir zurueck (Mapping fuer Listbox) |* \************************************************************************/ UINT16 SdTbxCtlGlueEscDir::GetEscDirPos( UINT16 nEscDir ) { for( UINT16 i = 0; i < ESCDIR_COUNT; i++ ) { if( aEscDirArray[ i ] == nEscDir ) return( i ); } return( 99 ); } <commit_msg>INTEGRATION: CWS changefileheader (1.7.358); FILE MERGED 2008/04/01 15:34:19 thb 1.7.358.2: #i85898# Stripping all external header guards 2008/03/31 13:57:45 rt 1.7.358.1: #i87441# Change license header to LPGL v3.<commit_after>#/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: gluectrl.cxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ // MARKER(update_precomp.py): autogen include statement, do not remove #include "precompiled_sd.hxx" #include <string> // HACK: prevent conflict between STLPORT and Workshop headers #include <svx/dialogs.hrc> #include <svx/svdglue.hxx> #include <svtools/intitem.hxx> #include <sfx2/app.hxx> #include <sfx2/dispatch.hxx> #include <vcl/toolbox.hxx> #include <sfx2/viewfrm.hxx> #include "strings.hrc" #include "gluectrl.hxx" #include "sdresid.hxx" #include "app.hrc" using namespace ::com::sun::star::uno; using namespace ::com::sun::star::beans; using namespace ::com::sun::star::frame; // z.Z. werden von Joe nur die u.a. Moeglichkeiten unterstuetzt #define ESCDIR_COUNT 5 static UINT16 aEscDirArray[] = { SDRESC_SMART, SDRESC_LEFT, SDRESC_RIGHT, SDRESC_TOP, SDRESC_BOTTOM, // SDRESC_LO, // SDRESC_LU, // SDRESC_RO, // SDRESC_RU, // SDRESC_HORZ, // SDRESC_VERT, // SDRESC_ALL }; SFX_IMPL_TOOLBOX_CONTROL( SdTbxCtlGlueEscDir, SfxUInt16Item ) /************************************************************************* |* |* Konstruktor fuer Klebepunkt-Autrittsrichtungs-Listbox |* \************************************************************************/ GlueEscDirLB::GlueEscDirLB( Window* pParent, const Reference< XFrame >& rFrame ) : ListBox( pParent, WinBits( WB_BORDER | WB_DROPDOWN ) ), m_xFrame( rFrame ) { String aStr; aStr += sal_Unicode('X'); Size aXSize( GetTextWidth( aStr ), GetTextHeight() ); //SetPosPixel( Point( aSize.Width(), 0 ) ); SetSizePixel( Size( aXSize.Width() * 12, aXSize.Height() * 10 ) ); Fill(); //SelectEntryPos( 0 ); Show(); } /************************************************************************* |* |* Dtor |* \************************************************************************/ GlueEscDirLB::~GlueEscDirLB() { } /************************************************************************* |* |* Ermittelt die Austrittsrichtung und verschickt den entspr. Slot |* \************************************************************************/ void GlueEscDirLB::Select() { UINT16 nPos = GetSelectEntryPos(); SfxUInt16Item aItem( SID_GLUE_ESCDIR, aEscDirArray[ nPos ] ); if ( m_xFrame.is() ) { Any a; Sequence< PropertyValue > aArgs( 1 ); aArgs[0].Name = rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( "GlueEscapeDirection" )); aItem.QueryValue( a ); aArgs[0].Value = a; SfxToolBoxControl::Dispatch( Reference< XDispatchProvider >( m_xFrame->getController(), UNO_QUERY ), rtl::OUString( RTL_CONSTASCII_USTRINGPARAM( ".uno:GlueEscapeDirection" )), aArgs ); } /* SfxViewFrame::Current()->GetDispatcher()->Execute( SID_GLUE_ESCDIR, SFX_CALLMODE_ASYNCHRON | SFX_CALLMODE_RECORD, &aItem, (void*) NULL, 0L ); */ } /************************************************************************* |* |* Fuellen der Listbox mit Strings |* \************************************************************************/ void GlueEscDirLB::Fill() { InsertEntry( String( SdResId( STR_GLUE_ESCDIR_SMART ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_LEFT ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_RIGHT ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_TOP ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_BOTTOM ) ) ); /* InsertEntry( String( SdResId( STR_GLUE_ESCDIR_LO ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_LU ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_RO ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_RU ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_HORZ ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_VERT ) ) ); InsertEntry( String( SdResId( STR_GLUE_ESCDIR_ALL ) ) ); */ } /************************************************************************* |* |* Konstruktor fuer Klebepunkt-Autrittsrichtungs-Toolbox-Control |* \************************************************************************/ SdTbxCtlGlueEscDir::SdTbxCtlGlueEscDir( USHORT nSlotId, USHORT nId, ToolBox& rTbx ) : SfxToolBoxControl( nSlotId, nId, rTbx ) { } /************************************************************************* |* |* Stellt Status in der Listbox des Controllers dar |* \************************************************************************/ void SdTbxCtlGlueEscDir::StateChanged( USHORT nSId, SfxItemState eState, const SfxPoolItem* pState ) { if( eState == SFX_ITEM_AVAILABLE ) { GlueEscDirLB* pGlueEscDirLB = (GlueEscDirLB*) ( GetToolBox(). GetItemWindow( GetId() ) ); if( pGlueEscDirLB ) { if( pState ) { pGlueEscDirLB->Enable(); if ( IsInvalidItem( pState ) ) { pGlueEscDirLB->SetNoSelection(); } else { UINT16 nEscDir = ( (const SfxUInt16Item*) pState )->GetValue(); pGlueEscDirLB->SelectEntryPos( GetEscDirPos( nEscDir ) ); } } else { pGlueEscDirLB->Disable(); pGlueEscDirLB->SetNoSelection(); } } } SfxToolBoxControl::StateChanged( nSId, eState, pState ); } /************************************************************************* |* |* No Comment |* \************************************************************************/ Window* SdTbxCtlGlueEscDir::CreateItemWindow( Window *pParent ) { if( GetSlotId() == SID_GLUE_ESCDIR ) { return( new GlueEscDirLB( pParent, m_xFrame ) ); } return( NULL ); } /************************************************************************* |* |* Liefert Position im Array fuer EscDir zurueck (Mapping fuer Listbox) |* \************************************************************************/ UINT16 SdTbxCtlGlueEscDir::GetEscDirPos( UINT16 nEscDir ) { for( UINT16 i = 0; i < ESCDIR_COUNT; i++ ) { if( aEscDirArray[ i ] == nEscDir ) return( i ); } return( 99 ); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: futransf.hxx,v $ * * $Revision: 1.1.1.1 $ * * last change: $Author: hr $ $Date: 2000-09-18 16:48:39 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef _SD_FUTRANSF_HXX #define _SD_FUTRANSF_HXX #ifndef _SVX_RETENUM_HXX #include <svx/rectenum.hxx> #endif #ifndef _SD_FUPOOR_HXX #include "fupoor.hxx" #endif class FuTransform : public FuPoor { public: TYPEINFO(); FuTransform(SdViewShell* pViewSh, SdWindow* pWin, SdView* pView, SdDrawDocument* pDoc, SfxRequest& rReq); virtual ~FuTransform() {} virtual void Activate(); // Function aktivieren virtual void Deactivate(); // Function deaktivieren Point GetPoint( Rectangle aRect, RECT_POINT eRP ); }; #endif // _SD_FUTRANSF_HXX <commit_msg>INTEGRATION: CWS impress1 (1.1.1.1.262); FILE MERGED 2003/09/16 13:35:54 af 1.1.1.1.262.1: #111996# Introduction of namespace sd. Use of sub-shells.<commit_after>/************************************************************************* * * $RCSfile: futransf.hxx,v $ * * $Revision: 1.2 $ * * last change: $Author: obo $ $Date: 2004-01-20 12:16:04 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SD_FU_TRANSFORM_HXX #define SD_FU_TRANSFORM_HXX #ifndef _SVX_RETENUM_HXX #include <svx/rectenum.hxx> #endif #ifndef SD_FU_POOR_HXX #include "fupoor.hxx" #endif namespace sd { class FuTransform : public FuPoor { public: TYPEINFO(); FuTransform ( ViewShell* pViewSh, ::sd::Window* pWin, ::sd::View* pView, SdDrawDocument* pDoc, SfxRequest& rReq); virtual ~FuTransform (void) {} virtual void Activate(); // Function aktivieren virtual void Deactivate(); // Function deaktivieren Point GetPoint( Rectangle aRect, RECT_POINT eRP ); }; } // end of namespace sd #endif <|endoftext|>
<commit_before>#ifndef _SDD_ORDER_STRATEGIES_FORCE_HH_ #define _SDD_ORDER_STRATEGIES_FORCE_HH_ #include <algorithm> // minmax_element #include <cassert> #include <functional> // reference_wrapper #include <limits> #include <numeric> // accumulate #include <stdexcept> // runtime_error #include <vector> #include <boost/container/flat_set.hpp> #include "sdd/hom/definition.hh" #include "sdd/order/order.hh" namespace sdd { namespace force { /*------------------------------------------------------------------------------------------------*/ namespace /* anonymous */ { // Forward declaration for vertex. struct hyperedge; /// @internal struct vertex { /// @brief The corresponding index in the order's nodes. const unsigned int pos; /// @brief This vertex's tentative location. double location; /// @brief The hyperedges this vertex is connected to. std::vector<hyperedge*> hyperedges; /// @brief Constructor. vertex(unsigned int p, double l) : pos(p), location(l), hyperedges() {} }; /// @internal struct hyperedge { /// @brief The center of gravity. double cog; /// @brief Vertices connected to this hyperedge. boost::container::flat_set<vertex*> vertices; /// @brief Constructor with an already existing container of vertices. hyperedge(const boost::container::flat_set<vertex*>& v) : cog(0), vertices(v) {} /// @brief Compute the center of gravity. void center_of_gravity() noexcept { assert(not vertices.empty()); cog = std::accumulate( vertices.cbegin(), vertices.cend(), 0 , [](double acc, const vertex* v){return acc + v->location;} ) / vertices.size(); } /// @brief Compute the span of all vertices. double span() const noexcept { assert(not vertices.empty()); const auto minmax = std::minmax_element( vertices.cbegin(), vertices.cend() , [](const vertex* lhs, const vertex* rhs) {return lhs->location < rhs->location;}); return *minmax.second - *minmax.first; } }; } // namespace anonymous /*------------------------------------------------------------------------------------------------*/ /// @internal template <typename C> class mk_hyperedges_visitor { private: /// @brief Where to get vertices to connect to hyperedges. std::vector<vertex>& vertices_; /// @brief Where to put hyperedges created by this visitor. std::vector<hyperedge>& hyperedges_; public: /// @brief Required by the mem::variant visitor mechanism. using result_type = boost::container::flat_set<vertex*>; /// @brief Constructor. mk_hyperedges_visitor(std::vector<vertex>& v, std::vector<hyperedge>& h) : vertices_(v), hyperedges_(h) {} /// @brief composition is a node of the AST. result_type operator()(const hom::_composition<C>& c) const { result_type&& res = visit(*this, c.left()); auto&& r = visit(*this, c.right()); res.insert(r.begin(), r.end()); if (not res.empty()) { hyperedges_.emplace_back(res); } return res; } #if !defined(HAS_NO_BOOST_COROUTINE) /// @brief expression is a leaf of the AST. result_type operator()(const hom::_expression<C>& e) const { // There are several variables touched by an expression, we keep this information. result_type res; res.reserve(e.operands().size()); for (const auto& position : e.operands()) { res.insert(&vertices_[position]); } if (not res.empty()) { hyperedges_.emplace_back(res); } return res; } #endif // !defined(HAS_NO_BOOST_COROUTINE) /// @brief fixpoint is a node of the AST. result_type operator()(const hom::_fixpoint<C>& f) const { // We don't need to create an hyperedge as it's the same as the nested operand. return visit(*this, f.hom()); } /// @brief function is a leaf of the AST. result_type operator()(const hom::_function<C>& f) const { result_type res; res.insert(&vertices_[f.target()]); return res; } /// @brief inductive is a leaf of the AST. /// /// There's a problem: we don't know ahead of time on what variable an inductive applies. /// @todo Ask the inductive if it skips for every variable of the order (it will just be an /// approximation though). result_type operator()(const hom::_inductive<C>&) const { return result_type(); } /// @brief intersection is a node of the AST. result_type operator()(const hom::_intersection<C>& i) const { result_type res; for (const auto& h : i) { auto&& tmp = visit(*this, h); res.insert(tmp.begin(), tmp.end()); } if (not res.empty()) { hyperedges_.emplace_back(res); } return res; } /// @brief local is a node of the AST. /// /// Hierarchy is unsupported for the moment. result_type operator()(const hom::_local<C>& l) const { throw std::runtime_error("FORCE: local homomorphism is unsupported."); } /// @brief saturation_fixpoint is a node of the AST. result_type operator()(const hom::_saturation_fixpoint<C>& sf) const { // We don't want to create an hyperedge for saturation operations. result_type&& res = visit(*this, sf.F()); auto&& l = visit(*this, sf.L()); res.insert(l.begin(), l.end()); for (auto cit = sf.G_begin(); cit != sf.G_end(); ++cit) { auto&& g = visit(*this, *cit); res.insert(g.begin(), g.end()); } return res; } /// @brief saturation_intersection is a node of the AST. result_type operator()(const hom::_saturation_intersection<C>& si) const { // We don't want to create an hyperedge for saturation operations. result_type res; if (si.F()) { auto&& f = visit(*this, *si.F()); res.insert(f.begin(), f.end()); } if (si.L()) { auto&& l = visit(*this, *si.L()); res.insert(l.begin(), l.end()); } for (const auto& h : si.G()) { auto&& g = visit(*this, h); res.insert(g.begin(), g.end()); } return res; } /// @brief saturation_sum is a node of the AST. result_type operator()(const hom::_saturation_sum<C>& si) const { // We don't want to create an hyperedge for saturation operations. result_type res; if (si.F()) { auto&& f = visit(*this, *si.F()); res.insert(f.begin(), f.end()); } if (si.L()) { auto&& l = visit(*this, *si.L()); res.insert(l.begin(), l.end()); } for (const auto& h : si.G()) { auto&& g = visit(*this, h); res.insert(g.begin(), g.end()); } return res; } /// @brief simple_expression is a leaf of the AST. result_type operator()(const hom::_simple_expression<C>& e) const { // There are several variables touched by a simple expression, we keep this information. result_type res; res.reserve(e.operands().size()); for (const auto& position : e.operands()) { res.insert(&vertices_[position]); } if (not res.empty()) { hyperedges_.emplace_back(res); } return res; } /// @brief sum is a node of the AST. result_type operator()(const hom::_sum<C>& s) const { result_type res; for (const auto& h : s) { auto&& tmp = visit(*this, h); res.insert(tmp.begin(), tmp.end()); } if (not res.empty()) { hyperedges_.emplace_back(res); } return res; } /// @brief All other homomorphisms that are leaves of the AST, but that do not target a specific /// variable. template <typename T> result_type operator()(const T&) const { return result_type(); } }; /*------------------------------------------------------------------------------------------------*/ /// @internal template <typename C> class worker { private: /// @brief Keep the order. const order<C> o_; /// @brief Keep the homomorphism. const homomorphism<C> h_; /// @brief Map an order_node position to its corresponding vertex; /// /// The order_node position is the index in this vector. std::vector<vertex> vertices_; /// @brief The hyperedges that link together vertices. std::vector<hyperedge> hyperedges_; public: /// @brief Constructor. worker(const order<C>& o, const homomorphism<C>& h) : o_(o), h_(h), vertices_(), hyperedges_() { // Assign a initial location for every vertex. vertices_.reserve(o_.nodes().size()); for (std::size_t i = 0; i < o_.nodes().size(); ++i) { vertices_.emplace_back(i /* position in order.nodes */, i /* initial location */); } // Build hyperedges visit(mk_hyperedges_visitor<C>(vertices_, hyperedges_), h); // Update all vertices with their connected hyperedges for (auto& edge : hyperedges_) { for (auto& vertex_ptr : edge.vertices) { vertex_ptr->hyperedges.push_back(&edge); } } } /// @brief Dump the hypergraph to the DOT format. void to_dot(std::ostream& os) const { os << "graph hypergraph { layout=fdp;" << std::endl; for (const auto& vertex : vertices_) { os << "vertex_" << vertex.pos << " [label=\"" << o_.nodes()[vertex.pos].identifier().user() << "\"];" << std::endl; } for (const auto& edge : hyperedges_) { os << "hyperedge_" << &edge << " [label=\"\",shape=point]" << std::endl; for (const auto& vertex_ptr : edge.vertices) { os << "hyperedge_" << &edge << " -- vertex_" << vertex_ptr->pos << ";" << std::endl; } } os << "}" << std::endl; } /// @brief Effectively apply the FORCE ordering strategy. order<C> operator()() { std::vector<std::reference_wrapper<vertex>> sorted_vertices(vertices_.begin(), vertices_.end()); double span = std::numeric_limits<double>::max(); double old_span = 0; do { old_span = span; // Compute the new center of gravity for every hyperedge. for (auto& edge : hyperedges_) { edge.center_of_gravity(); } // Compute the tentative new location of every vertex. for (auto& vertex : vertices_) { assert(not vertex.hyperedges.empty()); vertex.location = std::accumulate( vertex.hyperedges.cbegin(), vertex.hyperedges.cend(), 0 , [](double acc, const hyperedge* e){return acc + e->cog;} ) / vertex.hyperedges.size(); } // Sort tentative vertex locations. std::sort( sorted_vertices.begin(), sorted_vertices.end() , [](vertex& lhs, vertex& rhs){return lhs.location < rhs.location;}); // Assign integer indices to the vertices. unsigned int pos = 0;; std::for_each( sorted_vertices.begin(), sorted_vertices.end() , [&pos](vertex& v){v.location = pos++;}); span = get_total_span(); } while (old_span > span); order_builder<C> ob; for (auto rcit = sorted_vertices.rbegin(); rcit != sorted_vertices.rend(); ++rcit) { ob.push(o_.nodes()[rcit->get().pos].identifier().user()); } return order<C>(ob); } private: double get_total_span() const noexcept { return std::accumulate( hyperedges_.cbegin(), hyperedges_.cend(), 0 , [](double acc, const hyperedge& h){return acc + h.span();}); } }; } // namespace force /*------------------------------------------------------------------------------------------------*/ /// @brief The FORCE ordering strategy. /// /// See http://dx.doi.org/10.1145/764808.764839 for the details. template <typename C> order<C> force_ordering(const order<C>& o, const homomorphism<C>& h) { if (o.empty() or h == id<C>()) { return o; } return force::worker<C>(o, h)(); } /*------------------------------------------------------------------------------------------------*/ } // namespace sdd #endif // _SDD_ORDER_STRATEGIES_FORCE_HH_ <commit_msg>Export DOT of hypergraph or debugging purposes.<commit_after>#ifndef _SDD_ORDER_STRATEGIES_FORCE_HH_ #define _SDD_ORDER_STRATEGIES_FORCE_HH_ #include <algorithm> // minmax_element #include <cassert> #include <functional> // reference_wrapper #include <limits> #include <numeric> // accumulate #include <stdexcept> // runtime_error #include <vector> #include <boost/container/flat_set.hpp> #include <fstream> #include "sdd/hom/definition.hh" #include "sdd/order/order.hh" namespace sdd { namespace force { /*------------------------------------------------------------------------------------------------*/ namespace /* anonymous */ { // Forward declaration for vertex. struct hyperedge; /// @internal struct vertex { /// @brief The corresponding index in the order's nodes. const unsigned int pos; /// @brief This vertex's tentative location. double location; /// @brief The hyperedges this vertex is connected to. std::vector<hyperedge*> hyperedges; /// @brief Constructor. vertex(unsigned int p, double l) : pos(p), location(l), hyperedges() {} }; /// @internal struct hyperedge { /// @brief The center of gravity. double cog; /// @brief Vertices connected to this hyperedge. boost::container::flat_set<vertex*> vertices; /// @brief Constructor with an already existing container of vertices. hyperedge(const boost::container::flat_set<vertex*>& v) : cog(0), vertices(v) {} /// @brief Compute the center of gravity. void center_of_gravity() noexcept { assert(not vertices.empty()); cog = std::accumulate( vertices.cbegin(), vertices.cend(), 0 , [](double acc, const vertex* v){return acc + v->location;} ) / vertices.size(); } /// @brief Compute the span of all vertices. double span() const noexcept { assert(not vertices.empty()); const auto minmax = std::minmax_element( vertices.cbegin(), vertices.cend() , [](const vertex* lhs, const vertex* rhs) {return lhs->location < rhs->location;}); return *minmax.second - *minmax.first; } }; } // namespace anonymous /*------------------------------------------------------------------------------------------------*/ /// @internal template <typename C> class mk_hyperedges_visitor { private: /// @brief Where to get vertices to connect to hyperedges. std::vector<vertex>& vertices_; /// @brief Where to put hyperedges created by this visitor. std::vector<hyperedge>& hyperedges_; public: /// @brief Required by the mem::variant visitor mechanism. using result_type = boost::container::flat_set<vertex*>; /// @brief Constructor. mk_hyperedges_visitor(std::vector<vertex>& v, std::vector<hyperedge>& h) : vertices_(v), hyperedges_(h) {} /// @brief composition is a node of the AST. result_type operator()(const hom::_composition<C>& c) const { result_type&& res = visit(*this, c.left()); auto&& r = visit(*this, c.right()); res.insert(r.begin(), r.end()); if (not res.empty()) { hyperedges_.emplace_back(res); } return res; } #if !defined(HAS_NO_BOOST_COROUTINE) /// @brief expression is a leaf of the AST. result_type operator()(const hom::_expression<C>& e) const { // There are several variables touched by an expression, we keep this information. result_type res; res.reserve(e.operands().size()); for (const auto& position : e.operands()) { res.insert(&vertices_[position]); } if (not res.empty()) { hyperedges_.emplace_back(res); } return res; } #endif // !defined(HAS_NO_BOOST_COROUTINE) /// @brief fixpoint is a node of the AST. result_type operator()(const hom::_fixpoint<C>& f) const { // We don't need to create an hyperedge as it's the same as the nested operand. return visit(*this, f.hom()); } /// @brief function is a leaf of the AST. result_type operator()(const hom::_function<C>& f) const { result_type res; res.insert(&vertices_[f.target()]); return res; } /// @brief inductive is a leaf of the AST. /// /// There's a problem: we don't know ahead of time on what variable an inductive applies. /// @todo Ask the inductive if it skips for every variable of the order (it will just be an /// approximation though). result_type operator()(const hom::_inductive<C>&) const { return result_type(); } /// @brief intersection is a node of the AST. result_type operator()(const hom::_intersection<C>& i) const { result_type res; for (const auto& h : i) { auto&& tmp = visit(*this, h); res.insert(tmp.begin(), tmp.end()); } if (not res.empty()) { hyperedges_.emplace_back(res); } return res; } /// @brief local is a node of the AST. /// /// Hierarchy is unsupported for the moment. result_type operator()(const hom::_local<C>& l) const { throw std::runtime_error("FORCE: local homomorphism is unsupported."); } /// @brief saturation_fixpoint is a node of the AST. result_type operator()(const hom::_saturation_fixpoint<C>& sf) const { // We don't want to create an hyperedge for saturation operations. result_type&& res = visit(*this, sf.F()); auto&& l = visit(*this, sf.L()); res.insert(l.begin(), l.end()); for (auto cit = sf.G_begin(); cit != sf.G_end(); ++cit) { auto&& g = visit(*this, *cit); res.insert(g.begin(), g.end()); } return res; } /// @brief saturation_intersection is a node of the AST. result_type operator()(const hom::_saturation_intersection<C>& si) const { // We don't want to create an hyperedge for saturation operations. result_type res; if (si.F()) { auto&& f = visit(*this, *si.F()); res.insert(f.begin(), f.end()); } if (si.L()) { auto&& l = visit(*this, *si.L()); res.insert(l.begin(), l.end()); } for (const auto& h : si.G()) { auto&& g = visit(*this, h); res.insert(g.begin(), g.end()); } return res; } /// @brief saturation_sum is a node of the AST. result_type operator()(const hom::_saturation_sum<C>& si) const { // We don't want to create an hyperedge for saturation operations. result_type res; if (si.F()) { auto&& f = visit(*this, *si.F()); res.insert(f.begin(), f.end()); } if (si.L()) { auto&& l = visit(*this, *si.L()); res.insert(l.begin(), l.end()); } for (const auto& h : si.G()) { auto&& g = visit(*this, h); res.insert(g.begin(), g.end()); } return res; } /// @brief simple_expression is a leaf of the AST. result_type operator()(const hom::_simple_expression<C>& e) const { // There are several variables touched by a simple expression, we keep this information. result_type res; res.reserve(e.operands().size()); for (const auto& position : e.operands()) { res.insert(&vertices_[position]); } if (not res.empty()) { hyperedges_.emplace_back(res); } return res; } /// @brief sum is a node of the AST. result_type operator()(const hom::_sum<C>& s) const { result_type res; for (const auto& h : s) { auto&& tmp = visit(*this, h); res.insert(tmp.begin(), tmp.end()); } if (not res.empty()) { hyperedges_.emplace_back(res); } return res; } /// @brief All other homomorphisms that are leaves of the AST, but that do not target a specific /// variable. template <typename T> result_type operator()(const T&) const { return result_type(); } }; /*------------------------------------------------------------------------------------------------*/ /// @internal template <typename C> class worker { private: /// @brief Keep the order. const order<C> o_; /// @brief Keep the homomorphism. const homomorphism<C> h_; /// @brief Map an order_node position to its corresponding vertex; /// /// The order_node position is the index in this vector. std::vector<vertex> vertices_; /// @brief The hyperedges that link together vertices. std::vector<hyperedge> hyperedges_; public: /// @brief Constructor. worker(const order<C>& o, const homomorphism<C>& h) : o_(o), h_(h), vertices_(), hyperedges_() { // Assign a initial location for every vertex. vertices_.reserve(o_.nodes().size()); for (std::size_t i = 0; i < o_.nodes().size(); ++i) { vertices_.emplace_back(i /* position in order.nodes */, i /* initial location */); } // Build hyperedges visit(mk_hyperedges_visitor<C>(vertices_, hyperedges_), h); std::ofstream dot_file("/tmp/force.dot"); if (dot_file.is_open()) { to_dot(dot_file); } // Update all vertices with their connected hyperedges for (auto& edge : hyperedges_) { for (auto& vertex_ptr : edge.vertices) { vertex_ptr->hyperedges.push_back(&edge); } } } /// @brief Dump the hypergraph to the DOT format. void to_dot(std::ostream& os) const { os << "graph hypergraph { layout=fdp;" << std::endl; for (const auto& vertex : vertices_) { os << "vertex_" << vertex.pos << " [label=\"" << o_.nodes()[vertex.pos].identifier().user() << "\"];" << std::endl; } for (const auto& edge : hyperedges_) { os << "hyperedge_" << &edge << " [label=\"\",shape=point]" << std::endl; for (const auto& vertex_ptr : edge.vertices) { os << "hyperedge_" << &edge << " -- vertex_" << vertex_ptr->pos << ";" << std::endl; } } os << "}" << std::endl; } /// @brief Effectively apply the FORCE ordering strategy. order<C> operator()() { std::vector<std::reference_wrapper<vertex>> sorted_vertices(vertices_.begin(), vertices_.end()); double span = std::numeric_limits<double>::max(); double old_span = 0; do { old_span = span; // Compute the new center of gravity for every hyperedge. for (auto& edge : hyperedges_) { edge.center_of_gravity(); } // Compute the tentative new location of every vertex. for (auto& vertex : vertices_) { assert(not vertex.hyperedges.empty()); vertex.location = std::accumulate( vertex.hyperedges.cbegin(), vertex.hyperedges.cend(), 0 , [](double acc, const hyperedge* e){return acc + e->cog;} ) / vertex.hyperedges.size(); } // Sort tentative vertex locations. std::sort( sorted_vertices.begin(), sorted_vertices.end() , [](vertex& lhs, vertex& rhs){return lhs.location < rhs.location;}); // Assign integer indices to the vertices. unsigned int pos = 0;; std::for_each( sorted_vertices.begin(), sorted_vertices.end() , [&pos](vertex& v){v.location = pos++;}); span = get_total_span(); } while (old_span > span); order_builder<C> ob; for (auto rcit = sorted_vertices.rbegin(); rcit != sorted_vertices.rend(); ++rcit) { ob.push(o_.nodes()[rcit->get().pos].identifier().user()); } return order<C>(ob); } private: double get_total_span() const noexcept { return std::accumulate( hyperedges_.cbegin(), hyperedges_.cend(), 0 , [](double acc, const hyperedge& h){return acc + h.span();}); } }; } // namespace force /*------------------------------------------------------------------------------------------------*/ /// @brief The FORCE ordering strategy. /// /// See http://dx.doi.org/10.1145/764808.764839 for the details. template <typename C> order<C> force_ordering(const order<C>& o, const homomorphism<C>& h) { if (o.empty() or h == id<C>()) { return o; } return force::worker<C>(o, h)(); } /*------------------------------------------------------------------------------------------------*/ } // namespace sdd #endif // _SDD_ORDER_STRATEGIES_FORCE_HH_ <|endoftext|>
<commit_before>struct GoodTrack { Int_t lab; Int_t code; Float_t px,py,pz; Float_t x,y,z; Float_t pxg,pyg,pzg,ptg; Bool_t flag; }; Int_t good_tracks(GoodTrack *gt, Int_t max); Int_t TPCtracks() { Int_t i; cerr<<"Doing comparison...\n"; // Connect the Root Galice file containing Geometry, Kine and Hits TFile *cf=TFile::Open("AliTPCclusters.root"); if (!cf->IsOpen()) {cerr<<"Can't open AliTPCclusters.root !\n"; return 1;} AliTPCParam *digp= (AliTPCParam*)cf->Get("75x40_100x60"); if (!digp) { cerr<<"TPC parameters have not been found !\n"; return 2; } // Load clusters AliTPCClustersArray *ca=new AliTPCClustersArray; ca->Setup(digp); ca->SetClusterType("AliTPCcluster"); ca->ConnectTree("Segment Tree"); Int_t nentr=Int_t(ca->GetTree()->GetEntries()); for (Int_t i=0; i<nentr; i++) { ca->LoadEntry(i); } // Load tracks TFile *tf=TFile::Open("AliTPCtracks.root"); if (!tf->IsOpen()) {cerr<<"Can't open AliTPCtracks.root !\n"; return 3;} TObjArray tarray(2000); TTree *tracktree=(TTree*)tf->Get("TreeT"); TBranch *tbranch=tracktree->GetBranch("tracks"); nentr=(Int_t)tracktree->GetEntries(); for (i=0; i<nentr; i++) { AliTPCtrack *iotrack=new AliTPCtrack; tbranch->SetAddress(&iotrack); tracktree->GetEvent(i); iotrack->CookLabel(ca); tarray.AddLast(iotrack); } tf->Close(); delete ca; cf->Close(); //printf("after cf close\n"); cerr<<"Number of found tracks "<<nentr<<endl; tarray.Sort(); TFile *pfile = new TFile("tpctracks.root","RECREATE"); TTree tracktree1("TreeT","Tree with TPC tracks"); AliTPCtrack *iotrack=0; tracktree1.Branch("tracks","AliTPCtrack",&iotrack,32000,0); for (i=0; i<nentr; i++) { iotrack=(AliTPCtrack*)tarray.UncheckedAt(i); tracktree1.Fill(); } tracktree1.Write(); pfile->Close(); tarray.Clear(); ///////////////////////////////////////////////////////////////////////// GoodTrack gt[15000]; Int_t ngood=0; cerr<<"Marking good tracks (this will take a while)...\n"; ngood=good_tracks(gt,15000); ofstream out("good_tracks"); if (out) { for (Int_t ngd=0; ngd<ngood; ngd++) out<<gt[ngd].lab<<' '<<gt[ngd].code<<' ' <<gt[ngd].px <<' '<<gt[ngd].py<<' '<<gt[ngd].pz<<' ' <<gt[ngd].x <<' '<<gt[ngd].y <<' '<<gt[ngd].z <<' ' <<gt[ngd].pxg <<' '<<gt[ngd].pyg <<' '<<gt[ngd].pzg <<' ' <<gt[ngd].ptg <<gt[ngd].flag<<endl; } else cerr<<"Can not open file (good_tracks) !\n"; out.close(); cerr<<"Number of good tracks : "<<ngood<<endl; printf("before return in tpctracks\n"); return 0; } //--------------------------------- Int_t good_tracks(GoodTrack *gt, Int_t max) { Int_t nt=0; //TFile *file=TFile::Open("rfio:galice.root"); // via server TFile *file=TFile::Open("galice.root"); if (!file->IsOpen()) {cerr<<"Can't open galice.root !\n"; exit(4);} if (!(gAlice=(AliRun*)file->Get("gAlice"))) { cerr<<"gAlice have not been found on galice.root !\n"; exit(5); } gAlice->GetEvent(0); AliTPC *TPC=(AliTPC*)gAlice->GetDetector("TPC"); Int_t ver = TPC->IsVersion(); cerr<<"TPC version "<<ver<<" has been found !\n"; AliTPCParam *digp=(AliTPCParam*)file->Get("75x40_100x60"); if (!digp) { cerr<<"TPC parameters have not been found !\n"; exit(6); } TPC->SetParam(digp); Int_t nrow_up=digp->GetNRowUp(); Int_t nrows=digp->GetNRowLow()+nrow_up; Int_t zero=digp->GetZeroSup(); Int_t gap=Int_t(0.125*nrows); Int_t good_number=Int_t(0.4*nrows); TObjArray *particles=gAlice->Particles(); //Int_t np=particles->GetEntriesFast(); Int_t np=gAlice->GetNtrack(); //FCA correction Int_t *good=new Int_t[np]; for (Int_t ii=0; ii<np; ii++) good[ii]=0; //MI change to be possible compile macro //definition out of the switch statement Int_t sectors_by_rows=0; TTree *TD=0; AliSimDigits da, *digits=&da; Int_t *count=0; switch (ver) { case 1: { TFile *cf=TFile::Open("AliTPCclusters.root"); if (!cf->IsOpen()){cerr<<"Can't open AliTPCclusters.root !\n";exit(5);} AliTPCClustersArray *ca=new AliTPCClustersArray; ca->Setup(digp); ca->SetClusterType("AliTPCcluster"); ca->ConnectTree("Segment Tree"); Int_t nrows=Int_t(ca->GetTree()->GetEntries()); for (Int_t n=0; n<nrows; n++) { AliSegmentID *s=ca->LoadEntry(n); Int_t sec,row; digp->AdjustSectorRow(s->GetID(),sec,row); AliTPCClustersRow &clrow = *ca->GetRow(sec,row); Int_t ncl=clrow.GetArray()->GetEntriesFast(); while (ncl--) { AliTPCcluster *c=(AliTPCcluster*)clrow[ncl]; Int_t lab=c->GetLabel(0); if (lab<0) continue; //noise cluster lab=TMath::Abs(lab); if (sec>=digp->GetNInnerSector()) if (row==nrow_up-1 ) good[lab]|=0x1000; if (sec>=digp->GetNInnerSector()) if (row==nrow_up-1-gap) good[lab]|=0x800; good[lab]++; } ca->ClearRow(sec,row); } cf->Close(); } break; case 2: TD=(TTree*)gDirectory->Get("TreeD_75x40_100x60"); TD->GetBranch("Segment")->SetAddress(&digits); count = new Int_t[np]; Int_t i; for (i=0; i<np; i++) count[i]=0; Int_t sectors_by_rows=(Int_t)TD->GetEntries(); for (i=0; i<sectors_by_rows; i++) { if (!TD->GetEvent(i)) continue; Int_t sec,row; digp->AdjustSectorRow(digits->GetID(),sec,row); cerr<<sec<<' '<<row<<" \r"; digits->First(); while (digits->Next()) { Int_t it=digits->CurrentRow(), ip=digits->CurrentColumn(); Short_t dig = digits->GetDigit(it,ip); Int_t idx0=digits->GetTrackID(it,ip,0); Int_t idx1=digits->GetTrackID(it,ip,1); Int_t idx2=digits->GetTrackID(it,ip,2); if (idx0>=0 && dig>=zero) count[idx0]+=1; if (idx1>=0 && dig>=zero) count[idx1]+=1; if (idx2>=0 && dig>=zero) count[idx2]+=1; } for (Int_t j=0; j<np; j++) { if (count[j]>1) { if (sec>=digp->GetNInnerSector()) if (row==nrow_up-1 ) good[j]|=0x1000; if (sec>=digp->GetNInnerSector()) if (row==nrow_up-1-gap) good[j]|=0x800; good[j]++; } count[j]=0; } } delete[] count; break; default: cerr<<"Invalid TPC version !\n"; file->Close(); exit(7); } TTree *TH=gAlice->TreeH(); //TClonesArray *hits=TPC->Hits(); Int_t npart=TH->GetEntries(); while (npart--) { AliTPChit *hit0=0; TPC->ResetHits(); TH->GetEvent(npart); AliTPChit *hit = (AliTPChit*) TPC->FirstHit(-1); while(hit) { if(hit->fQ==0.) break; hit = (AliTPChit*) TPC->NextHit(); } if(hit) { hit0 = new AliTPChit(*hit); // Make copy of hit hit=hit0; } else continue; AliTPChit *hit1=(AliTPChit*) TPC->NextHit(); if(hit1==0) continue; if (hit1->fQ != 0.) continue; // Int_t i=hit->fTrack; Int_t i=hit->Track(); //TParticle *p = (TParticle*)particles->UncheckedAt(i); TParticle *p = (TParticle*)gAlice->Particle(i); //mod. secondonew //AliTPCcomaprison if (p->GetFirstMother()>=0) continue; //secondary particle if (good[i] < 0x1000+0x800+2+good_number) continue; if (p->Pt()<0.100) continue; if (TMath::Abs(p->Pz()/p->Pt())>0.999) continue; gt[nt].lab=i; gt[nt].code=p->GetPdgCode(); //**** px py pz - in global coordinate system, x y z - in local ! // gt[nt].px=hit->fX; gt[nt].py=hit->fY; gt[nt].pz=hit->fZ; //modificato tenendo conto di AliTPCComparison gt[nt].px=hit->X(); gt[nt].py=hit->Y(); gt[nt].pz=hit->Z(); Float_t cs,sn; digp->AdjustCosSin(hit1->fSector,cs,sn); //gt[nt].x = hit1->fX*cs + hit1->fY*sn; // gt[nt].y =-hit1->fX*sn + hit1->fY*cs; //modificato tenedo conto di AliTPCComaprison //gt[nt].z = hit1->fZ; gt[nt].x = hit1->X()*cs + hit1->Y()*sn; gt[nt].y =-hit1->X()*sn + hit1->Y()*cs; gt[nt].z = hit1->Z(); gt[nt].pxg = p->Px(); gt[nt].pyg = p->Py(); gt[nt].pzg = p->Pz(); gt[nt].ptg = p->Pt(); gt[nt].flag = 0; nt++; if(hit0) delete hit0; cerr<<i<<" \r"; if (nt==max) {cerr<<"Too many good tracks !\n"; break;} } delete[] good; printf("before delete gAlice\n"); delete gAlice; gAlice=0; printf("after delete gAlice\n"); file->Close(); printf("after file close\n"); return nt; } //-------------------------------------- <commit_msg>Delete gAlice commented to be consistent with the TPC<commit_after>struct GoodTrack { Int_t lab; Int_t code; Float_t px,py,pz; Float_t x,y,z; Float_t pxg,pyg,pzg,ptg; Bool_t flag; }; Int_t good_tracks(GoodTrack *gt, Int_t max); Int_t TPCtracks() { Int_t i; cerr<<"Doing comparison...\n"; // Connect the Root Galice file containing Geometry, Kine and Hits TFile *cf=TFile::Open("AliTPCclusters.root"); if (!cf->IsOpen()) {cerr<<"Can't open AliTPCclusters.root !\n"; return 1;} AliTPCParam *digp= (AliTPCParam*)cf->Get("75x40_100x60"); if (!digp) { cerr<<"TPC parameters have not been found !\n"; return 2; } // Load clusters AliTPCClustersArray *ca=new AliTPCClustersArray; ca->Setup(digp); ca->SetClusterType("AliTPCcluster"); ca->ConnectTree("Segment Tree"); Int_t nentr=Int_t(ca->GetTree()->GetEntries()); for (Int_t i=0; i<nentr; i++) { ca->LoadEntry(i); } // Load tracks TFile *tf=TFile::Open("AliTPCtracks.root"); if (!tf->IsOpen()) {cerr<<"Can't open AliTPCtracks.root !\n"; return 3;} TObjArray tarray(2000); TTree *tracktree=(TTree*)tf->Get("TreeT"); TBranch *tbranch=tracktree->GetBranch("tracks"); nentr=(Int_t)tracktree->GetEntries(); for (i=0; i<nentr; i++) { AliTPCtrack *iotrack=new AliTPCtrack; tbranch->SetAddress(&iotrack); tracktree->GetEvent(i); iotrack->CookLabel(ca); tarray.AddLast(iotrack); } tf->Close(); delete ca; cf->Close(); //printf("after cf close\n"); cerr<<"Number of found tracks "<<nentr<<endl; tarray.Sort(); TFile *pfile = new TFile("tpctracks.root","RECREATE"); TTree tracktree1("TreeT","Tree with TPC tracks"); AliTPCtrack *iotrack=0; tracktree1.Branch("tracks","AliTPCtrack",&iotrack,32000,0); for (i=0; i<nentr; i++) { iotrack=(AliTPCtrack*)tarray.UncheckedAt(i); tracktree1.Fill(); } tracktree1.Write(); pfile->Close(); tarray.Clear(); ///////////////////////////////////////////////////////////////////////// GoodTrack gt[15000]; Int_t ngood=0; cerr<<"Marking good tracks (this will take a while)...\n"; ngood=good_tracks(gt,15000); ofstream out("good_tracks"); if (out) { for (Int_t ngd=0; ngd<ngood; ngd++) out<<gt[ngd].lab<<' '<<gt[ngd].code<<' ' <<gt[ngd].px <<' '<<gt[ngd].py<<' '<<gt[ngd].pz<<' ' <<gt[ngd].x <<' '<<gt[ngd].y <<' '<<gt[ngd].z <<' ' <<gt[ngd].pxg <<' '<<gt[ngd].pyg <<' '<<gt[ngd].pzg <<' ' <<gt[ngd].ptg <<gt[ngd].flag<<endl; } else cerr<<"Can not open file (good_tracks) !\n"; out.close(); cerr<<"Number of good tracks : "<<ngood<<endl; printf("before return in tpctracks\n"); return 0; } //--------------------------------- Int_t good_tracks(GoodTrack *gt, Int_t max) { Int_t nt=0; //TFile *file=TFile::Open("rfio:galice.root"); // via server TFile *file=TFile::Open("galice.root"); if (!file->IsOpen()) {cerr<<"Can't open galice.root !\n"; exit(4);} if (!(gAlice=(AliRun*)file->Get("gAlice"))) { cerr<<"gAlice have not been found on galice.root !\n"; exit(5); } gAlice->GetEvent(0); AliTPC *TPC=(AliTPC*)gAlice->GetDetector("TPC"); Int_t ver = TPC->IsVersion(); cerr<<"TPC version "<<ver<<" has been found !\n"; AliTPCParam *digp=(AliTPCParam*)file->Get("75x40_100x60"); if (!digp) { cerr<<"TPC parameters have not been found !\n"; exit(6); } TPC->SetParam(digp); Int_t nrow_up=digp->GetNRowUp(); Int_t nrows=digp->GetNRowLow()+nrow_up; Int_t zero=digp->GetZeroSup(); Int_t gap=Int_t(0.125*nrows); Int_t good_number=Int_t(0.4*nrows); TObjArray *particles=gAlice->Particles(); //Int_t np=particles->GetEntriesFast(); Int_t np=gAlice->GetNtrack(); //FCA correction Int_t *good=new Int_t[np]; for (Int_t ii=0; ii<np; ii++) good[ii]=0; //MI change to be possible compile macro //definition out of the switch statement Int_t sectors_by_rows=0; TTree *TD=0; AliSimDigits da, *digits=&da; Int_t *count=0; switch (ver) { case 1: { TFile *cf=TFile::Open("AliTPCclusters.root"); if (!cf->IsOpen()){cerr<<"Can't open AliTPCclusters.root !\n";exit(5);} AliTPCClustersArray *ca=new AliTPCClustersArray; ca->Setup(digp); ca->SetClusterType("AliTPCcluster"); ca->ConnectTree("Segment Tree"); Int_t nrows=Int_t(ca->GetTree()->GetEntries()); for (Int_t n=0; n<nrows; n++) { AliSegmentID *s=ca->LoadEntry(n); Int_t sec,row; digp->AdjustSectorRow(s->GetID(),sec,row); AliTPCClustersRow &clrow = *ca->GetRow(sec,row); Int_t ncl=clrow.GetArray()->GetEntriesFast(); while (ncl--) { AliTPCcluster *c=(AliTPCcluster*)clrow[ncl]; Int_t lab=c->GetLabel(0); if (lab<0) continue; //noise cluster lab=TMath::Abs(lab); if (sec>=digp->GetNInnerSector()) if (row==nrow_up-1 ) good[lab]|=0x1000; if (sec>=digp->GetNInnerSector()) if (row==nrow_up-1-gap) good[lab]|=0x800; good[lab]++; } ca->ClearRow(sec,row); } cf->Close(); } break; case 2: TD=(TTree*)gDirectory->Get("TreeD_75x40_100x60"); TD->GetBranch("Segment")->SetAddress(&digits); count = new Int_t[np]; Int_t i; for (i=0; i<np; i++) count[i]=0; Int_t sectors_by_rows=(Int_t)TD->GetEntries(); for (i=0; i<sectors_by_rows; i++) { if (!TD->GetEvent(i)) continue; Int_t sec,row; digp->AdjustSectorRow(digits->GetID(),sec,row); cerr<<sec<<' '<<row<<" \r"; digits->First(); while (digits->Next()) { Int_t it=digits->CurrentRow(), ip=digits->CurrentColumn(); Short_t dig = digits->GetDigit(it,ip); Int_t idx0=digits->GetTrackID(it,ip,0); Int_t idx1=digits->GetTrackID(it,ip,1); Int_t idx2=digits->GetTrackID(it,ip,2); if (idx0>=0 && dig>=zero) count[idx0]+=1; if (idx1>=0 && dig>=zero) count[idx1]+=1; if (idx2>=0 && dig>=zero) count[idx2]+=1; } for (Int_t j=0; j<np; j++) { if (count[j]>1) { if (sec>=digp->GetNInnerSector()) if (row==nrow_up-1 ) good[j]|=0x1000; if (sec>=digp->GetNInnerSector()) if (row==nrow_up-1-gap) good[j]|=0x800; good[j]++; } count[j]=0; } } delete[] count; break; default: cerr<<"Invalid TPC version !\n"; file->Close(); exit(7); } TTree *TH=gAlice->TreeH(); //TClonesArray *hits=TPC->Hits(); Int_t npart=TH->GetEntries(); while (npart--) { AliTPChit *hit0=0; TPC->ResetHits(); TH->GetEvent(npart); AliTPChit *hit = (AliTPChit*) TPC->FirstHit(-1); while(hit) { if(hit->fQ==0.) break; hit = (AliTPChit*) TPC->NextHit(); } if(hit) { hit0 = new AliTPChit(*hit); // Make copy of hit hit=hit0; } else continue; AliTPChit *hit1=(AliTPChit*) TPC->NextHit(); if(hit1==0) continue; if (hit1->fQ != 0.) continue; // Int_t i=hit->fTrack; Int_t i=hit->Track(); //TParticle *p = (TParticle*)particles->UncheckedAt(i); TParticle *p = (TParticle*)gAlice->Particle(i); //mod. secondonew //AliTPCcomaprison if (p->GetFirstMother()>=0) continue; //secondary particle if (good[i] < 0x1000+0x800+2+good_number) continue; if (p->Pt()<0.100) continue; if (TMath::Abs(p->Pz()/p->Pt())>0.999) continue; gt[nt].lab=i; gt[nt].code=p->GetPdgCode(); //**** px py pz - in global coordinate system, x y z - in local ! // gt[nt].px=hit->fX; gt[nt].py=hit->fY; gt[nt].pz=hit->fZ; //modificato tenendo conto di AliTPCComparison gt[nt].px=hit->X(); gt[nt].py=hit->Y(); gt[nt].pz=hit->Z(); Float_t cs,sn; digp->AdjustCosSin(hit1->fSector,cs,sn); //gt[nt].x = hit1->fX*cs + hit1->fY*sn; // gt[nt].y =-hit1->fX*sn + hit1->fY*cs; //modificato tenedo conto di AliTPCComaprison //gt[nt].z = hit1->fZ; gt[nt].x = hit1->X()*cs + hit1->Y()*sn; gt[nt].y =-hit1->X()*sn + hit1->Y()*cs; gt[nt].z = hit1->Z(); gt[nt].pxg = p->Px(); gt[nt].pyg = p->Py(); gt[nt].pzg = p->Pz(); gt[nt].ptg = p->Pt(); gt[nt].flag = 0; nt++; if(hit0) delete hit0; cerr<<i<<" \r"; if (nt==max) {cerr<<"Too many good tracks !\n"; break;} } delete[] good; printf("before delete gAlice\n"); //delete gAlice; gAlice=0; printf("after delete gAlice\n"); file->Close(); printf("after file close\n"); return nt; } //-------------------------------------- <|endoftext|>
<commit_before>#include "sctfile.h" #include <iostream> #include <string> #include <sstream> #include <vector> #include <fstream> #include <map> SctFile::SctFile(std::string filename) { std::string line; std::ifstream myfile (filename); if (myfile.is_open()) { // read in file into chunk getline(myfile, line); while (getline (myfile, line)) { this->file_chunk.push_back(line); } myfile.close(); // extract out relations from chunk for (std::vector<std::string>::iterator it = file_chunk.begin(); it != file_chunk.end(); ++it) { std::vector<std::string> temp_token_vec; std::istringstream iss(*it); std::string token; while (std::getline(iss, token, '\t')){ temp_token_vec.push_back(token); } if (temp_token_vec[2] == "1" && temp_token_vec[7] == "116680003") { this->relations.push_back(temp_token_vec[4] + "," + temp_token_vec[5]); } } // extract nodes from relations std::cout << this->relations.size() << std::endl; } else { std::cout << "Unable to open file"; } } std::vector<std::string> SctFile::GetNodes() { std::vector<std::string> res; std::for_each(file_chunk.begin(), file_chunk.end(), [](std::string const& line) { std::istringstream iss(line); std::string token; while (std::getline(iss, token, '\t')){ std::cout << token << "|"; } }); return res; } std::vector<std::string> SctFile::GetRelations() { std::vector<std::string> res; for (std::vector<std::string>::iterator it = file_chunk.begin(); it != file_chunk.end(); ++it) { std::vector<std::string> temp_token_vec; std::istringstream iss(*it); std::string token; while (std::getline(iss, token, '\t')){ temp_token_vec.push_back(token); } if (temp_token_vec[2] == "1" && temp_token_vec[7] == "116680003") { res.push_back(temp_token_vec[4] + "," + temp_token_vec[5]); } } this->relations = res; return res; }<commit_msg>put extract nodes and relations function in constructor<commit_after>#include "sctfile.h" #include <iostream> #include <string> #include <sstream> #include <vector> #include <fstream> #include <map> #include <set> SctFile::SctFile(std::string filename) { std::string line; std::ifstream myfile (filename); if (myfile.is_open()) { // read in file into chunk getline(myfile, line); while (getline (myfile, line)) { this->file_chunk.push_back(line); } myfile.close(); std::set<std::string> temp_nodes; // extract out relations from chunk for (std::vector<std::string>::iterator it = file_chunk.begin(); it != file_chunk.end(); ++it) { std::vector<std::string> temp_token_vec; std::istringstream iss(*it); std::string token; while (std::getline(iss, token, '\t')){ temp_token_vec.push_back(token); } if (temp_token_vec[2] == "1" && temp_token_vec[7] == "116680003") { temp_nodes.insert(temp_token_vec[4]); temp_nodes.insert(temp_token_vec[5]); this->relations.push_back(temp_token_vec[4] + "," + temp_token_vec[5]); } } // extract nodes from relations std::cout << temp_nodes.size() << std::endl; } else { std::cout << "Unable to open file"; } } std::vector<std::string> SctFile::GetNodes() { std::vector<std::string> res; std::for_each(file_chunk.begin(), file_chunk.end(), [](std::string const& line) { std::istringstream iss(line); std::string token; while (std::getline(iss, token, '\t')){ std::cout << token << "|"; } }); return res; } std::vector<std::string> SctFile::GetRelations() { std::vector<std::string> res; for (std::vector<std::string>::iterator it = file_chunk.begin(); it != file_chunk.end(); ++it) { std::vector<std::string> temp_token_vec; std::istringstream iss(*it); std::string token; while (std::getline(iss, token, '\t')){ temp_token_vec.push_back(token); } if (temp_token_vec[2] == "1" && temp_token_vec[7] == "116680003") { res.push_back(temp_token_vec[4] + "," + temp_token_vec[5]); } } this->relations = res; return res; }<|endoftext|>
<commit_before>#include <cstdio> #include <upcxx.h> #include "convergent_matrix.hpp" // global matrix dimensions #define M 2000 #define N 1000 // block-cyclic distribution #define NPCOL 2 #define NPROW 2 #define MB 64 #define NB 64 #define LLD 1024 // convenient typedef for distributed matrix typedef cm::ConvergentMatrix<float, NPROW, NPCOL, MB, NB, LLD> cm_t; /** * A simple example of some ConvergentMatrix functionality */ void simple() { // initialize the distributed matrix abstraction cm_t dist_mat( M, N ); // optional: turn on replicated consistency checks (run during commit) // * requires enough memory to replicate the entire matrix to all threads // * requires a working MPI implementation dist_mat.consistency_check_on(); // create and apply an update ... { // generate leading and trailing dimension indexing long ixs[] = { 0, 100, 1000, 1500 }, jxs[] = { 0, 300, 600 }; // generate matrix slice // indexing arrays above map into the global distributed matrix cm::LocalMatrix<float> A( 4, 3 ); A = 1.0; // arbitrarily setting all elements to 1.0 // apply the update (A may be destroyed when update() returns) dist_mat.update( &A, ixs, jxs ); } // commit all updates dist_mat.commit(); // get a raw pointer to local storage // * freed when dist_mat destroyed float * data_ptr = dist_mat.get_local_data(); printf( "[%s] thread %3i : data_ptr[0] = %f\n", __func__, MYTHREAD, data_ptr[0] ); // fetch the value at global index ( 0, 0 ) // * should match data_ptr[0] on thread 0 printf( "[%s] thread %3i : dist_mat(0, 0) = %f\n", __func__, MYTHREAD, dist_mat( 0, 0 ) ); // sync before dist_mat goes out of scope and is destroyed upcxx::barrier(); } int main( int argc, char **argv ) { // initialize upcxx upcxx::init( &argc, &argv ); // run the example above simple(); // shut down upcxx upcxx::finalize(); } <commit_msg>Further tweaks to simple.cpp comments<commit_after>#include <cstdio> #include <upcxx.h> #include "convergent_matrix.hpp" // global matrix dimensions #define M 2000 #define N 1000 // block-cyclic distribution #define NPCOL 2 #define NPROW 2 #define MB 64 #define NB 64 #define LLD 1024 // convenient typedef for the distributed matrix class typedef cm::ConvergentMatrix<float, NPROW, NPCOL, MB, NB, LLD> cmat_t; /** * A small example of some basic ConvergentMatrix functionality * * Must be run on 4 threads using the appropriate command (mpirun, aprun, etc.) * for the environment and GASNet conduit. */ void simple() { // initialize the distributed matrix abstraction cmat_t dist_mat( M, N ); // optional: turn on replicated consistency checks (run during commit) // * requires enough memory to replicate the entire matrix to all threads // * requires a working MPI implementation dist_mat.consistency_check_on(); // create and apply an update ... { // generate leading and trailing dimension indexing long ixs[] = { 0, 100, 1000, 1500 }, jxs[] = { 0, 300, 600 }; // generate matrix slice // indexing arrays above map into the global distributed matrix cm::LocalMatrix<float> A( 4, 3 ); A = 1.0; // arbitrarily setting all elements to 1.0 // apply the update (A may be destroyed when update() returns) dist_mat.update( &A, ixs, jxs ); } // commit all updates dist_mat.commit(); // get a raw pointer to local storage // * freed when dist_mat destroyed float * data_ptr = dist_mat.get_local_data(); printf( "[%s] thread %3i : data_ptr[0] = %f\n", __func__, MYTHREAD, data_ptr[0] ); // fetch the value at global index ( 0, 0 ) // * should match data_ptr[0] on thread 0 printf( "[%s] thread %3i : dist_mat(0, 0) = %f\n", __func__, MYTHREAD, dist_mat( 0, 0 ) ); // sync before dist_mat goes out of scope and is destroyed upcxx::barrier(); } int main( int argc, char **argv ) { // initialize upcxx upcxx::init( &argc, &argv ); // run the example above simple(); // shut down upcxx upcxx::finalize(); } <|endoftext|>
<commit_before>/* Reproducing xfstest generic/322 _write_after_fsync_rename_test 1. Create file foo and write some contents into it and do fsync 2. Write some more contents into different offset and do sync_range 3. Rename foo to bar and do fsync After a crash at random point, bar should be present and should have the same contents written to foo. https://github.com/kdave/xfstests/blob/master/tests/generic/322 */ #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <string> #include <iostream> #include <dirent.h> #include <cstring> #include <errno.h> #include "BaseTestCase.h" #include "../user_tools/api/workload.h" #include "../user_tools/api/actions.h" #define TEST_FILE_FOO "foo" #define TEST_FILE_FOO_BACKUP "foo_backup" #define TEST_FILE_BAR "bar" #define TEST_DIR_A "test_dir_a" using fs_testing::tests::DataTestResult; using fs_testing::user_tools::api::WriteData; using fs_testing::user_tools::api::WriteDataMmap; using fs_testing::user_tools::api::Checkpoint; using std::string; #define TEST_FILE_PERMS ((mode_t) (S_IRWXU | S_IRWXG | S_IRWXO)) namespace fs_testing { namespace tests { class Generic322_2: public BaseTestCase { public: virtual int setup() override { init_paths(); // Create test directory A. string dir_path = mnt_dir_ + "/" TEST_DIR_A; int res = mkdir(dir_path.c_str(), 0777); if (res < 0) { return -1; } //Create file foo in TEST_DIR_A const int fd_foo = open(foo_path.c_str(), O_RDWR | O_CREAT, TEST_FILE_PERMS); if (fd_foo < 0) { return -1; } const int fd_foo_backup = open(foo_backup_path.c_str(), O_RDWR | O_CREAT, TEST_FILE_PERMS); if (fd_foo_backup < 0) { return -1; } // Write some contents to the file if (WriteData(fd_foo, 0, 1024) < 0) { return -2; } // Write some contents to the backup file (for verifying md5sum in check_test) if (WriteData(fd_foo_backup, 0, 1024) < 0) { return -2; } // Sync the file and backup file if (fsync(fd_foo) < 0) { return -1; } if (fsync(fd_foo_backup) < 0) { return -1; } // write more contents in a different offset if (WriteData(fd_foo, 1024, 2048) < 0) { return -2; } if (WriteData(fd_foo_backup, 1024, 2048) < 0) { return -2; } // sync range the foo file if (sync_file_range(fd_foo, 1024, 2048, 0) < 0) { return -3; } // fsync the entire backup file if (fsync(fd_foo_backup) < 0) { return -1; } close(fd_foo); close(fd_foo_backup); return 0; } virtual int run() override { init_paths(); // Rename the foo to bar if (rename(foo_path.c_str(), bar_path.c_str()) != 0) { return -2; } const int fd_bar = open(bar_path.c_str(), O_RDWR | O_CREAT, TEST_FILE_PERMS); if (fd_bar < 0) { return -3; } if (fsync(fd_bar) < 0) { return -4; } if (Checkpoint() < 0){ return -5; } //Close open files close(fd_bar); return 0; } virtual int check_test(unsigned int last_checkpoint, DataTestResult *test_result) override { init_paths(); const int fd_bar = open(bar_path.c_str(), O_RDONLY, TEST_FILE_PERMS); const int fd_foo = open(foo_path.c_str(), O_RDONLY, TEST_FILE_PERMS); if (fd_bar >= 0 && fd_foo >= 0) { test_result->SetError(DataTestResult::kOldFilePersisted); test_result->error_description = " : Both old and new files present after crash recovery"; close(fd_bar); close(fd_foo); return 0; } if (fd_bar < 0 && fd_foo < 0) { test_result->SetError(DataTestResult::kFileMissing); test_result->error_description = " : Both old and new files are missing after crash recovery"; return 0; } if (fd_foo >= 0) { close(fd_foo); } if (fd_bar < 0 && last_checkpoint >= 1) { test_result->SetError(DataTestResult::kFileMissing); test_result->error_description = " : Unable to locate bar file after crash recovery"; return 0; } string expected_md5sum = get_md5sum(foo_backup_path); string actual_md5sum = get_md5sum(bar_path); if (expected_md5sum.compare(actual_md5sum) != 0 && last_checkpoint >= 1) { test_result->SetError(DataTestResult::kFileDataCorrupted); test_result->error_description = " : md5sum of bar does not match with expected md5sum of foo backup"; } if (fd_bar >= 0) { close(fd_bar); } return 0; } private: string foo_path; string foo_backup_path; string bar_path; void init_paths() { foo_path = mnt_dir_ + "/" TEST_DIR_A "/" TEST_FILE_FOO; foo_backup_path = mnt_dir_ + "/" TEST_DIR_A "/" TEST_FILE_FOO_BACKUP; bar_path = mnt_dir_ + "/" TEST_DIR_A "/" TEST_FILE_BAR; } string get_md5sum(string file_name) { FILE *fp; string command = "md5sum " + file_name; fp = popen(command.c_str(), "r"); char md5[100]; fscanf(fp,"%s", md5); fclose(fp); string md5_str(md5); return md5_str; } }; } // namespace tests } // namespace fs_testing extern "C" fs_testing::tests::BaseTestCase *test_case_get_instance() { return new fs_testing::tests::Generic322_2; } extern "C" void test_case_delete_instance(fs_testing::tests::BaseTestCase *tc) { delete tc; } <commit_msg>Making the write offsets multiple of 4K in generic 322_2<commit_after>/* Reproducing xfstest generic/322 _write_after_fsync_rename_test 1. Create file foo and write some contents into it and do fsync 2. Write some more contents into different offset and do sync_range 3. Rename foo to bar and do fsync After a crash at random point, bar should be present and should have the same contents written to foo. https://github.com/kdave/xfstests/blob/master/tests/generic/322 */ #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include <string> #include <iostream> #include <dirent.h> #include <cstring> #include <errno.h> #include "BaseTestCase.h" #include "../user_tools/api/workload.h" #include "../user_tools/api/actions.h" #define TEST_FILE_FOO "foo" #define TEST_FILE_FOO_BACKUP "foo_backup" #define TEST_FILE_BAR "bar" #define TEST_DIR_A "test_dir_a" using fs_testing::tests::DataTestResult; using fs_testing::user_tools::api::WriteData; using fs_testing::user_tools::api::WriteDataMmap; using fs_testing::user_tools::api::Checkpoint; using std::string; #define TEST_FILE_PERMS ((mode_t) (S_IRWXU | S_IRWXG | S_IRWXO)) namespace fs_testing { namespace tests { class Generic322_2: public BaseTestCase { public: virtual int setup() override { init_paths(); // Create test directory A. string dir_path = mnt_dir_ + "/" TEST_DIR_A; int res = mkdir(dir_path.c_str(), 0777); if (res < 0) { return -1; } //Create file foo in TEST_DIR_A const int fd_foo = open(foo_path.c_str(), O_RDWR | O_CREAT, TEST_FILE_PERMS); if (fd_foo < 0) { return -1; } const int fd_foo_backup = open(foo_backup_path.c_str(), O_RDWR | O_CREAT, TEST_FILE_PERMS); if (fd_foo_backup < 0) { return -1; } // Write some contents to the file if (WriteData(fd_foo, 0, 4096) < 0) { return -2; } // Write some contents to the backup file (for verifying md5sum in check_test) if (WriteData(fd_foo_backup, 0, 4096) < 0) { return -2; } // Sync the file and backup file if (fsync(fd_foo) < 0) { return -1; } if (fsync(fd_foo_backup) < 0) { return -1; } // write more contents in a different offset if (WriteData(fd_foo, 4096, 4096) < 0) { return -2; } if (WriteData(fd_foo_backup, 4096, 4096) < 0) { return -2; } // sync range the foo file if (sync_file_range(fd_foo, 4096, 4096, 0) < 0) { return -3; } // fsync the entire backup file if (fsync(fd_foo_backup) < 0) { return -1; } close(fd_foo); close(fd_foo_backup); return 0; } virtual int run() override { init_paths(); // Rename the foo to bar if (rename(foo_path.c_str(), bar_path.c_str()) != 0) { return -2; } const int fd_bar = open(bar_path.c_str(), O_RDWR | O_CREAT, TEST_FILE_PERMS); if (fd_bar < 0) { return -3; } if (fsync(fd_bar) < 0) { return -4; } if (Checkpoint() < 0){ return -5; } //Close open files close(fd_bar); return 0; } virtual int check_test(unsigned int last_checkpoint, DataTestResult *test_result) override { init_paths(); const int fd_bar = open(bar_path.c_str(), O_RDONLY, TEST_FILE_PERMS); const int fd_foo = open(foo_path.c_str(), O_RDONLY, TEST_FILE_PERMS); if (fd_bar >= 0 && fd_foo >= 0) { test_result->SetError(DataTestResult::kOldFilePersisted); test_result->error_description = " : Both old and new files present after crash recovery"; close(fd_bar); close(fd_foo); return 0; } if (fd_bar < 0 && fd_foo < 0) { test_result->SetError(DataTestResult::kFileMissing); test_result->error_description = " : Both old and new files are missing after crash recovery"; return 0; } if (fd_foo >= 0) { close(fd_foo); } if (fd_bar < 0 && last_checkpoint >= 1) { test_result->SetError(DataTestResult::kFileMissing); test_result->error_description = " : Unable to locate bar file after crash recovery"; return 0; } string expected_md5sum = get_md5sum(foo_backup_path); string actual_md5sum = get_md5sum(bar_path); if (expected_md5sum.compare(actual_md5sum) != 0 && last_checkpoint >= 1) { test_result->SetError(DataTestResult::kFileDataCorrupted); test_result->error_description = " : md5sum of bar does not match with expected md5sum of foo backup"; } if (fd_bar >= 0) { close(fd_bar); } return 0; } private: string foo_path; string foo_backup_path; string bar_path; void init_paths() { foo_path = mnt_dir_ + "/" TEST_DIR_A "/" TEST_FILE_FOO; foo_backup_path = mnt_dir_ + "/" TEST_DIR_A "/" TEST_FILE_FOO_BACKUP; bar_path = mnt_dir_ + "/" TEST_DIR_A "/" TEST_FILE_BAR; } string get_md5sum(string file_name) { FILE *fp; string command = "md5sum " + file_name; fp = popen(command.c_str(), "r"); char md5[100]; fscanf(fp,"%s", md5); fclose(fp); string md5_str(md5); return md5_str; } }; } // namespace tests } // namespace fs_testing extern "C" fs_testing::tests::BaseTestCase *test_case_get_instance() { return new fs_testing::tests::Generic322_2; } extern "C" void test_case_delete_instance(fs_testing::tests::BaseTestCase *tc) { delete tc; } <|endoftext|>
<commit_before>#include <algorithm> #include <iostream> #include <unordered_set> #include <limits> #include "maxis/graph.hpp" #include "maxis/genetic.hpp" #include "maxis/solver.hpp" #include "maxis/rng.hpp" namespace maxis { // Brute Force Solver BruteForceMaxisSolver::BruteForceMaxisSolver(const Graph &g) : graph{g} {} // Ripple carry increment for a collection of bits. // Returns true on overflow. bool increment_bit_vector(BitVector &bv) { using std::begin; using std::end; bool carry = true; for (auto it = begin(bv); it != end(bv); ++it) { if (*it == 0){ *it = 1; carry = false; break; } else { *it = 0; } } return carry; } BitVector BruteForceMaxisSolver::operator()() { // max_weight tracks the current maximum weight int max_weight = 0; BitVector max_set; auto adjacency_matrix = graph.adjacency_matrix(); BitVector bv(graph.order(), 0); do { if (graph.is_independent_set(bv)) { auto weight = graph.weighted_total(bv); if (weight > max_weight) { max_weight = weight; max_set = bv; } } } while (increment_bit_vector(bv) == false); return max_set; } // Genetic Maxis Solver // The heuristic feasability operator ensures that genotypes created // from mutation and breeding are valid independent sets // TODO: use decltype as adj need not be a BitVector void heuristic_feasibility(size_t order, BitVector &adj, BitVector &chromosome) { using std::begin; using std::end; // Remove vertices until we have an independent set // it.first is the iterator over the adjacency matrix // it.second is the iterator over the set of vertices for (auto it = std::make_pair(begin(adj), begin(chromosome)); it.second != end(chromosome); it.first += order, ++it.second) { // If vertex is not selected, there is no conflict if (!*it.second) { continue; } // Delete all vertices that are in the set and neighbors of the // vertex which is currently being processed // TODO: change to std::rbegin() when gcc supports it BitVector::reverse_iterator rit{std::next(it.first, order)}; for (auto jt = std::make_pair(rit, chromosome.rbegin()); jt.second != chromosome.rend(); ++jt.first, ++jt.second) { if (*jt.first) { *jt.second = 0; } } } // Add back vertices to fill empty spaces for (auto it = std::make_pair(begin(adj), begin(chromosome)); it.second != end(chromosome); it.first += order, ++it.second) { if (*it.second) { continue; } if(std::inner_product(begin(chromosome), end(chromosome), it.first, 0) == 0) { *it.second = 1; } } } // initialize_set is used to generate the initial population with valid // independent sets on the graph void initialize_set(size_t order, BitVector &adj, BitVector &chromosome) { using std::begin; using std::end; static RNG rng; BitVector cover(order, 0); std::fill(begin(chromosome), end(chromosome), 0); auto uncovered_cnt = order; // Randomly select a set of vertices that completely cover the // graph while (uncovered_cnt > 0) { // Pick an uncovered vertex at random size_t skips = rng.random_index(0, uncovered_cnt - 1); size_t dist = 0; auto it = begin(cover); for (; it != end(cover); ++it) { if (*it == 0 && skips-- == 0) { dist = std::distance(begin(cover), it); *it = 1; break; } } // Select it and mark all of its neighbors as covered chromosome[dist] = 1; --uncovered_cnt; for (auto i = begin(cover), j = begin(adj) + dist*order; i != end(cover); ++i, ++j) { if (*j != 0 && *i == 0) { *i = 1; if (--uncovered_cnt == 0) { break; } } } } } GeneticMaxisSolver::GeneticMaxisSolver( const Graph &g, genetic::Selector &sel, genetic::Recombinator &rec, genetic::Mutator &mut ) : graph{g}, selector{sel}, recombinator{rec}, mutator{mut} { using std::begin; using std::end; size = graph.order() / 2; // Reorder graph by sorting vertices by (weight / degree) permutation.resize(graph.order()); std::iota(begin(permutation), end(permutation), 0); auto &weights = graph.weights; auto &adj = graph.adjacency_list; std::sort(begin(permutation), end(permutation), [&weights, &adj](size_t i, size_t j) { return weights[i] / adj[i].size() > weights[j] / adj[j].size(); }); graph.reorder(permutation); } BitVector GeneticMaxisSolver::operator()() { using std::begin; using std::end; auto order = graph.order(); auto adj = graph.adjacency_matrix(); genetic::AlgorithmState state; // Keep a hash table to check for duplicate chromosomes auto hash_func = [](BitVector *chromosome) { return std::hash<std::vector<bool>>()(*chromosome); }; auto eq_func = [](BitVector *lhs, BitVector *rhs) { return std::equal(begin(*lhs), end(*lhs), begin(*rhs)); }; std::unordered_set<BitVector*, decltype(hash_func), decltype(eq_func)> dupes(size, hash_func, eq_func); // Generate the initial population std::vector<BitVector> chromosomes; std::vector<genetic::Phenotype> pop; pop.reserve(size); chromosomes.reserve(size); for (decltype(size) i = 0; i < size; ++i) { chromosomes.emplace_back(order); pop.emplace_back(&chromosomes[i]); do { initialize_set(order, adj, chromosomes[i]); } while (dupes.insert(&chromosomes[i]).second == false); pop[i].fitness = graph.weighted_total(*pop[i].chromosome); } // Sort population by fitness and initialize state information std::sort(begin(pop), end(pop)); state.min_fitness = begin(pop)->fitness; state.max_fitness = end(pop)->fitness; state.total_fitness = std::accumulate( begin(pop), end(pop), 0.0, [](double acc, genetic::Phenotype &ph) { return acc + ph.fitness; } ); state.adjusted_fitness = state.total_fitness - state.min_fitness * size; // TODO: parallelize while (state.max_fitness < constraint) { // Select the weakest member of the population to be replaced auto &child = *begin(pop); dupes.erase(child.chromosome); do { // Select two parents for breeding and store the result into the // child, while ensuring that the newly created child is unique recombinator.breed( state, selector.select(state, begin(pop), end(pop)), selector.select(state, begin(pop), end(pop)), child ); mutator.mutate(state, child); heuristic_feasibility(order, adj, *child.chromosome); } while (dupes.insert(child.chromosome).second == false); // Calculate fitness of new population member and update the // total fitness state.total_fitness -= child.fitness; auto child_fitness = child.fitness = graph.weighted_total(*child.chromosome); state.total_fitness += child_fitness; // Log fitness info if (child_fitness > state.max_fitness) { state.max_fitness = child_fitness; std::cout << "Best independent set (" << state.max_fitness << "): " << std::endl; } // Insert new child into sorted position and update algorithm state for (auto it = std::next(begin(pop)); it != end(pop) && it->fitness <= child_fitness; ++it) { std::swap(*it, *std::prev(it)); } state.min_fitness = begin(pop)->fitness; state.adjusted_fitness = state.total_fitness - state.min_fitness * size; ++state.iterations; if ((state.iterations & 0x3ff) == 0) { std::cout << "Iterations: " << state.iterations << "; Average Fitness: " << state.total_fitness / size << std::endl; } } auto max = std::prev(end(pop)); BitVector result(order); for (size_t i = 0; i < order; ++i) { result[permutation[i]] = (*max->chromosome)[i]; } return result; } } // namespace maxis <commit_msg>Use forward iteration in the heuristic feasibility operator<commit_after>#include <algorithm> #include <iostream> #include <unordered_set> #include <limits> #include "maxis/graph.hpp" #include "maxis/genetic.hpp" #include "maxis/solver.hpp" #include "maxis/rng.hpp" namespace maxis { // Brute Force Solver BruteForceMaxisSolver::BruteForceMaxisSolver(const Graph &g) : graph{g} {} // Ripple carry increment for a collection of bits. // Returns true on overflow. bool increment_bit_vector(BitVector &bv) { using std::begin; using std::end; bool carry = true; for (auto it = begin(bv); it != end(bv); ++it) { if (*it == 0){ *it = 1; carry = false; break; } else { *it = 0; } } return carry; } BitVector BruteForceMaxisSolver::operator()() { // max_weight tracks the current maximum weight int max_weight = 0; BitVector max_set; auto adjacency_matrix = graph.adjacency_matrix(); BitVector bv(graph.order(), 0); do { if (graph.is_independent_set(bv)) { auto weight = graph.weighted_total(bv); if (weight > max_weight) { max_weight = weight; max_set = bv; } } } while (increment_bit_vector(bv) == false); return max_set; } // Genetic Maxis Solver // The heuristic feasability operator ensures that genotypes created // from mutation and breeding are valid independent sets // TODO: use decltype as adj need not be a BitVector void heuristic_feasibility(size_t order, BitVector &adj, BitVector &chromosome) { using std::begin; using std::end; // Remove vertices until we have an independent set // it.first is the iterator over the adjacency matrix // it.second is the iterator over the set of vertices for (auto it = std::make_pair(begin(adj), begin(chromosome)); it.second != end(chromosome); it.first += order, ++it.second) { // If vertex is not selected, there is no conflict if (!*it.second) { continue; } // Delete all vertices that are in the set and neighbors of the // vertex which is currently being processed for (auto jt = std::make_pair(std::next(it.first, std::distance(begin(chromosome), it.second)), it.second); jt.second != chromosome.end(); ++jt.first, ++jt.second) { if (*jt.first) { *jt.second = 0; } } } // Add back vertices to fill empty spaces for (auto it = std::make_pair(begin(adj), begin(chromosome)); it.second != end(chromosome); it.first += order, ++it.second) { if (*it.second) { continue; } if(std::inner_product(begin(chromosome), end(chromosome), it.first, 0) == 0) { *it.second = 1; } } } // initialize_set is used to generate the initial population with valid // independent sets on the graph void initialize_set(size_t order, BitVector &adj, BitVector &chromosome) { using std::begin; using std::end; static RNG rng; BitVector cover(order, 0); std::fill(begin(chromosome), end(chromosome), 0); auto uncovered_cnt = order; // Randomly select a set of vertices that completely cover the // graph while (uncovered_cnt > 0) { // Pick an uncovered vertex at random size_t skips = rng.random_index(0, uncovered_cnt - 1); size_t dist = 0; auto it = begin(cover); for (; it != end(cover); ++it) { if (*it == 0 && skips-- == 0) { dist = std::distance(begin(cover), it); *it = 1; break; } } // Select it and mark all of its neighbors as covered chromosome[dist] = 1; --uncovered_cnt; for (auto i = begin(cover), j = begin(adj) + dist*order; i != end(cover); ++i, ++j) { if (*j != 0 && *i == 0) { *i = 1; if (--uncovered_cnt == 0) { break; } } } } } GeneticMaxisSolver::GeneticMaxisSolver( const Graph &g, genetic::Selector &sel, genetic::Recombinator &rec, genetic::Mutator &mut ) : graph{g}, selector{sel}, recombinator{rec}, mutator{mut} { using std::begin; using std::end; size = graph.order() / 2; // Reorder graph by sorting vertices by (weight / degree) permutation.resize(graph.order()); std::iota(begin(permutation), end(permutation), 0); auto &weights = graph.weights; auto &adj = graph.adjacency_list; std::sort(begin(permutation), end(permutation), [&weights, &adj](size_t i, size_t j) { return weights[i] / adj[i].size() > weights[j] / adj[j].size(); }); graph.reorder(permutation); } BitVector GeneticMaxisSolver::operator()() { using std::begin; using std::end; auto order = graph.order(); auto adj = graph.adjacency_matrix(); genetic::AlgorithmState state; // Keep a hash table to check for duplicate chromosomes auto hash_func = [](BitVector *chromosome) { return std::hash<std::vector<bool>>()(*chromosome); }; auto eq_func = [](BitVector *lhs, BitVector *rhs) { return std::equal(begin(*lhs), end(*lhs), begin(*rhs)); }; std::unordered_set<BitVector*, decltype(hash_func), decltype(eq_func)> dupes(size, hash_func, eq_func); // Generate the initial population std::vector<BitVector> chromosomes; std::vector<genetic::Phenotype> pop; pop.reserve(size); chromosomes.reserve(size); for (decltype(size) i = 0; i < size; ++i) { chromosomes.emplace_back(order); pop.emplace_back(&chromosomes[i]); do { initialize_set(order, adj, chromosomes[i]); } while (dupes.insert(&chromosomes[i]).second == false); pop[i].fitness = graph.weighted_total(*pop[i].chromosome); } // Sort population by fitness and initialize state information std::sort(begin(pop), end(pop)); state.min_fitness = begin(pop)->fitness; state.max_fitness = end(pop)->fitness; state.total_fitness = std::accumulate( begin(pop), end(pop), 0.0, [](double acc, genetic::Phenotype &ph) { return acc + ph.fitness; } ); state.adjusted_fitness = state.total_fitness - state.min_fitness * size; // TODO: parallelize while (state.max_fitness < constraint) { // Select the weakest member of the population to be replaced auto &child = *begin(pop); dupes.erase(child.chromosome); do { // Select two parents for breeding and store the result into the // child, while ensuring that the newly created child is unique recombinator.breed( state, selector.select(state, begin(pop), end(pop)), selector.select(state, begin(pop), end(pop)), child ); mutator.mutate(state, child); heuristic_feasibility(order, adj, *child.chromosome); } while (dupes.insert(child.chromosome).second == false); // Calculate fitness of new population member and update the // total fitness state.total_fitness -= child.fitness; auto child_fitness = child.fitness = graph.weighted_total(*child.chromosome); state.total_fitness += child_fitness; // Log fitness info if (child_fitness > state.max_fitness) { state.max_fitness = child_fitness; std::cout << "Best independent set (" << state.max_fitness << "): " << std::endl; } // Insert new child into sorted position and update algorithm state for (auto it = std::next(begin(pop)); it != end(pop) && it->fitness <= child_fitness; ++it) { std::swap(*it, *std::prev(it)); } state.min_fitness = begin(pop)->fitness; state.adjusted_fitness = state.total_fitness - state.min_fitness * size; ++state.iterations; if ((state.iterations & 0x3ff) == 0) { std::cout << "Iterations: " << state.iterations << "; Average Fitness: " << state.total_fitness / size << std::endl; } } auto max = std::prev(end(pop)); BitVector result(order); for (size_t i = 0; i < order; ++i) { result[permutation[i]] = (*max->chromosome)[i]; } return result; } } // namespace maxis <|endoftext|>
<commit_before>#include <v8.h> #include <node.h> #include <node_events.h> #include <sqlite3.h> #include "macros.h" #include "database.h" #include "statement.h" using namespace node_sqlite3; extern "C" void init (v8::Handle<Object> target) { Database::Init(target); Statement::Init(target); DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_READONLY, OPEN_READONLY); DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_READWRITE, OPEN_READWRITE); DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_CREATE, OPEN_CREATE); DEFINE_CONSTANT_STRING(target, SQLITE_VERSION, VERSION); // DEFINE_CONSTANT_STRING(target, SQLITE_SOURCE_ID, SOURCE_ID); DEFINE_CONSTANT_INTEGER(target, SQLITE_VERSION_NUMBER, VERSION_NUMBER); DEFINE_CONSTANT_INTEGER(target, SQLITE_OK, OK); DEFINE_CONSTANT_INTEGER(target, SQLITE_ERROR, ERROR); DEFINE_CONSTANT_INTEGER(target, SQLITE_INTERNAL, INTERNAL); DEFINE_CONSTANT_INTEGER(target, SQLITE_PERM, PERM); DEFINE_CONSTANT_INTEGER(target, SQLITE_ABORT, ABORT); DEFINE_CONSTANT_INTEGER(target, SQLITE_BUSY, BUSY); DEFINE_CONSTANT_INTEGER(target, SQLITE_LOCKED, LOCKED); DEFINE_CONSTANT_INTEGER(target, SQLITE_NOMEM, NOMEM); DEFINE_CONSTANT_INTEGER(target, SQLITE_READONLY, READONLY); DEFINE_CONSTANT_INTEGER(target, SQLITE_INTERRUPT, INTERRUPT); DEFINE_CONSTANT_INTEGER(target, SQLITE_IOERR, IOERR); DEFINE_CONSTANT_INTEGER(target, SQLITE_CORRUPT, CORRUPT); DEFINE_CONSTANT_INTEGER(target, SQLITE_NOTFOUND, NOTFOUND); DEFINE_CONSTANT_INTEGER(target, SQLITE_FULL, FULL); DEFINE_CONSTANT_INTEGER(target, SQLITE_CANTOPEN, CANTOPEN); DEFINE_CONSTANT_INTEGER(target, SQLITE_PROTOCOL, PROTOCOL); DEFINE_CONSTANT_INTEGER(target, SQLITE_EMPTY, EMPTY); DEFINE_CONSTANT_INTEGER(target, SQLITE_SCHEMA, SCHEMA); DEFINE_CONSTANT_INTEGER(target, SQLITE_TOOBIG, TOOBIG); DEFINE_CONSTANT_INTEGER(target, SQLITE_CONSTRAINT, CONSTRAINT); DEFINE_CONSTANT_INTEGER(target, SQLITE_MISMATCH, MISMATCH); DEFINE_CONSTANT_INTEGER(target, SQLITE_MISUSE, MISUSE); DEFINE_CONSTANT_INTEGER(target, SQLITE_NOLFS, NOLFS); DEFINE_CONSTANT_INTEGER(target, SQLITE_AUTH, AUTH); DEFINE_CONSTANT_INTEGER(target, SQLITE_FORMAT, FORMAT); DEFINE_CONSTANT_INTEGER(target, SQLITE_RANGE, RANGE); DEFINE_CONSTANT_INTEGER(target, SQLITE_NOTADB, NOTADB); } const char* sqlite_code_string(int code) { switch (code) { case SQLITE_OK: return "SQLITE_OK"; case SQLITE_ERROR: return "SQLITE_ERROR"; case SQLITE_INTERNAL: return "SQLITE_INTERNAL"; case SQLITE_PERM: return "SQLITE_PERM"; case SQLITE_ABORT: return "SQLITE_ABORT"; case SQLITE_BUSY: return "SQLITE_BUSY"; case SQLITE_LOCKED: return "SQLITE_LOCKED"; case SQLITE_NOMEM: return "SQLITE_NOMEM"; case SQLITE_READONLY: return "SQLITE_READONLY"; case SQLITE_INTERRUPT: return "SQLITE_INTERRUPT"; case SQLITE_IOERR: return "SQLITE_IOERR"; case SQLITE_CORRUPT: return "SQLITE_CORRUPT"; case SQLITE_NOTFOUND: return "SQLITE_NOTFOUND"; case SQLITE_FULL: return "SQLITE_FULL"; case SQLITE_CANTOPEN: return "SQLITE_CANTOPEN"; case SQLITE_PROTOCOL: return "SQLITE_PROTOCOL"; case SQLITE_EMPTY: return "SQLITE_EMPTY"; case SQLITE_SCHEMA: return "SQLITE_SCHEMA"; case SQLITE_TOOBIG: return "SQLITE_TOOBIG"; case SQLITE_CONSTRAINT: return "SQLITE_CONSTRAINT"; case SQLITE_MISMATCH: return "SQLITE_MISMATCH"; case SQLITE_MISUSE: return "SQLITE_MISUSE"; case SQLITE_NOLFS: return "SQLITE_NOLFS"; case SQLITE_AUTH: return "SQLITE_AUTH"; case SQLITE_FORMAT: return "SQLITE_FORMAT"; case SQLITE_RANGE: return "SQLITE_RANGE"; case SQLITE_NOTADB: return "SQLITE_NOTADB"; case SQLITE_ROW: return "SQLITE_ROW"; case SQLITE_DONE: return "SQLITE_DONE"; default: return "UNKNOWN"; } } <commit_msg>add SQLITE_SOURCE_ID when it exists<commit_after>#include <v8.h> #include <node.h> #include <node_events.h> #include <sqlite3.h> #include "macros.h" #include "database.h" #include "statement.h" using namespace node_sqlite3; extern "C" void init (v8::Handle<Object> target) { Database::Init(target); Statement::Init(target); DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_READONLY, OPEN_READONLY); DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_READWRITE, OPEN_READWRITE); DEFINE_CONSTANT_INTEGER(target, SQLITE_OPEN_CREATE, OPEN_CREATE); DEFINE_CONSTANT_STRING(target, SQLITE_VERSION, VERSION); #ifdef SQLITE_SOURCE_ID DEFINE_CONSTANT_STRING(target, SQLITE_SOURCE_ID, SOURCE_ID); #endif DEFINE_CONSTANT_INTEGER(target, SQLITE_VERSION_NUMBER, VERSION_NUMBER); DEFINE_CONSTANT_INTEGER(target, SQLITE_OK, OK); DEFINE_CONSTANT_INTEGER(target, SQLITE_ERROR, ERROR); DEFINE_CONSTANT_INTEGER(target, SQLITE_INTERNAL, INTERNAL); DEFINE_CONSTANT_INTEGER(target, SQLITE_PERM, PERM); DEFINE_CONSTANT_INTEGER(target, SQLITE_ABORT, ABORT); DEFINE_CONSTANT_INTEGER(target, SQLITE_BUSY, BUSY); DEFINE_CONSTANT_INTEGER(target, SQLITE_LOCKED, LOCKED); DEFINE_CONSTANT_INTEGER(target, SQLITE_NOMEM, NOMEM); DEFINE_CONSTANT_INTEGER(target, SQLITE_READONLY, READONLY); DEFINE_CONSTANT_INTEGER(target, SQLITE_INTERRUPT, INTERRUPT); DEFINE_CONSTANT_INTEGER(target, SQLITE_IOERR, IOERR); DEFINE_CONSTANT_INTEGER(target, SQLITE_CORRUPT, CORRUPT); DEFINE_CONSTANT_INTEGER(target, SQLITE_NOTFOUND, NOTFOUND); DEFINE_CONSTANT_INTEGER(target, SQLITE_FULL, FULL); DEFINE_CONSTANT_INTEGER(target, SQLITE_CANTOPEN, CANTOPEN); DEFINE_CONSTANT_INTEGER(target, SQLITE_PROTOCOL, PROTOCOL); DEFINE_CONSTANT_INTEGER(target, SQLITE_EMPTY, EMPTY); DEFINE_CONSTANT_INTEGER(target, SQLITE_SCHEMA, SCHEMA); DEFINE_CONSTANT_INTEGER(target, SQLITE_TOOBIG, TOOBIG); DEFINE_CONSTANT_INTEGER(target, SQLITE_CONSTRAINT, CONSTRAINT); DEFINE_CONSTANT_INTEGER(target, SQLITE_MISMATCH, MISMATCH); DEFINE_CONSTANT_INTEGER(target, SQLITE_MISUSE, MISUSE); DEFINE_CONSTANT_INTEGER(target, SQLITE_NOLFS, NOLFS); DEFINE_CONSTANT_INTEGER(target, SQLITE_AUTH, AUTH); DEFINE_CONSTANT_INTEGER(target, SQLITE_FORMAT, FORMAT); DEFINE_CONSTANT_INTEGER(target, SQLITE_RANGE, RANGE); DEFINE_CONSTANT_INTEGER(target, SQLITE_NOTADB, NOTADB); } const char* sqlite_code_string(int code) { switch (code) { case SQLITE_OK: return "SQLITE_OK"; case SQLITE_ERROR: return "SQLITE_ERROR"; case SQLITE_INTERNAL: return "SQLITE_INTERNAL"; case SQLITE_PERM: return "SQLITE_PERM"; case SQLITE_ABORT: return "SQLITE_ABORT"; case SQLITE_BUSY: return "SQLITE_BUSY"; case SQLITE_LOCKED: return "SQLITE_LOCKED"; case SQLITE_NOMEM: return "SQLITE_NOMEM"; case SQLITE_READONLY: return "SQLITE_READONLY"; case SQLITE_INTERRUPT: return "SQLITE_INTERRUPT"; case SQLITE_IOERR: return "SQLITE_IOERR"; case SQLITE_CORRUPT: return "SQLITE_CORRUPT"; case SQLITE_NOTFOUND: return "SQLITE_NOTFOUND"; case SQLITE_FULL: return "SQLITE_FULL"; case SQLITE_CANTOPEN: return "SQLITE_CANTOPEN"; case SQLITE_PROTOCOL: return "SQLITE_PROTOCOL"; case SQLITE_EMPTY: return "SQLITE_EMPTY"; case SQLITE_SCHEMA: return "SQLITE_SCHEMA"; case SQLITE_TOOBIG: return "SQLITE_TOOBIG"; case SQLITE_CONSTRAINT: return "SQLITE_CONSTRAINT"; case SQLITE_MISMATCH: return "SQLITE_MISMATCH"; case SQLITE_MISUSE: return "SQLITE_MISUSE"; case SQLITE_NOLFS: return "SQLITE_NOLFS"; case SQLITE_AUTH: return "SQLITE_AUTH"; case SQLITE_FORMAT: return "SQLITE_FORMAT"; case SQLITE_RANGE: return "SQLITE_RANGE"; case SQLITE_NOTADB: return "SQLITE_NOTADB"; case SQLITE_ROW: return "SQLITE_ROW"; case SQLITE_DONE: return "SQLITE_DONE"; default: return "UNKNOWN"; } } <|endoftext|>
<commit_before><commit_msg>force all tabs to exist when layout enabled<commit_after><|endoftext|>
<commit_before>#include "ghost/timing.h" #include "ghost/util.h" #include <map> #include <vector> #include <sstream> #include <iostream> #include <iomanip> #include <numeric> #include <algorithm> using namespace std; typedef struct { /** * @brief User-defined callback function to compute a region's performance. */ ghost_compute_performance_func_t perfFunc; /** * @brief Argument to perfFunc. */ void *perfFuncArg; /** * @brief The unit of performance. */ const char *perfUnit; } ghost_timing_perfFunc_t; /** * @brief Region timing accumulator */ typedef struct { /** * @brief The runtimes of this region. */ vector<double> times; /** * @brief The last start time of this region. */ double start; vector<ghost_timing_perfFunc_t> perfFuncs; } ghost_timing_region_accu_t; static map<string,ghost_timing_region_accu_t> timings; void ghost_timing_tick(const char *tag) { double start = 0.; ghost_timing_wc(&start); timings[tag].start = start; } void ghost_timing_tock(const char *tag) { double end; ghost_timing_wc(&end); ghost_timing_region_accu_t *ti = &timings[string(tag)]; ti->times.push_back(end-ti->start); } void ghost_timing_set_perfFunc(const char *prefix, const char *tag, ghost_compute_performance_func_t func, void *arg, size_t sizeofarg, const char *unit) { if (!tag) { WARNING_LOG("Empty tag! This should not have happened..."); return; } ghost_timing_perfFunc_t pf; pf.perfFunc = func; pf.perfUnit = unit; const char *fulltag; if (prefix) { fulltag = (string(prefix)+"->"+string(tag)).c_str(); } else { fulltag = tag; } for (std::vector<ghost_timing_perfFunc_t>::iterator it = timings[fulltag].perfFuncs.begin(); it != timings[fulltag].perfFuncs.end(); ++it) { if (it->perfFunc == func && !strcmp(it->perfUnit,unit)) { return; } } ghost_malloc((void **)&(pf.perfFuncArg),sizeofarg); memcpy(pf.perfFuncArg,arg,sizeofarg); timings[fulltag].perfFuncs.push_back(pf); } ghost_error_t ghost_timing_region_create(ghost_timing_region_t ** ri, const char *tag) { ghost_timing_region_accu_t ti = timings[string(tag)]; if (!ti.times.size()) { *ri = NULL; return GHOST_SUCCESS; } ghost_error_t ret = GHOST_SUCCESS; GHOST_CALL_GOTO(ghost_malloc((void **)ri,sizeof(ghost_timing_region_t)),err,ret); (*ri)->nCalls = ti.times.size(); (*ri)->minTime = *min_element(ti.times.begin(),ti.times.end()); (*ri)->maxTime = *max_element(ti.times.begin(),ti.times.end()); (*ri)->accTime = accumulate(ti.times.begin(),ti.times.end(),0.); (*ri)->avgTime = (*ri)->accTime/(*ri)->nCalls; if ((*ri)->nCalls > 10) { (*ri)->skip10avgTime = accumulate(ti.times.begin()+10,ti.times.end(),0.)/((*ri)->nCalls-10); } else { (*ri)->skip10avgTime = 0.; } GHOST_CALL_GOTO(ghost_malloc((void **)(&((*ri)->times)),sizeof(double)*(*ri)->nCalls),err,ret); memcpy((*ri)->times,&ti.times[0],(*ri)->nCalls*sizeof(double)); goto out; err: ERROR_LOG("Freeing region info"); if (*ri) { free((*ri)->times); (*ri)->times = NULL; } free(*ri); (*ri) = NULL; out: return ret; } void ghost_timing_region_destroy(ghost_timing_region_t * ri) { if (ri) { free(ri->times); ri->times = NULL; } free(ri); } ghost_error_t ghost_timing_summarystring(char **str) { stringstream buffer; map<string,ghost_timing_region_accu_t>::iterator iter; vector<ghost_timing_perfFunc_t>::iterator pf_iter; size_t maxRegionLen = 0; size_t maxCallsLen = 0; size_t maxUnitLen = 0; stringstream tmp; for (iter = timings.begin(); iter != timings.end(); ++iter) { int regLen = 0; for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) { if (pf_iter->perfUnit) { tmp << iter->first.length(); maxUnitLen = max(strlen(pf_iter->perfUnit),maxUnitLen); regLen = strlen(pf_iter->perfUnit); tmp.str(""); } } tmp << regLen+iter->first.length(); maxRegionLen = max(regLen+iter->first.length(),maxRegionLen); tmp.str(""); tmp << iter->second.times.size(); maxCallsLen = max(maxCallsLen,tmp.str().length()); tmp.str(""); } if (maxCallsLen < 5) { maxCallsLen = 5; } buffer << left << setw(maxRegionLen+4) << "Region" << right << " | "; buffer << setw(maxCallsLen+3) << "Calls | "; buffer << " t_min | "; buffer << " t_max | "; buffer << " t_avg | "; buffer << " t_s10 | "; buffer << " t_acc" << endl; buffer << string(maxRegionLen+maxCallsLen+7+5*11,'-') << endl; buffer.precision(2); for (iter = timings.begin(); iter != timings.end(); ++iter) { ghost_timing_region_t *region = NULL; ghost_timing_region_create(&region,iter->first.c_str()); if (region) { buffer << scientific << left << setw(maxRegionLen+4) << iter->first << " | " << right << setw(maxCallsLen) << region->nCalls << " | " << region->minTime << " | " << region->maxTime << " | " << region->avgTime << " | " << region->skip10avgTime << " | " << region->accTime << endl; ghost_timing_region_destroy(region); } } int printed = 0; buffer.precision(2); for (iter = timings.begin(); iter != timings.end(); ++iter) { if (!printed) { buffer << endl << endl << left << setw(maxRegionLen+4) << "Region" << right << " | "; buffer << setw(maxCallsLen+3) << "Calls | "; buffer << " P_max | "; buffer << " P_min | "; buffer << " P_avg | "; buffer << "P_skip10" << endl;; buffer << string(maxRegionLen+maxCallsLen+7+4*11,'-') << endl; } printed = 1; ghost_timing_region_t *region = NULL; ghost_timing_region_create(&region,iter->first.c_str()); if (region) { for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) { ghost_compute_performance_func_t pf = pf_iter->perfFunc; void *pfa = pf_iter->perfFuncArg; double P_min = 0., P_max = 0., P_avg = 0., P_skip10 = 0.; int err = pf(&P_min,region->maxTime,pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } err = pf(&P_max,region->minTime,pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } err = pf(&P_avg,region->avgTime,pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } if (region->nCalls > 10) { err = pf(&P_skip10,accumulate(iter->second.times.begin()+10,iter->second.times.end(),0.)/(region->nCalls-10),pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } } buffer << scientific << left << setw(maxRegionLen-maxUnitLen+2) << iter->first << right << "(" << setw(maxUnitLen) << pf_iter->perfUnit << ")" << " | " << setw(maxCallsLen) << region->nCalls << " | " << P_max << " | " << P_min << " | " << P_avg << " | " << P_skip10 << endl; } ghost_timing_region_destroy(region); } } // clear all timings to prevent memory leaks for (iter = timings.begin(); iter != timings.end(); ++iter) { for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) { if( pf_iter->perfFuncArg != NULL ) free(pf_iter->perfFuncArg); pf_iter->perfFuncArg = NULL; } } timings.clear(); GHOST_CALL_RETURN(ghost_malloc((void **)str,buffer.str().length()+1)); strcpy(*str,buffer.str().c_str()); return GHOST_SUCCESS; } <commit_msg>bugfix which caused segfault.<commit_after>#include "ghost/timing.h" #include "ghost/util.h" #include <map> #include <vector> #include <sstream> #include <iostream> #include <iomanip> #include <numeric> #include <algorithm> using namespace std; typedef struct { /** * @brief User-defined callback function to compute a region's performance. */ ghost_compute_performance_func_t perfFunc; /** * @brief Argument to perfFunc. */ void *perfFuncArg; /** * @brief The unit of performance. */ const char *perfUnit; } ghost_timing_perfFunc_t; /** * @brief Region timing accumulator */ typedef struct { /** * @brief The runtimes of this region. */ vector<double> times; /** * @brief The last start time of this region. */ double start; vector<ghost_timing_perfFunc_t> perfFuncs; } ghost_timing_region_accu_t; static map<string,ghost_timing_region_accu_t> timings; void ghost_timing_tick(const char *tag) { double start = 0.; ghost_timing_wc(&start); timings[tag].start = start; } void ghost_timing_tock(const char *tag) { double end; ghost_timing_wc(&end); ghost_timing_region_accu_t *ti = &timings[string(tag)]; ti->times.push_back(end-ti->start); } void ghost_timing_set_perfFunc(const char *prefix, const char *tag, ghost_compute_performance_func_t func, void *arg, size_t sizeofarg, const char *unit) { if (!tag) { WARNING_LOG("Empty tag! This should not have happened..."); return; } ghost_timing_perfFunc_t pf; pf.perfFunc = func; pf.perfUnit = unit; ghost_timing_region_accu_t region; if (prefix) { const char *fulltag = (string(prefix)+"->"+string(tag)).c_str(); region = timings[fulltag]; } else { region = timings[tag]; } for (std::vector<ghost_timing_perfFunc_t>::iterator it = region.perfFuncs.begin(); it !=region.perfFuncs.end(); ++it) { if (it->perfFunc == func && !strcmp(it->perfUnit,unit)) { return; } } ghost_malloc((void **)&(pf.perfFuncArg),sizeofarg); memcpy(pf.perfFuncArg,arg,sizeofarg); region.perfFuncs.push_back(pf); } ghost_error_t ghost_timing_region_create(ghost_timing_region_t ** ri, const char *tag) { ghost_timing_region_accu_t ti = timings[string(tag)]; if (!ti.times.size()) { *ri = NULL; return GHOST_SUCCESS; } ghost_error_t ret = GHOST_SUCCESS; GHOST_CALL_GOTO(ghost_malloc((void **)ri,sizeof(ghost_timing_region_t)),err,ret); (*ri)->nCalls = ti.times.size(); (*ri)->minTime = *min_element(ti.times.begin(),ti.times.end()); (*ri)->maxTime = *max_element(ti.times.begin(),ti.times.end()); (*ri)->accTime = accumulate(ti.times.begin(),ti.times.end(),0.); (*ri)->avgTime = (*ri)->accTime/(*ri)->nCalls; if ((*ri)->nCalls > 10) { (*ri)->skip10avgTime = accumulate(ti.times.begin()+10,ti.times.end(),0.)/((*ri)->nCalls-10); } else { (*ri)->skip10avgTime = 0.; } GHOST_CALL_GOTO(ghost_malloc((void **)(&((*ri)->times)),sizeof(double)*(*ri)->nCalls),err,ret); memcpy((*ri)->times,&ti.times[0],(*ri)->nCalls*sizeof(double)); goto out; err: ERROR_LOG("Freeing region info"); if (*ri) { free((*ri)->times); (*ri)->times = NULL; } free(*ri); (*ri) = NULL; out: return ret; } void ghost_timing_region_destroy(ghost_timing_region_t * ri) { if (ri) { free(ri->times); ri->times = NULL; } free(ri); } ghost_error_t ghost_timing_summarystring(char **str) { stringstream buffer; map<string,ghost_timing_region_accu_t>::iterator iter; vector<ghost_timing_perfFunc_t>::iterator pf_iter; size_t maxRegionLen = 0; size_t maxCallsLen = 0; size_t maxUnitLen = 0; stringstream tmp; for (iter = timings.begin(); iter != timings.end(); ++iter) { int regLen = 0; for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) { if (pf_iter->perfUnit) { tmp << iter->first.length(); maxUnitLen = max(strlen(pf_iter->perfUnit),maxUnitLen); regLen = strlen(pf_iter->perfUnit); tmp.str(""); } } tmp << regLen+iter->first.length(); maxRegionLen = max(regLen+iter->first.length(),maxRegionLen); tmp.str(""); tmp << iter->second.times.size(); maxCallsLen = max(maxCallsLen,tmp.str().length()); tmp.str(""); } if (maxCallsLen < 5) { maxCallsLen = 5; } buffer << left << setw(maxRegionLen+4) << "Region" << right << " | "; buffer << setw(maxCallsLen+3) << "Calls | "; buffer << " t_min | "; buffer << " t_max | "; buffer << " t_avg | "; buffer << " t_s10 | "; buffer << " t_acc" << endl; buffer << string(maxRegionLen+maxCallsLen+7+5*11,'-') << endl; buffer.precision(2); for (iter = timings.begin(); iter != timings.end(); ++iter) { ghost_timing_region_t *region = NULL; ghost_timing_region_create(&region,iter->first.c_str()); if (region) { buffer << scientific << left << setw(maxRegionLen+4) << iter->first << " | " << right << setw(maxCallsLen) << region->nCalls << " | " << region->minTime << " | " << region->maxTime << " | " << region->avgTime << " | " << region->skip10avgTime << " | " << region->accTime << endl; ghost_timing_region_destroy(region); } } int printed = 0; buffer.precision(2); for (iter = timings.begin(); iter != timings.end(); ++iter) { if (!printed) { buffer << endl << endl << left << setw(maxRegionLen+4) << "Region" << right << " | "; buffer << setw(maxCallsLen+3) << "Calls | "; buffer << " P_max | "; buffer << " P_min | "; buffer << " P_avg | "; buffer << "P_skip10" << endl;; buffer << string(maxRegionLen+maxCallsLen+7+4*11,'-') << endl; } printed = 1; ghost_timing_region_t *region = NULL; ghost_timing_region_create(&region,iter->first.c_str()); if (region) { for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) { ghost_compute_performance_func_t pf = pf_iter->perfFunc; void *pfa = pf_iter->perfFuncArg; double P_min = 0., P_max = 0., P_avg = 0., P_skip10 = 0.; int err = pf(&P_min,region->maxTime,pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } err = pf(&P_max,region->minTime,pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } err = pf(&P_avg,region->avgTime,pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } if (region->nCalls > 10) { err = pf(&P_skip10,accumulate(iter->second.times.begin()+10,iter->second.times.end(),0.)/(region->nCalls-10),pfa); if (err) { ERROR_LOG("Error in calling performance computation callback!"); } } buffer << scientific << left << setw(maxRegionLen-maxUnitLen+2) << iter->first << right << "(" << setw(maxUnitLen) << pf_iter->perfUnit << ")" << " | " << setw(maxCallsLen) << region->nCalls << " | " << P_max << " | " << P_min << " | " << P_avg << " | " << P_skip10 << endl; } ghost_timing_region_destroy(region); } } // clear all timings to prevent memory leaks for (iter = timings.begin(); iter != timings.end(); ++iter) { for (pf_iter = iter->second.perfFuncs.begin(); pf_iter != iter->second.perfFuncs.end(); ++pf_iter) { if( pf_iter->perfFuncArg != NULL ) free(pf_iter->perfFuncArg); pf_iter->perfFuncArg = NULL; } } timings.clear(); GHOST_CALL_RETURN(ghost_malloc((void **)str,buffer.str().length()+1)); strcpy(*str,buffer.str().c_str()); return GHOST_SUCCESS; } <|endoftext|>
<commit_before>/* * Copyright (c) 2011 James Peach * * 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 <ts/ts.h> #include <stdlib.h> #include <spdy/spdy.h> #include "logging.h" struct spdy_io_control { spdy_io_control(TSVConn); ~spdy_io_control(); struct buffered_stream { TSIOBuffer buffer; TSIOBufferReader reader; buffered_stream() { buffer = TSIOBufferCreate(); reader = TSIOBufferReaderAlloc(buffer); } ~buffered_stream() { TSIOBufferReaderFree(reader); TSIOBufferDestroy(buffer); } void consume(size_t nbytes) { TSIOBufferReaderConsume(reader, nbytes); } void watermark(size_t nbytes) { TSIOBufferWaterMarkSet(buffer, nbytes); } }; TSVConn vconn; buffered_stream input; buffered_stream output; static spdy_io_control * get(TSCont contp) { return (spdy_io_control *)TSContDataGet(contp); } }; spdy_io_control::spdy_io_control(TSVConn v) : vconn(v) { } spdy_io_control::~spdy_io_control() { TSVConnClose(vconn); } static void dispatch_spdy_control_frame( const spdy::message_header& header, spdy_io_control * /*io*/, const uint8_t __restrict * ptr, size_t nbytes) { union { spdy::syn_stream_message stream; } msg; switch (header.control.type) { case spdy::CONTROL_SYN_STREAM: msg.stream = spdy::syn_stream_message::parse(ptr, nbytes); debug_protocol("%s frame stream=%u associated=%u priority=%u headers=%u", cstringof(header.control.type), msg.stream.stream_id, msg.stream.associated_id, msg.stream.priority, msg.stream.header_count); break; case spdy::CONTROL_SYN_REPLY: case spdy::CONTROL_RST_STREAM: case spdy::CONTROL_SETTINGS: case spdy::CONTROL_PING: case spdy::CONTROL_GOAWAY: case spdy::CONTROL_HEADERS: case spdy::CONTROL_WINDOW_UPDATE: debug_protocol("control frame type %s not implemented yet", cstringof(header.control.type)); break; default: // SPDY 2.2.1 - MUST ignore unrecognized control frames TSError("ignoring invalid control frame type %u", header.control.type); } } static void consume_spdy_frame(spdy_io_control * io) { spdy::message_header header; TSIOBufferBlock blk; const uint8_t * ptr; int64_t nbytes; next_frame: blk = TSIOBufferStart(io->input.buffer); ptr = (const uint8_t *)TSIOBufferBlockReadStart(blk, io->input.reader, &nbytes); TSReleaseAssert(nbytes >= spdy::message_header::size); header = spdy::message_header::parse(ptr, (size_t)nbytes); TSAssert(header.datalen > 0); // XXX if (header.is_control) { if (header.control.version != spdy::PROTOCOL_VERSION) { TSError("[spdy] client is version %u, but we implement version %u", header.control.version, spdy::PROTOCOL_VERSION); } debug_protocol("SPDY control frame, version=%u type=%s flags=0x%x, %zu bytes", header.control.version, cstringof(header.control.type), header.flags, header.datalen); } else { debug_protocol("SPDY data frame, stream=%u flags=0x%x, %zu bytes", header.data.stream_id, header.flags, header.datalen); } if (header.datalen >= spdy::MAX_FRAME_LENGTH) { // XXX } if (header.datalen <= (nbytes - spdy::message_header::size)) { // We have all the data in-hand ... parse it. io->input.consume(spdy::message_header::size); io->input.consume(header.datalen); ptr += spdy::message_header::size; if (header.is_control) { dispatch_spdy_control_frame(header, io, ptr, nbytes); } else { TSError("[spdy] no data frame support yet"); } if (TSIOBufferReaderAvail(io->input.reader) >= spdy::message_header::size) { goto next_frame; } } // Push the high water mark to the end of the frame so that we don't get // called back until we have the whole thing. io->input.watermark(spdy::message_header::size + header.datalen); } static int spdy_read(TSCont contp, TSEvent ev, void * /* edata */) { int nbytes; spdy_io_control * io; switch (ev) { case TS_EVENT_VCONN_READ_READY: case TS_EVENT_VCONN_READ_COMPLETE: io = spdy_io_control::get(contp); // what is edata at this point? nbytes = TSIOBufferReaderAvail(io->input.reader); debug_plugin("received %d bytes", nbytes); if ((unsigned)nbytes >= spdy::message_header::size) { consume_spdy_frame(io); } else { io->input.consume(nbytes); } // XXX frame parsing can throw. If it does, best to catch it, log it // and drop the connection. break; case TS_EVENT_VCONN_EOS: // fallthru default: io = spdy_io_control::get(contp); debug_plugin("unexpected accept event %s", cstringof(ev)); TSVConnClose(io->vconn); delete io; } return TS_EVENT_NONE; } static int spdy_accept(TSCont contp, TSEvent ev, void * edata) { TSVConn vconn; spdy_io_control * io; TSAssert(contp == nullptr); switch (ev) { case TS_EVENT_NET_ACCEPT: debug_protocol("setting up SPDY session on new connection"); vconn = (TSVConn)edata; io = new spdy_io_control(vconn); io->input.watermark(spdy::message_header::size); contp = TSContCreate(spdy_read, TSMutexCreate()); TSContDataSet(contp, io); TSVConnRead(vconn, contp, io->input.buffer, INT64_MAX); break; default: debug_plugin("unexpected accept event %s", cstringof(ev)); } return TS_EVENT_NONE; } static void spdy_initialize(uint16_t port) { TSCont contp; TSAction action; contp = TSContCreate(spdy_accept, TSMutexCreate()); action = TSNetAccept(contp, port, -1 /* domain */, 1 /* accept threads */); if (TSActionDone(action)) { debug_plugin("accept action done?"); } } void TSPluginInit(int argc, const char *argv[]) { int port; TSPluginRegistrationInfo info; info.plugin_name = (char *)"spdy"; info.vendor_name = (char *)"James Peach"; info.support_email = (char *)"jamespeach@me.com"; if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) { TSError("[%s] Plugin registration failed", __func__); } debug_plugin("initializing"); if (argc != 2) { TSError("[%s] Usage: spdy.so PORT", __func__); return; } port = atoi(argv[1]); if (port <= 1 || port > UINT16_MAX) { TSError("[%s] invalid port number: %s", __func__, argv[1]); return; } spdy_initialize((uint16_t)port); } /* vim: set sw=4 tw=79 ts=4 et ai : */ <commit_msg>Send stream resets in response to stream syns.<commit_after>/* * Copyright (c) 2011 James Peach * * 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 <ts/ts.h> #include <stdlib.h> #include <spdy/spdy.h> #include "logging.h" struct spdy_io_control { spdy_io_control(TSVConn); ~spdy_io_control(); struct buffered_stream { TSIOBuffer buffer; TSIOBufferReader reader; buffered_stream() { buffer = TSIOBufferCreate(); reader = TSIOBufferReaderAlloc(buffer); } ~buffered_stream() { TSIOBufferReaderFree(reader); TSIOBufferDestroy(buffer); } void consume(size_t nbytes) { TSIOBufferReaderConsume(reader, nbytes); } void watermark(size_t nbytes) { TSIOBufferWaterMarkSet(buffer, nbytes); } }; TSVConn vconn; buffered_stream input; buffered_stream output; static spdy_io_control * get(TSCont contp) { return (spdy_io_control *)TSContDataGet(contp); } }; spdy_io_control::spdy_io_control(TSVConn v) : vconn(v) { } spdy_io_control::~spdy_io_control() { TSVConnClose(vconn); } static void spdy_reset_stream( spdy_io_control * io, unsigned stream_id, spdy::error status) { spdy::message_header hdr; spdy::rst_stream_message rst; uint8_t buffer[spdy::message_header::size + spdy::message_header::size]; uint8_t * ptr = buffer; size_t nbytes = 0; hdr.is_control = true; hdr.control.version = spdy::PROTOCOL_VERSION; hdr.control.type = spdy::CONTROL_RST_STREAM; hdr.flags = 0; hdr.datalen = spdy::rst_stream_message::size; rst.stream_id = stream_id; rst.status_code = status; nbytes += spdy::message_header::marshall(hdr, ptr, sizeof(buffer)); nbytes += spdy::rst_stream_message::marshall(rst, ptr, sizeof(buffer) - nbytes); debug_protocol("resetting stream %u with error %s", stream_id, cstringof(status)); TSIOBufferWrite(io->output.buffer, buffer, nbytes); TSIOBufferProduce(io->output.buffer, nbytes); } static void dispatch_spdy_control_frame( const spdy::message_header& header, spdy_io_control * io, const uint8_t __restrict * ptr, size_t nbytes) { union { spdy::syn_stream_message stream; } msg; switch (header.control.type) { case spdy::CONTROL_SYN_STREAM: msg.stream = spdy::syn_stream_message::parse(ptr, nbytes); debug_protocol("%s frame stream=%u associated=%u priority=%u headers=%u", cstringof(header.control.type), msg.stream.stream_id, msg.stream.associated_id, msg.stream.priority, msg.stream.header_count); spdy_reset_stream(io, msg.stream.stream_id, spdy::REFUSED_STREAM); break; case spdy::CONTROL_SYN_REPLY: case spdy::CONTROL_RST_STREAM: case spdy::CONTROL_SETTINGS: case spdy::CONTROL_PING: case spdy::CONTROL_GOAWAY: case spdy::CONTROL_HEADERS: case spdy::CONTROL_WINDOW_UPDATE: debug_protocol("control frame type %s not implemented yet", cstringof(header.control.type)); break; default: // SPDY 2.2.1 - MUST ignore unrecognized control frames TSError("ignoring invalid control frame type %u", header.control.type); } } static void consume_spdy_frame(spdy_io_control * io) { spdy::message_header header; TSIOBufferBlock blk; const uint8_t * ptr; int64_t nbytes; next_frame: blk = TSIOBufferStart(io->input.buffer); ptr = (const uint8_t *)TSIOBufferBlockReadStart(blk, io->input.reader, &nbytes); TSReleaseAssert(nbytes >= spdy::message_header::size); header = spdy::message_header::parse(ptr, (size_t)nbytes); TSAssert(header.datalen > 0); // XXX if (header.is_control) { if (header.control.version != spdy::PROTOCOL_VERSION) { TSError("[spdy] client is version %u, but we implement version %u", header.control.version, spdy::PROTOCOL_VERSION); } debug_protocol("SPDY control frame, version=%u type=%s flags=0x%x, %zu bytes", header.control.version, cstringof(header.control.type), header.flags, header.datalen); } else { debug_protocol("SPDY data frame, stream=%u flags=0x%x, %zu bytes", header.data.stream_id, header.flags, header.datalen); } if (header.datalen >= spdy::MAX_FRAME_LENGTH) { // XXX } if (header.datalen <= (nbytes - spdy::message_header::size)) { // We have all the data in-hand ... parse it. io->input.consume(spdy::message_header::size); io->input.consume(header.datalen); ptr += spdy::message_header::size; if (header.is_control) { dispatch_spdy_control_frame(header, io, ptr, nbytes); } else { TSError("[spdy] no data frame support yet"); } if (TSIOBufferReaderAvail(io->input.reader) >= spdy::message_header::size) { goto next_frame; } } // Push the high water mark to the end of the frame so that we don't get // called back until we have the whole thing. io->input.watermark(spdy::message_header::size + header.datalen); } static int spdy_vconn_io(TSCont contp, TSEvent ev, void * edata) { int nbytes; spdy_io_control * io; debug_plugin("received IO event %s, data=%p", cstringof(ev), edata); switch (ev) { case TS_EVENT_VCONN_READ_READY: case TS_EVENT_VCONN_READ_COMPLETE: io = spdy_io_control::get(contp); // what is edata at this point? nbytes = TSIOBufferReaderAvail(io->input.reader); debug_plugin("received %d bytes", nbytes); if ((unsigned)nbytes >= spdy::message_header::size) { consume_spdy_frame(io); } // XXX frame parsing can throw. If it does, best to catch it, log it // and drop the connection. break; case TS_EVENT_VCONN_WRITE_READY: case TS_EVENT_VCONN_WRITE_COMPLETE: break; case TS_EVENT_VCONN_EOS: // fallthru default: io = spdy_io_control::get(contp); debug_plugin("unexpected accept event %s", cstringof(ev)); TSVConnClose(io->vconn); delete io; } return TS_EVENT_NONE; } static int spdy_accept(TSCont contp, TSEvent ev, void * edata) { TSVConn vconn; spdy_io_control * io; TSAssert(contp == nullptr); switch (ev) { case TS_EVENT_NET_ACCEPT: debug_protocol("setting up SPDY session on new connection"); vconn = (TSVConn)edata; io = new spdy_io_control(vconn); io->input.watermark(spdy::message_header::size); io->output.watermark(spdy::message_header::size); contp = TSContCreate(spdy_vconn_io, TSMutexCreate()); TSContDataSet(contp, io); TSVConnRead(vconn, contp, io->input.buffer, INT64_MAX); TSVConnWrite(vconn, contp, io->output.reader, INT64_MAX); break; default: debug_plugin("unexpected accept event %s", cstringof(ev)); } return TS_EVENT_NONE; } static void spdy_initialize(uint16_t port) { TSCont contp; TSAction action; contp = TSContCreate(spdy_accept, TSMutexCreate()); action = TSNetAccept(contp, port, -1 /* domain */, 1 /* accept threads */); if (TSActionDone(action)) { debug_plugin("accept action done?"); } } void TSPluginInit(int argc, const char *argv[]) { int port; TSPluginRegistrationInfo info; info.plugin_name = (char *)"spdy"; info.vendor_name = (char *)"James Peach"; info.support_email = (char *)"jamespeach@me.com"; if (TSPluginRegister(TS_SDK_VERSION_3_0, &info) != TS_SUCCESS) { TSError("[%s] Plugin registration failed", __func__); } debug_plugin("initializing"); if (argc != 2) { TSError("[%s] Usage: spdy.so PORT", __func__); return; } port = atoi(argv[1]); if (port <= 1 || port > UINT16_MAX) { TSError("[%s] invalid port number: %s", __func__, argv[1]); return; } spdy_initialize((uint16_t)port); } /* vim: set sw=4 tw=79 ts=4 et ai : */ <|endoftext|>
<commit_before>/* Copyright 2007-2015 QReal Research Group * * 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 "kitBase/blocksBase/common/waitForColorBlock.h" #include "kitBase/robotModel/robotParts/colorSensorFull.h" using namespace kitBase; using namespace blocksBase::common; WaitForColorBlock::WaitForColorBlock(kitBase::robotModel::RobotModelInterface &robotModel) : WaitForColorSensorBlockBase(robotModel) { } void WaitForColorBlock::responseSlot(int reading) { const QString targetColor = stringProperty("Color"); QString color; switch (reading) { case 1: color = tr("Black"); break; case 2: color = tr("Blue"); break; case 3: color = tr("Green"); break; case 4: color = tr("Yellow"); break; case 5: color = tr("Red"); break; case 6: color = tr("White"); break; default: return; } if (targetColor == color) { stop(); } } robotModel::DeviceInfo WaitForColorBlock::device() const { return robotModel::DeviceInfo::create<robotModel::robotParts::ColorSensorFull>(); } <commit_msg>Fixed color sensor work in NXT mode<commit_after>/* Copyright 2007-2015 QReal Research Group * * 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 "kitBase/blocksBase/common/waitForColorBlock.h" #include "kitBase/robotModel/robotParts/colorSensorFull.h" using namespace kitBase; using namespace blocksBase::common; WaitForColorBlock::WaitForColorBlock(kitBase::robotModel::RobotModelInterface &robotModel) : WaitForColorSensorBlockBase(robotModel) { } void WaitForColorBlock::responseSlot(int reading) { const QString targetColor = stringProperty("Color"); QString color; switch (reading) { case 1: color = "black"; break; case 2: color = "blue"; break; case 3: color = "green"; break; case 4: color = "yellow"; break; case 5: color = "red"; break; case 6: color = "white"; break; default: return; } if (targetColor == color) { stop(); } } robotModel::DeviceInfo WaitForColorBlock::device() const { return robotModel::DeviceInfo::create<robotModel::robotParts::ColorSensorFull>(); } <|endoftext|>
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h" #include <fstream> #include <memory> #include "absl/status/status.h" #include "tensorflow/lite/core/shims/cc/shims_test_util.h" #include "tensorflow_lite_support/cc/port/gmock.h" #include "tensorflow_lite_support/cc/port/gtest.h" #include "tensorflow_lite_support/cc/port/status_matchers.h" #include "tensorflow_lite_support/cc/task/core/task_utils.h" #include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h" #include "tensorflow_lite_support/cc/test/test_utils.h" #include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils.h" namespace tflite { namespace task { namespace processor { namespace { using ::tflite::support::StatusOr; using ::tflite::task::JoinPath; using ::tflite::task::core::TfLiteEngine; using ::tflite::task::vision::DecodeImageFromFile; using ::tflite::task::vision::FrameBuffer; using ::tflite::task::vision::ImageData; constexpr char kTestDataDirectory[] = "tensorflow_lite_support/cc/test/testdata/task/vision/"; constexpr char kDilatedConvolutionModelWithMetaData[] = "dilated_conv.tflite"; StatusOr<ImageData> LoadImage(std::string image_name) { return DecodeImageFromFile( JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name)); } class DynamicInputTest : public tflite_shims::testing::Test { public: void SetUp() { engine_ = absl::make_unique<TfLiteEngine>(); engine_->BuildModelFromFile(JoinPath("./", kTestDataDirectory, kDilatedConvolutionModelWithMetaData)); engine_->InitInterpreter(); SUPPORT_ASSERT_OK_AND_ASSIGN(auto preprocessor, ImagePreprocessor::Create(engine_.get(), {0})); SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg")); std::unique_ptr<FrameBuffer> image_frame_buffer = CreateFromRgbRawBuffer( image.pixel_data, FrameBuffer::Dimension{image.width, image.height}); preprocessor->Preprocess(*image_frame_buffer); } protected: std::unique_ptr<TfLiteEngine> engine_ = nullptr; }; // See if output tensor has been re-dimmed as per the input // tensor. Expected shape: (1, input_height, input_width, 16). TEST_F(DynamicInputTest, OutputDimensionCheck) { EXPECT_TRUE(engine_->interpreter_wrapper()->InvokeWithoutFallback().ok()); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[0], 1); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[1], engine_->GetInputs()[0]->dims->data[1]); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[2], engine_->GetInputs()[0]->dims->data[2]); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[3], 16); } // Compare pre-processed input with an already pre-processed // golden image. TEST_F(DynamicInputTest, GoldenImageComparison) { // Check the processed input image. float *processed_input_data = tflite::task::core::AssertAndReturnTypedTensor<float>( engine_->GetInputs()[0]); bool is_equal = true; float epsilon = 0.1f; // std::string file_path = // JoinPath("./", kTestDataDirectory, "burger_normalized.bin"); std::string file_path = "/home/psykik/open_source/tflite-support/tensorflow_lite_support/cc/test/" "testdata/task/vision/burger_normalized.bin"; std::ifstream golden_image(file_path, std::ios::binary); // Input read success check. is_equal &= golden_image.peek() != std::ifstream::traits_type::eof(); std::vector<uint8_t> buffer(std::istreambuf_iterator<char>(golden_image), {}); float *val_ptr = reinterpret_cast<float *>(buffer.data()); for (size_t i = 0; i < buffer.size() / sizeof(float); ++i) { is_equal &= std::fabs(*val_ptr - *processed_input_data) <= epsilon; ++val_ptr; ++processed_input_data; } EXPECT_TRUE(is_equal); } } // namespace } // namespace processor } // namespace task } // namespace tflite <commit_msg>Image read succesful.<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==============================================================================*/ #include "tensorflow_lite_support/cc/task/processor/image_preprocessor.h" #include <fstream> #include <memory> #include "absl/status/status.h" #include "tensorflow/lite/core/shims/cc/shims_test_util.h" #include "tensorflow_lite_support/cc/port/gmock.h" #include "tensorflow_lite_support/cc/port/gtest.h" #include "tensorflow_lite_support/cc/port/status_matchers.h" #include "tensorflow_lite_support/cc/task/core/task_utils.h" #include "tensorflow_lite_support/cc/task/vision/utils/frame_buffer_common_utils.h" #include "tensorflow_lite_support/cc/test/test_utils.h" #include "tensorflow_lite_support/examples/task/vision/desktop/utils/image_utils.h" namespace tflite { namespace task { namespace processor { namespace { using ::tflite::support::StatusOr; using ::tflite::task::JoinPath; using ::tflite::task::core::TfLiteEngine; using ::tflite::task::vision::DecodeImageFromFile; using ::tflite::task::vision::FrameBuffer; using ::tflite::task::vision::ImageData; constexpr char kTestDataDirectory[] = "tensorflow_lite_support/cc/test/testdata/task/vision/"; constexpr char kDilatedConvolutionModelWithMetaData[] = "dilated_conv.tflite"; StatusOr<ImageData> LoadImage(std::string image_name) { return DecodeImageFromFile( JoinPath("./" /*test src dir*/, kTestDataDirectory, image_name)); } class DynamicInputTest : public tflite_shims::testing::Test { public: void SetUp() { engine_ = absl::make_unique<TfLiteEngine>(); engine_->BuildModelFromFile(JoinPath("./", kTestDataDirectory, kDilatedConvolutionModelWithMetaData)); engine_->InitInterpreter(); SUPPORT_ASSERT_OK_AND_ASSIGN(auto preprocessor, ImagePreprocessor::Create(engine_.get(), {0})); SUPPORT_ASSERT_OK_AND_ASSIGN(ImageData image, LoadImage("burger.jpg")); std::unique_ptr<FrameBuffer> image_frame_buffer = CreateFromRgbRawBuffer( image.pixel_data, FrameBuffer::Dimension{image.width, image.height}); preprocessor->Preprocess(*image_frame_buffer); } protected: std::unique_ptr<TfLiteEngine> engine_ = nullptr; }; // See if output tensor has been re-dimmed as per the input // tensor. Expected shape: (1, input_height, input_width, 16). TEST_F(DynamicInputTest, OutputDimensionCheck) { EXPECT_TRUE(engine_->interpreter_wrapper()->InvokeWithoutFallback().ok()); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[0], 1); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[1], engine_->GetInputs()[0]->dims->data[1]); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[2], engine_->GetInputs()[0]->dims->data[2]); EXPECT_EQ(engine_->GetOutputs()[0]->dims->data[3], 16); } // Compare pre-processed input with an already pre-processed // golden image. TEST_F(DynamicInputTest, GoldenImageComparison) { // Check the processed input image. float *processed_input_data = tflite::task::core::AssertAndReturnTypedTensor<float>( engine_->GetInputs()[0]); bool is_equal = true; float epsilon = 0.1f; std::string file_path = JoinPath("./", kTestDataDirectory, "burger_normalized.bin"); std::ifstream golden_image(file_path, std::ios::binary); std::vector<uint8> buffer(std::istreambuf_iterator<char>(golden_image), {}); float *val_ptr = reinterpret_cast<float *>(buffer.data()); for (size_t i = 0; i < buffer.size() / sizeof(float); ++i) { is_equal &= std::fabs(*val_ptr - *processed_input_data) <= epsilon; ++val_ptr; ++processed_input_data; } EXPECT_TRUE(is_equal); } } // namespace } // namespace processor } // namespace task } // namespace tflite <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: config.hxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2007-11-02 13:09:36 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef CONFIG_HXX_INCLUDED #define CONFIG_HXX_INCLUDED #ifdef _MSC_VER #pragma warning (disable : 4786 4503 4917) #endif #ifndef OS2 #include <tchar.h> #endif #define MODULE_NAME TEXT("shlxthdl.dll") #define MODULE_NAME_FILTER TEXT("ooofilt.dll") #define COLUMN_HANDLER_DESCRIPTIVE_NAME TEXT("OpenOffice.org Column Handler") #define INFOTIP_HANDLER_DESCRIPTIVE_NAME TEXT("OpenOffice.org Infotip Handler") #define PROPSHEET_HANDLER_DESCRIPTIVE_NAME TEXT("OpenOffice.org Property Sheet Handler") #define THUMBVIEWER_HANDLER_DESCRIPTIVAE_NAME TEXT("OpenOffice.org Thumbnail Viewer") #define META_CONTENT_NAME "meta.xml" #define DOC_CONTENT_NAME "content.xml" #define EMPTY_STRING L"" #define SPACE L" " #define LF L"\n" #define META_INFO_TITLE L"title" #define META_INFO_AUTHOR L"initial-creator" #define META_INFO_SUBJECT L"subject" #define META_INFO_KEYWORDS L"keywords" #define META_INFO_KEYWORD L"keyword" #define META_INFO_DESCRIPTION L"description" #define META_INFO_PAGES L"page-count" #define META_INFO_TABLES L"table-count" #define META_INFO_DRAWS L"image-count" #define META_INFO_OBJECTS L"object-count" #define META_INFO_OLE_OBJECTS L"object-count" #define META_INFO_PARAGRAPHS L"paragraph-count" #define META_INFO_WORDS L"word-count" #define META_INFO_CHARACTERS L"character-count" #define META_INFO_ROWS L"row-count" #define META_INFO_CELLS L"cell-count" #define META_INFO_DOCUMENT_STATISTIC L"document-statistic" #define META_INFO_MODIFIED L"date" #define META_INFO_DOCUMENT_NUMBER L"editing-cycles" #define META_INFO_EDITING_TIME L"editing-duration" #define META_INFO_LANGUAGE L"language" #define META_INFO_CREATOR L"creator" #define META_INFO_CREATION L"creation-date" #define META_INFO_GENERATOR L"generator" #define CONTENT_TEXT_A L"a" #define CONTENT_TEXT_P L"p" #define CONTENT_TEXT_H L"h" #define CONTENT_TEXT_SPAN L"span" #define CONTENT_TEXT_SEQUENCE L"sequence" #define CONTENT_TEXT_BOOKMARK_REF L"bookmark-ref" #define CONTENT_TEXT_INDEX_TITLE_TEMPLATE L"index-title-template" #define CONTENT_TEXT_STYLENAME L"style-name" #define CONTENT_STYLE_STYLE L"style" #define CONTENT_STYLE_STYLE_NAME L"name" #define CONTENT_STYLE_PROPERTIES L"properties" #define CONTENT_TEXT_STYLE_PROPERTIES L"text-properties" // added for OASIS Open Office XML format. #define CONTENT_STYLE_PROPERTIES_LANGUAGE L"language" #define CONTENT_STYLE_PROPERTIES_COUNTRY L"country" #define CONTENT_STYLE_PROPERTIES_LANGUAGEASIAN L"language-asian" #define CONTENT_STYLE_PROPERTIES_COUNTRYASIAN L"country-asian" #endif <commit_msg>INTEGRATION: CWS changefileheader (1.7.40); FILE MERGED 2008/03/31 13:17:03 rt 1.7.40.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: config.hxx,v $ * $Revision: 1.8 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #ifndef CONFIG_HXX_INCLUDED #define CONFIG_HXX_INCLUDED #ifdef _MSC_VER #pragma warning (disable : 4786 4503 4917) #endif #ifndef OS2 #include <tchar.h> #endif #define MODULE_NAME TEXT("shlxthdl.dll") #define MODULE_NAME_FILTER TEXT("ooofilt.dll") #define COLUMN_HANDLER_DESCRIPTIVE_NAME TEXT("OpenOffice.org Column Handler") #define INFOTIP_HANDLER_DESCRIPTIVE_NAME TEXT("OpenOffice.org Infotip Handler") #define PROPSHEET_HANDLER_DESCRIPTIVE_NAME TEXT("OpenOffice.org Property Sheet Handler") #define THUMBVIEWER_HANDLER_DESCRIPTIVAE_NAME TEXT("OpenOffice.org Thumbnail Viewer") #define META_CONTENT_NAME "meta.xml" #define DOC_CONTENT_NAME "content.xml" #define EMPTY_STRING L"" #define SPACE L" " #define LF L"\n" #define META_INFO_TITLE L"title" #define META_INFO_AUTHOR L"initial-creator" #define META_INFO_SUBJECT L"subject" #define META_INFO_KEYWORDS L"keywords" #define META_INFO_KEYWORD L"keyword" #define META_INFO_DESCRIPTION L"description" #define META_INFO_PAGES L"page-count" #define META_INFO_TABLES L"table-count" #define META_INFO_DRAWS L"image-count" #define META_INFO_OBJECTS L"object-count" #define META_INFO_OLE_OBJECTS L"object-count" #define META_INFO_PARAGRAPHS L"paragraph-count" #define META_INFO_WORDS L"word-count" #define META_INFO_CHARACTERS L"character-count" #define META_INFO_ROWS L"row-count" #define META_INFO_CELLS L"cell-count" #define META_INFO_DOCUMENT_STATISTIC L"document-statistic" #define META_INFO_MODIFIED L"date" #define META_INFO_DOCUMENT_NUMBER L"editing-cycles" #define META_INFO_EDITING_TIME L"editing-duration" #define META_INFO_LANGUAGE L"language" #define META_INFO_CREATOR L"creator" #define META_INFO_CREATION L"creation-date" #define META_INFO_GENERATOR L"generator" #define CONTENT_TEXT_A L"a" #define CONTENT_TEXT_P L"p" #define CONTENT_TEXT_H L"h" #define CONTENT_TEXT_SPAN L"span" #define CONTENT_TEXT_SEQUENCE L"sequence" #define CONTENT_TEXT_BOOKMARK_REF L"bookmark-ref" #define CONTENT_TEXT_INDEX_TITLE_TEMPLATE L"index-title-template" #define CONTENT_TEXT_STYLENAME L"style-name" #define CONTENT_STYLE_STYLE L"style" #define CONTENT_STYLE_STYLE_NAME L"name" #define CONTENT_STYLE_PROPERTIES L"properties" #define CONTENT_TEXT_STYLE_PROPERTIES L"text-properties" // added for OASIS Open Office XML format. #define CONTENT_STYLE_PROPERTIES_LANGUAGE L"language" #define CONTENT_STYLE_PROPERTIES_COUNTRY L"country" #define CONTENT_STYLE_PROPERTIES_LANGUAGEASIAN L"language-asian" #define CONTENT_STYLE_PROPERTIES_COUNTRYASIAN L"country-asian" #endif <|endoftext|>
<commit_before>// Copyright (c) 2016 Kasper Kronborg Isager and Radoslaw Niemczyk. #include "vector.hpp" #include <iostream> namespace lsh { /** * Create a new vector from existing component chunks. * * @param components The existing component chunks. * @param size The number of components. */ vector::vector(const std::vector<unsigned int>& components, unsigned int size) { this->size_ = size; unsigned int n = components.size(); for (unsigned int i = 0; i < n; i++) { this->components_.push_back(components[i]); } } /** * Construct a new vector. * * @param components The components of the vector. */ vector::vector(const std::vector<bool>& components) { this->size_ = components.size(); unsigned int s = this->size_; unsigned int c = this->chunk_size_; unsigned int i = 0; unsigned char k = 0; while (i < s) { this->components_.push_back(0); unsigned int n = i + c > s ? s - i : c; for (unsigned int j = 0; j < n; j++) { this->components_[k] |= components[i + j] << (n - j - 1); } i += n; k += 1; } } /** * Get the number of components in this vector. * * @return The number of components in this vector. */ unsigned int vector::size() const { return this->size_; } /** * Get the component at the specified index of this vector. * * @param index The index of the component to get. * @return The component at the index. */ bool vector::get(unsigned int index) const { unsigned int s = this->size_; unsigned int c = this->chunk_size_; if (index >= s) { return -1; } unsigned int d = index / s; unsigned int j = d * s; unsigned int p = j + c > s ? s - j : c; return (this->components_[d] >> (p - (index % s) - 1)) & 1; } /** * Get a string representation of this vector. * * @return The string representation of the vector. */ std::string vector::to_string() const { unsigned int n = this->size_; std::string value = "Vector["; for (unsigned int i = 0; i < n; i++) { value += std::to_string(this->get(i)); } return value + "]"; } /** * Check if this vector equals another vector. * * @param vector The other vector. * @return `true` if this vector equals the other vector, otherwise `false`. */ bool vector::operator==(const vector& vector) const { return vector::distance(*this, vector) == 0; } /** * Compute the dot product of this and another vector. * * @param vector The other vector. * @return The dot product of this and another vector. */ unsigned int vector::operator*(const vector& vector) const { unsigned int d = 0; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { d += __builtin_popcount(this->components_[i] & vector.components_[i]); } return d; } /** * Compute the dot product of this vector and an integer. * * @param integer The integer. * @return The dot product of this vector and an integer. */ unsigned int vector::operator*(unsigned int integer) const { unsigned int d = 0; unsigned int s = this->size_; unsigned int c = this->chunk_size_; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { // Compute the starting index of the current chunk. unsigned int j = c * i; // Compute the number of bits in the current chunk. unsigned int m = j + c > s ? s - j : c; // Grab the bits of the integer that correspond to the current chunk. unsigned int b = (integer >> (s - j - m)) % (1 << m); d += __builtin_popcount(this->components_[i] & b); } return d; } /** * Compute the bitwise AND of this and another vector. * * @param vector The other vector. * @return The bitwise AND of this and another vector. */ vector vector::operator&(const vector& vector) const { std::vector<unsigned int> c; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { c.push_back(this->components_[i] & vector.components_[i]); } return lsh::vector(c, this->size_); } /** * Compupte the hash of this vector. * * @return The hash of this vector. */ int vector::hash() const { unsigned int n = this->components_.size(); unsigned long b = 7; for (unsigned int i = 0; i < n; i++) { b = 31 * b + this->components_[i]; } return b ^ (b >> 32); } /** * Compute the distance between two vectors. * * @see http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan * * @param u The first vector. * @param v The second vector. * @return The distance between the two vectors. */ int vector::distance(const vector& u, const vector& v) { unsigned int d = 0; unsigned int n = u.components_.size(); for (unsigned int i = 0; i < n; i++) { unsigned int x = u.components_[i] ^ v.components_[i]; while (x) { x &= x - 1; d++; } } return d; } /** * Construct a random vector of a given dimensionality. * * @param dimensions The number of dimensions in the vector. * @return The randomly generated vector. */ vector vector::random(unsigned int dimensions) { std::random_device random; std::mt19937 generator(random()); std::uniform_int_distribution<bool> components(0, 1); std::vector<bool> c; for (unsigned int i = 0; i < dimensions; i++) { c.push_back(components(generator)); } return vector(c); } } <commit_msg>Bit of refactoring, for consistency<commit_after>// Copyright (c) 2016 Kasper Kronborg Isager and Radoslaw Niemczyk. #include "vector.hpp" #include <iostream> namespace lsh { /** * Create a new vector from existing component chunks. * * @param components The existing component chunks. * @param size The number of components. */ vector::vector(const std::vector<unsigned int>& components, unsigned int size) { this->size_ = size; unsigned int n = components.size(); for (unsigned int i = 0; i < n; i++) { this->components_.push_back(components[i]); } } /** * Construct a new vector. * * @param components The components of the vector. */ vector::vector(const std::vector<bool>& components) { this->size_ = components.size(); unsigned int s = this->size_; unsigned int c = this->chunk_size_; unsigned int i = 0; unsigned char k = 0; while (i < s) { this->components_.push_back(0); // Compute the number of bits in the current chunk. unsigned int b = i + c > s ? s - i : c; for (unsigned int j = 0; j < b; j++) { this->components_[k] |= components[i + j] << (b - j - 1); } i += b; k += 1; } } /** * Get the number of components in this vector. * * @return The number of components in this vector. */ unsigned int vector::size() const { return this->size_; } /** * Get the component at the specified index of this vector. * * @param index The index of the component to get. * @return The component at the index. */ bool vector::get(unsigned int index) const { unsigned int s = this->size_; unsigned int c = this->chunk_size_; if (index >= s) { return -1; } // Compute the index of the target chunk. unsigned int d = index / s; // Compute the index of the first bit of the target chunk. unsigned int j = d * s; // Compute the number of bits in the target chunk. unsigned int b = j + c > s ? s - j : c; return (this->components_[d] >> (b - (index % s) - 1)) & 1; } /** * Get a string representation of this vector. * * @return The string representation of the vector. */ std::string vector::to_string() const { unsigned int n = this->size_; std::string value = "Vector["; for (unsigned int i = 0; i < n; i++) { value += std::to_string(this->get(i)); } return value + "]"; } /** * Check if this vector equals another vector. * * @param vector The other vector. * @return `true` if this vector equals the other vector, otherwise `false`. */ bool vector::operator==(const vector& vector) const { return vector::distance(*this, vector) == 0; } /** * Compute the dot product of this and another vector. * * @param vector The other vector. * @return The dot product of this and another vector. */ unsigned int vector::operator*(const vector& vector) const { unsigned int d = 0; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { d += __builtin_popcount(this->components_[i] & vector.components_[i]); } return d; } /** * Compute the dot product of this vector and an integer. * * @param integer The integer. * @return The dot product of this vector and an integer. */ unsigned int vector::operator*(unsigned int integer) const { unsigned int d = 0; unsigned int s = this->size_; unsigned int c = this->chunk_size_; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { // Compute the index of the first bit of the current chunk. unsigned int j = c * i; // Compute the number of bits in the current chunk. unsigned int m = j + c > s ? s - j : c; // Grab the bits of the integer that correspond to the current chunk. unsigned int b = (integer >> (s - j - m)) % (1 << m); d += __builtin_popcount(this->components_[i] & b); } return d; } /** * Compute the bitwise AND of this and another vector. * * @param vector The other vector. * @return The bitwise AND of this and another vector. */ vector vector::operator&(const vector& vector) const { std::vector<unsigned int> c; unsigned int n = this->components_.size(); for (unsigned int i = 0; i < n; i++) { c.push_back(this->components_[i] & vector.components_[i]); } return lsh::vector(c, this->size_); } /** * Compupte the hash of this vector. * * @return The hash of this vector. */ int vector::hash() const { unsigned int n = this->components_.size(); unsigned long h = 7; for (unsigned int i = 0; i < n; i++) { h = 31 * h + this->components_[i]; } return h ^ (h >> 32); } /** * Compute the distance between two vectors. * * @see http://graphics.stanford.edu/~seander/bithacks.html#CountBitsSetKernighan * * @param u The first vector. * @param v The second vector. * @return The distance between the two vectors. */ int vector::distance(const vector& u, const vector& v) { unsigned int d = 0; unsigned int n = u.components_.size(); for (unsigned int i = 0; i < n; i++) { unsigned int x = u.components_[i] ^ v.components_[i]; while (x) { x &= x - 1; d++; } } return d; } /** * Construct a random vector of a given dimensionality. * * @param dimensions The number of dimensions in the vector. * @return The randomly generated vector. */ vector vector::random(unsigned int dimensions) { std::random_device random; std::mt19937 generator(random()); std::uniform_int_distribution<bool> components(0, 1); std::vector<bool> c; for (unsigned int i = 0; i < dimensions; i++) { c.push_back(components(generator)); } return vector(c); } } <|endoftext|>
<commit_before>#include "SysConfig.h" #if(HAS_PCA9539) #include <CI2C.h> #include "CPCA9539.h" #include "CTimer.h" #include "NDataManager.h" namespace { CTimer pcaSampleTimer; uint8_t counter; uint8_t value; bool firstPass; } CPCA9539::CPCA9539( CI2C *i2cInterfaceIn ) : m_pca( i2cInterfaceIn ) { } void CPCA9539::Initialize() { Serial.println( "CPCA9539.Status:INIT;" ); //Timer resets pcaSampleTimer.Reset(); counter = 1; //Expander init m_pca.Initialize(); m_pca.PinMode( OUTPUT ); Serial.println( "CPCA9539.Status:POST_INIT;"); } void CPCA9539::Update( CCommand &commandIn ) { if( pcaSampleTimer.HasElapsed( 500 ) ) { KnightRider(); } } void CPCA9539::KnightRider() { if( firstPass ) { value = ~(counter << 1) & bitmask; auto ret = m_pca.DigitalWriteDecimal( value ); if( ret != pca9539::ERetCode::SUCCESS ) { Serial.println(ret); } if( counter == 16 ) { firstPass = false; } } else { value = ~(counter >> 1) & bitmask; auto ret = m_pca.DigitalWriteDecimal( counter ); if( ret != pca9539::ERetCode::SUCCESS ) { Serial.println(ret); } if( counter == 1 ) { firstPass = true; } } } #endif<commit_msg>bitmasking<commit_after>#include "SysConfig.h" #if(HAS_PCA9539) #include <CI2C.h> #include "CPCA9539.h" #include "CTimer.h" #include "NDataManager.h" namespace { CTimer pcaSampleTimer; uint8_t counter; uint8_t value; uint8_t bitmask = 0x1F; bool firstPass; } CPCA9539::CPCA9539( CI2C *i2cInterfaceIn ) : m_pca( i2cInterfaceIn ) { } void CPCA9539::Initialize() { Serial.println( "CPCA9539.Status:INIT;" ); //Timer resets pcaSampleTimer.Reset(); counter = 1; //Expander init m_pca.Initialize(); m_pca.PinMode( OUTPUT ); Serial.println( "CPCA9539.Status:POST_INIT;"); } void CPCA9539::Update( CCommand &commandIn ) { if( pcaSampleTimer.HasElapsed( 500 ) ) { KnightRider(); } } void CPCA9539::KnightRider() { if( firstPass ) { value = ~(counter << 1) & bitmask; auto ret = m_pca.DigitalWriteDecimal( value ); if( ret != pca9539::ERetCode::SUCCESS ) { Serial.println(ret); } if( counter == 16 ) { firstPass = false; } } else { value = ~(counter >> 1) & bitmask; auto ret = m_pca.DigitalWriteDecimal( counter ); if( ret != pca9539::ERetCode::SUCCESS ) { Serial.println(ret); } if( counter == 1 ) { firstPass = true; } } } #endif<|endoftext|>
<commit_before>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \authors (rdo@rk9.bmstu.ru) \authors (lord.tiran@gmail.com) \date 10.05.2009 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <iostream> #define BOOST_TEST_MODULE RDORuntime_Fuzzy_Test #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdo_runtime.h" #include "simulator/runtime/rdo_fuzzy.h" // -------------------------------------------------------------------------------- OPEN_RDO_RUNTIME_NAMESPACE BOOST_AUTO_TEST_SUITE(RDORuntime_Fuzzy_Test) BOOST_AUTO_TEST_CASE(DefineAreaTest) { LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create(); BOOST_CHECK(pRuntime); LPDefineArea pDefineAreaEmpty = rdo::Factory<DefineArea>::create(); BOOST_CHECK(pDefineAreaEmpty); LPDefineArea pDefineArea = rdo::Factory<DefineArea>::create(1.0, 5.0); BOOST_CHECK(pDefineArea); } BOOST_AUTO_TEST_CASE(FuzzySetTest) { LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create(); BOOST_CHECK(pRuntime); LPFuzzySet pInfinityFuzzySet = rdo::Factory<FuzzySet>::create(); BOOST_CHECK(pInfinityFuzzySet); LPFuzzySet pCopyFuzzySet = rdo::Factory<FuzzySet>::create(pInfinityFuzzySet); BOOST_CHECK(pCopyFuzzySet); LPDefineArea pDefineArea = rdo::Factory<DefineArea>::create(0.0, 100.0); BOOST_CHECK(pDefineArea); LPFuzzySet pFuzzySet = rdo::Factory<FuzzySet>::create(pDefineArea); BOOST_CHECK(pFuzzySet); LPFuzzySet pSet = rdo::Factory<FuzzySet>::create(); tstring stringPresentation = pSet->getAsString(); std::cout << stringPresentation << std::endl; BOOST_CHECK(stringPresentation == _T("<1/0.10> <2/0.20> <3/1.00> <5/0.50> <6/0.40> <7/0.20> <9/0.10>")); RDOValue repeatValue = 3.0; pSet->append(repeatValue, 0.3); BOOST_CHECK(pSet); BOOST_CHECK(pSet->getAsString() == _T("<1/0.10> <2/0.20> <3/1.00> <5/0.50> <6/0.40> <7/0.20> <9/0.10>")); pSet->operator[](repeatValue) = 0.3; BOOST_CHECK(pSet->getAsString() == _T("<1/0.10> <2/0.20> <3/0.30> <5/0.50> <6/0.40> <7/0.20> <9/0.10>")); LPFuzzySet pConSet = MemberFunctionProperties::a_con(pSet); BOOST_CHECK(pConSet); tstring stringPresentation1 = pConSet->getAsString(); std::cout << stringPresentation1 << std::endl; LPFuzzySet pDilSet = MemberFunctionProperties::a_dil(pSet); BOOST_CHECK(pDilSet); tstring stringPresentation2 = pDilSet->getAsString(); std::cout << stringPresentation2 << std::endl; LPFuzzySet pUnaryMinusSet = MemberFunctionProperties::u_minus(pSet); BOOST_CHECK(pUnaryMinusSet); tstring stringPresentation3 = pUnaryMinusSet->getAsString(); std::cout << stringPresentation3 << std::endl; LPFuzzySet pScaleSet = MemberFunctionProperties::u_scale(pSet, 4.0); BOOST_CHECK(pScaleSet); tstring stringPresentation4 = pScaleSet->getAsString(); std::cout << stringPresentation4 << std::endl; LPFuzzySet pSupplement = MemberFunctionProperties::supplement(pSet); BOOST_CHECK(pSupplement); tstring stringPresentation5 = pSupplement->getAsString(); std::cout << stringPresentation5 << std::endl; LPFuzzySet pAlphaTest = MemberFunctionProperties::alpha(pSet, 0.3); BOOST_CHECK(pAlphaTest); tstring stringPresentation7 = pAlphaTest->getAsString(); std::cout << "pAlphaTest: " <<stringPresentation7 <<std::endl; LPFuzzySet pMultTest = MemberFunctionProperties::a_mult(pSet, pSupplement); BOOST_CHECK(pMultTest); tstring stringPresentationMult = pMultTest->getAsString(); std::cout << "pMultTest: " << stringPresentationMult <<std::endl; LPFuzzySet pMultTestDown = MemberFunctionProperties::a_mult(pSet, pScaleSet); BOOST_CHECK(pMultTestDown); tstring stringPresentationMultDown = pMultTestDown->getAsString(); std::cout << "pMultTest: " << stringPresentationMultDown <<std::endl; RDOValue defuzzyficationValue = MemberFunctionProperties::defuzzyfication(pSet); BOOST_CHECK(defuzzyficationValue); tstring stringPresentation9 = defuzzyficationValue.getAsString(); std::cout << stringPresentation9 <<std::endl; } BOOST_AUTO_TEST_CASE(TermTest) { LPFuzzySet pSet = rdo::Factory<FuzzySet>::create(); tstring testname = "test"; LPRDOFuzzyTerm pTerm = rdo::Factory<RDOFuzzyTerm>::create(testname, pSet); tstring name = pTerm->getName(); std::cout << name << std::endl; BOOST_CHECK(pTerm); LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create(); BOOST_CHECK(pRuntime); LPDefineArea pDefineArea = rdo::Factory<DefineArea>::create(0.0, 100.0); BOOST_CHECK(pDefineArea); LPFuzzySet pFuzzySet = rdo::Factory<FuzzySet>::create(pDefineArea); BOOST_CHECK(pFuzzySet); LPRDOFuzzyTerm pTerm3 = rdo::Factory<RDOFuzzyTerm>::create(_T("term"), pFuzzySet); BOOST_CHECK(pTerm3); tstring name3 = pTerm3->getName(); std::cout << name3 << std::endl; } BOOST_AUTO_TEST_CASE(VariableTest) { LPDefineArea pDefineArea1 = rdo::Factory<DefineArea>::create(0.0, 20.0); BOOST_CHECK(pDefineArea1); LPDefineArea pDefineArea2 = rdo::Factory<DefineArea>::create(10.0, 20.0); BOOST_CHECK(pDefineArea2); LPFuzzySet pFuzzySet1 = rdo::Factory<FuzzySet>::create(pDefineArea1); BOOST_CHECK(pFuzzySet1); LPFuzzySet pFuzzySet2 = rdo::Factory<FuzzySet>::create(pDefineArea2); BOOST_CHECK(pFuzzySet2); LPRDOFuzzyTerm pTerm1 = rdo::Factory<RDOFuzzyTerm>::create(_T("term1"), pFuzzySet1); BOOST_CHECK(pTerm1); LPRDOFuzzyTerm pTerm2 = rdo::Factory<RDOFuzzyTerm>::create(_T("term2"), pFuzzySet2); BOOST_CHECK(pTerm2); tstring name1 = pTerm1->getName(); std::cout << name1 << std::endl; LPRDOLingvoVariable pVariable = rdo::Factory<RDOLingvoVariable>::create(pTerm1,_T("test")); BOOST_CHECK(pVariable); LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create(); BOOST_CHECK(pRuntime); LPDefineArea pDefineArea = rdo::Factory<DefineArea>::create(0.0, 100.0); BOOST_CHECK(pDefineArea); LPFuzzySet pFuzzySet = rdo::Factory<FuzzySet>::create(pDefineArea); BOOST_CHECK(pFuzzySet); pFuzzySet->append(5,0.5); BOOST_CHECK(pFuzzySet); pFuzzySet->append(1,0.1); BOOST_CHECK(pFuzzySet); pFuzzySet->append(2,0.2); BOOST_CHECK(pFuzzySet); pFuzzySet->append(3,1.0); BOOST_CHECK(pFuzzySet); pFuzzySet->append(6,0.4); BOOST_CHECK(pFuzzySet); pFuzzySet->append(7,0.2); BOOST_CHECK(pFuzzySet); pFuzzySet->append(9,0.1); BOOST_CHECK(pFuzzySet); LPRDOFuzzyTerm pTerm4 = rdo::Factory<RDOFuzzyTerm>::create(_T("term4"), pFuzzySet); BOOST_CHECK(pTerm4); pVariable->append(pTerm4->getName(), pTerm4->getFuzzySetDefinition()); pVariable->setName(_T("testName")); RDOValue value = 1.0; LPRDOLingvoVariable pVariable2 = rdo::Factory<RDOLingvoVariable>::create(value, pVariable); BOOST_CHECK(pVariable2); RDOValue valueTrueOn0_2 = 7.0; LPRDOLingvoVariable fuzzyVariable1 = MemberFunctionProperties::fuzzyfication(valueTrueOn0_2, pVariable); BOOST_CHECK(fuzzyVariable1); RDOValue valueTrueOn0_0 = 10.0; LPRDOLingvoVariable fuzzyVariable2 = MemberFunctionProperties::fuzzyfication(valueTrueOn0_0, pVariable); BOOST_CHECK(fuzzyVariable2); } BOOST_AUTO_TEST_CASE(MemberFunctionProperties) { } BOOST_AUTO_TEST_SUITE_END() // RDORuntime_Fuzzy_Test CLOSE_RDO_RUNTIME_NAMESPACE<commit_msg> - исправления<commit_after>/*! \copyright (c) RDO-Team, 2011 \file main.cpp \authors (rdo@rk9.bmstu.ru) \authors (lord.tiran@gmail.com) \date 10.05.2009 \brief \indent 4T */ // ---------------------------------------------------------------------------- PCH // ----------------------------------------------------------------------- INCLUDES #include <iostream> #define BOOST_TEST_MODULE RDORuntime_Fuzzy_Test #include <boost/test/included/unit_test.hpp> // ----------------------------------------------------------------------- SYNOPSIS #include "simulator/runtime/rdo_runtime.h" #include "simulator/runtime/rdo_fuzzy.h" // -------------------------------------------------------------------------------- OPEN_RDO_RUNTIME_NAMESPACE BOOST_AUTO_TEST_SUITE(RDORuntime_Fuzzy_Test) BOOST_AUTO_TEST_CASE(DefineAreaTest) { LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create(); BOOST_CHECK(pRuntime); LPDefineArea pDefineAreaEmpty = rdo::Factory<DefineArea>::create(); BOOST_CHECK(pDefineAreaEmpty); LPDefineArea pDefineArea = rdo::Factory<DefineArea>::create(1.0, 5.0); BOOST_CHECK(pDefineArea); } BOOST_AUTO_TEST_CASE(FuzzySetTest) { LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create(); BOOST_CHECK(pRuntime); LPFuzzySet pInfinityFuzzySet = rdo::Factory<FuzzySet>::create(); BOOST_CHECK(pInfinityFuzzySet); LPFuzzySet pCopyFuzzySet = rdo::Factory<FuzzySet>::create(pInfinityFuzzySet); BOOST_CHECK(pCopyFuzzySet); LPDefineArea pDefineArea = rdo::Factory<DefineArea>::create(0.0, 100.0); BOOST_CHECK(pDefineArea); LPFuzzySet pFuzzySet = rdo::Factory<FuzzySet>::create(pDefineArea); BOOST_CHECK(pFuzzySet); LPFuzzySet pSet = rdo::Factory<FuzzySet>::create(); tstring stringPresentation = pSet->getAsString(); BOOST_CHECK(stringPresentation == _T("[empty value]")); pSet->append(1,0.10); pSet->append(2,0.20); pSet->append(3,1.00); pSet->append(5,0.50); pSet->append(6,0.40); pSet->append(7,0.20); pSet->append(9,0.10); BOOST_CHECK(pSet->getAsString() == _T("<1/0.10> <2/0.20> <3/1.00> <5/0.50> <6/0.40> <7/0.20> <9/0.10>")); RDOValue repeatValue = 3.0; pSet->append(repeatValue, 0.3); BOOST_CHECK(pSet->getAsString() == _T("<1/0.10> <2/0.20> <3/1.00> <5/0.50> <6/0.40> <7/0.20> <9/0.10>")); pSet->operator[](repeatValue) = 0.3; BOOST_CHECK(pSet->getAsString() == _T("<1/0.10> <2/0.20> <3/0.30> <5/0.50> <6/0.40> <7/0.20> <9/0.10>")); LPFuzzySet pConSet = MemberFunctionProperties::a_con(pSet); BOOST_CHECK(pConSet->getAsString() == _T("<1/0.01> <2/0.04> <3/0.09> <5/0.25> <6/0.16> <7/0.04> <9/0.01>")); LPFuzzySet pDilSet = MemberFunctionProperties::a_dil(pSet); BOOST_CHECK(pDilSet->getAsString() == _T("<1/0.32> <2/0.45> <3/0.55> <5/0.71> <6/0.63> <7/0.45> <9/0.32>")); LPFuzzySet pUnaryMinusSet = MemberFunctionProperties::u_minus(pSet); BOOST_CHECK(pUnaryMinusSet->getAsString() == _T("<-9/0.10> <-7/0.20> <-6/0.40> <-5/0.50> <-3/0.30> <-2/0.20> <-1/0.10>")); LPFuzzySet pScaleSet = MemberFunctionProperties::u_scale(pSet, 4.0); BOOST_CHECK(pScaleSet->getAsString() == _T("<4/0.10> <8/0.20> <12/0.30> <20/0.50> <24/0.40> <28/0.20> <36/0.10>")); LPFuzzySet pSupplement = MemberFunctionProperties::supplement(pSet); BOOST_CHECK(pSupplement->getAsString() == _T("<1/0.90> <2/0.80> <3/0.70> <5/0.50> <6/0.60> <7/0.80> <9/0.90>")); LPFuzzySet pAlphaTest = MemberFunctionProperties::alpha(pSet, 0.3); BOOST_CHECK(pAlphaTest->getAsString() == _T("<3/0.30> <5/0.50> <6/0.40>")); LPFuzzySet pMultTest = MemberFunctionProperties::a_mult(pSet, pSupplement); BOOST_CHECK(pMultTest->getAsString() == _T("<1/0.09> <2/0.16> <3/0.21> <5/0.25> <6/0.24> <7/0.16> <9/0.09>")); LPFuzzySet pMultTestDown = MemberFunctionProperties::a_mult(pSet, pScaleSet); BOOST_CHECK(pMultTestDown->getAsString() == _T("[empty value]")); RDOValue defuzzyficationValue = MemberFunctionProperties::defuzzyfication(pSet); BOOST_CHECK(defuzzyficationValue); tstring stringPresentation9 = defuzzyficationValue.getAsString(); std::cout << stringPresentation9 <<std::endl; } BOOST_AUTO_TEST_CASE(TermTest) { LPFuzzySet pSet = rdo::Factory<FuzzySet>::create(); tstring testname = "test"; LPRDOFuzzyTerm pTerm = rdo::Factory<RDOFuzzyTerm>::create(testname, pSet); BOOST_CHECK(pTerm->getName() == _T("test")); LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create(); BOOST_CHECK(pRuntime); LPDefineArea pDefineArea = rdo::Factory<DefineArea>::create(0.0, 100.0); BOOST_CHECK(pDefineArea); LPFuzzySet pFuzzySet = rdo::Factory<FuzzySet>::create(pDefineArea); BOOST_CHECK(pFuzzySet); LPRDOFuzzyTerm pTerm3 = rdo::Factory<RDOFuzzyTerm>::create(_T("term"), pFuzzySet); BOOST_CHECK(pTerm3->getName() == _T("term")); } BOOST_AUTO_TEST_CASE(VariableTest) { LPDefineArea pDefineArea1 = rdo::Factory<DefineArea>::create(0.0, 20.0); BOOST_CHECK(pDefineArea1); LPDefineArea pDefineArea2 = rdo::Factory<DefineArea>::create(10.0, 20.0); BOOST_CHECK(pDefineArea2); LPFuzzySet pFuzzySet1 = rdo::Factory<FuzzySet>::create(pDefineArea1); BOOST_CHECK(pFuzzySet1); LPFuzzySet pFuzzySet2 = rdo::Factory<FuzzySet>::create(pDefineArea2); BOOST_CHECK(pFuzzySet2); LPRDOFuzzyTerm pTerm1 = rdo::Factory<RDOFuzzyTerm>::create(_T("term1"), pFuzzySet1); BOOST_CHECK(pTerm1); LPRDOFuzzyTerm pTerm2 = rdo::Factory<RDOFuzzyTerm>::create(_T("term2"), pFuzzySet2); BOOST_CHECK(pTerm2); tstring name1 = pTerm1->getName(); BOOST_CHECK(name1 == _T("term1")); LPRDOLingvoVariable pVariable = rdo::Factory<RDOLingvoVariable>::create(pTerm1,_T("test")); BOOST_CHECK(pVariable); LPRDORuntime pRuntime = rdo::Factory<RDORuntime>::create(); BOOST_CHECK(pRuntime); LPDefineArea pDefineArea = rdo::Factory<DefineArea>::create(0.0, 100.0); BOOST_CHECK(pDefineArea); LPFuzzySet pFuzzySet = rdo::Factory<FuzzySet>::create(pDefineArea); BOOST_CHECK(pFuzzySet); pFuzzySet->append(5,0.5); BOOST_CHECK(pFuzzySet); pFuzzySet->append(1,0.1); BOOST_CHECK(pFuzzySet); pFuzzySet->append(2,0.2); BOOST_CHECK(pFuzzySet); pFuzzySet->append(3,1.0); BOOST_CHECK(pFuzzySet); pFuzzySet->append(6,0.4); BOOST_CHECK(pFuzzySet); pFuzzySet->append(7,0.2); BOOST_CHECK(pFuzzySet); pFuzzySet->append(9,0.1); BOOST_CHECK(pFuzzySet); LPRDOFuzzyTerm pTerm4 = rdo::Factory<RDOFuzzyTerm>::create(_T("term4"), pFuzzySet); BOOST_CHECK(pTerm4); pVariable->append(pTerm4->getName(), pTerm4->getFuzzySetDefinition()); pVariable->setName(_T("testName")); RDOValue value = 1.0; LPRDOLingvoVariable pVariable2 = rdo::Factory<RDOLingvoVariable>::create(value, pVariable); BOOST_CHECK(pVariable2); RDOValue valueTrueOn0_2 = 7.0; LPRDOLingvoVariable fuzzyVariable1 = MemberFunctionProperties::fuzzyfication(valueTrueOn0_2, pVariable); BOOST_CHECK(fuzzyVariable1); RDOValue valueTrueOn0_0 = 10.0; LPRDOLingvoVariable fuzzyVariable2 = MemberFunctionProperties::fuzzyfication(valueTrueOn0_0, pVariable); BOOST_CHECK(fuzzyVariable2); } BOOST_AUTO_TEST_SUITE_END() // RDORuntime_Fuzzy_Test CLOSE_RDO_RUNTIME_NAMESPACE<|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: startmenuicon.cxx,v $ * * $Revision: 1.10 $ * * last change: $Author: vg $ $Date: 2008-03-18 12:55:01 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #define _WIN32_WINDOWS 0x0410 #ifdef _MSC_VER #pragma warning(push, 1) /* disable warnings within system headers */ #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <msiquery.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <malloc.h> #ifdef UNICODE #define _UNICODE #define _tstring wstring #else #define _tstring string #endif #include <tchar.h> #include <string> std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty ) { std::_tstring result; TCHAR szDummy[1] = TEXT(""); DWORD nChars = 0; if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA ) { DWORD nBytes = ++nChars * sizeof(TCHAR); LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes)); ZeroMemory( buffer, nBytes ); MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars); result = buffer; } return result; } /* Called during installation to customize the start menu folder icon. See: http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/custom.asp */ extern "C" UINT __stdcall InstallStartmenuFolderIcon( MSIHANDLE handle ) { std::_tstring sOfficeMenuFolder = GetMsiProperty( handle, TEXT("OfficeMenuFolder") ); std::_tstring sDesktopFile = sOfficeMenuFolder + TEXT("Desktop.ini"); // MessageBox(NULL, sDesktopFile.c_str(), TEXT("OfficeMenuFolder"), MB_OK | MB_ICONINFORMATION); std::_tstring sIconFile = GetMsiProperty( handle, TEXT("OFFICEINSTALLLOCATION") ) + TEXT("program\\soffice.exe"); OSVERSIONINFO osverinfo; osverinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx( &osverinfo ); if (osverinfo.dwMajorVersion < 6 /* && osverinfo.dwMinorVersion */ ) { // This icon (18) is a Windows folder until XP Version (number is 0 based) WritePrivateProfileString( TEXT(".ShellClassInfo"), TEXT("IconFile"), sIconFile.c_str(), sDesktopFile.c_str() ); // FYI: in tool 'ResHack' this icon can be found on position '19' (number is 1 based) WritePrivateProfileString( TEXT(".ShellClassInfo"), TEXT("IconIndex"), TEXT("18"), sDesktopFile.c_str() ); } // else // { // // at the moment there exists no Vista Icon, so we use the default folder icon. // // add the icon into desktop/util/verinfo.rc // } // The value '0' is to avoid a message like "You Are Deleting a System Folder" warning when deleting or moving the folder. WritePrivateProfileString( TEXT(".ShellClassInfo"), TEXT("ConfirmFileOp"), TEXT("0"), sDesktopFile.c_str() ); /* WritePrivateProfileString( TEXT(".ShellClassInfo"), TEXT("InfoTip"), TEXT("StarOffice Productivity Suite"), sDesktopFile.c_str() ); */ SetFileAttributes( sDesktopFile.c_str(), FILE_ATTRIBUTE_HIDDEN ); SetFileAttributes( sOfficeMenuFolder.c_str(), FILE_ATTRIBUTE_SYSTEM ); return ERROR_SUCCESS; } extern "C" UINT __stdcall DeinstallStartmenuFolderIcon(MSIHANDLE handle) { std::_tstring sOfficeMenuFolder = GetMsiProperty( handle, TEXT("OfficeMenuFolder") ); std::_tstring sDesktopFile = sOfficeMenuFolder + TEXT("Desktop.ini"); SetFileAttributes( sDesktopFile.c_str(), FILE_ATTRIBUTE_NORMAL ); DeleteFile( sDesktopFile.c_str() ); SetFileAttributes( sOfficeMenuFolder.c_str(), FILE_ATTRIBUTE_NORMAL ); return ERROR_SUCCESS; } <commit_msg>INTEGRATION: CWS changefileheader (1.10.4); FILE MERGED 2008/03/31 16:08:01 rt 1.10.4.1: #i87441# Change license header to LPGL v3.<commit_after>/************************************************************************* * * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * Copyright 2008 by Sun Microsystems, Inc. * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: startmenuicon.cxx,v $ * $Revision: 1.11 $ * * This file is part of OpenOffice.org. * * OpenOffice.org is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * only, as published by the Free Software Foundation. * * OpenOffice.org 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 version 3 for more details * (a copy is included in the LICENSE file that accompanied this code). * * You should have received a copy of the GNU Lesser General Public License * version 3 along with OpenOffice.org. If not, see * <http://www.openoffice.org/license.html> * for a copy of the LGPLv3 License. * ************************************************************************/ #define _WIN32_WINDOWS 0x0410 #ifdef _MSC_VER #pragma warning(push, 1) /* disable warnings within system headers */ #endif #define WIN32_LEAN_AND_MEAN #include <windows.h> #include <msiquery.h> #ifdef _MSC_VER #pragma warning(pop) #endif #include <malloc.h> #ifdef UNICODE #define _UNICODE #define _tstring wstring #else #define _tstring string #endif #include <tchar.h> #include <string> std::_tstring GetMsiProperty( MSIHANDLE handle, const std::_tstring& sProperty ) { std::_tstring result; TCHAR szDummy[1] = TEXT(""); DWORD nChars = 0; if ( MsiGetProperty( handle, sProperty.c_str(), szDummy, &nChars ) == ERROR_MORE_DATA ) { DWORD nBytes = ++nChars * sizeof(TCHAR); LPTSTR buffer = reinterpret_cast<LPTSTR>(_alloca(nBytes)); ZeroMemory( buffer, nBytes ); MsiGetProperty(handle, sProperty.c_str(), buffer, &nChars); result = buffer; } return result; } /* Called during installation to customize the start menu folder icon. See: http://msdn.microsoft.com/library/en-us/shellcc/platform/shell/programmersguide/shell_basics/shell_basics_extending/custom.asp */ extern "C" UINT __stdcall InstallStartmenuFolderIcon( MSIHANDLE handle ) { std::_tstring sOfficeMenuFolder = GetMsiProperty( handle, TEXT("OfficeMenuFolder") ); std::_tstring sDesktopFile = sOfficeMenuFolder + TEXT("Desktop.ini"); // MessageBox(NULL, sDesktopFile.c_str(), TEXT("OfficeMenuFolder"), MB_OK | MB_ICONINFORMATION); std::_tstring sIconFile = GetMsiProperty( handle, TEXT("OFFICEINSTALLLOCATION") ) + TEXT("program\\soffice.exe"); OSVERSIONINFO osverinfo; osverinfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx( &osverinfo ); if (osverinfo.dwMajorVersion < 6 /* && osverinfo.dwMinorVersion */ ) { // This icon (18) is a Windows folder until XP Version (number is 0 based) WritePrivateProfileString( TEXT(".ShellClassInfo"), TEXT("IconFile"), sIconFile.c_str(), sDesktopFile.c_str() ); // FYI: in tool 'ResHack' this icon can be found on position '19' (number is 1 based) WritePrivateProfileString( TEXT(".ShellClassInfo"), TEXT("IconIndex"), TEXT("18"), sDesktopFile.c_str() ); } // else // { // // at the moment there exists no Vista Icon, so we use the default folder icon. // // add the icon into desktop/util/verinfo.rc // } // The value '0' is to avoid a message like "You Are Deleting a System Folder" warning when deleting or moving the folder. WritePrivateProfileString( TEXT(".ShellClassInfo"), TEXT("ConfirmFileOp"), TEXT("0"), sDesktopFile.c_str() ); /* WritePrivateProfileString( TEXT(".ShellClassInfo"), TEXT("InfoTip"), TEXT("StarOffice Productivity Suite"), sDesktopFile.c_str() ); */ SetFileAttributes( sDesktopFile.c_str(), FILE_ATTRIBUTE_HIDDEN ); SetFileAttributes( sOfficeMenuFolder.c_str(), FILE_ATTRIBUTE_SYSTEM ); return ERROR_SUCCESS; } extern "C" UINT __stdcall DeinstallStartmenuFolderIcon(MSIHANDLE handle) { std::_tstring sOfficeMenuFolder = GetMsiProperty( handle, TEXT("OfficeMenuFolder") ); std::_tstring sDesktopFile = sOfficeMenuFolder + TEXT("Desktop.ini"); SetFileAttributes( sDesktopFile.c_str(), FILE_ATTRIBUTE_NORMAL ); DeleteFile( sDesktopFile.c_str() ); SetFileAttributes( sOfficeMenuFolder.c_str(), FILE_ATTRIBUTE_NORMAL ); return ERROR_SUCCESS; } <|endoftext|>
<commit_before>// // // Copyright (C) 2005-2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <stdlib.h> // APPLICATION INCLUDES #include "os/OsConfigDb.h" #include "include/sipXmediaFactoryImpl.h" #include "include/CpPhoneMediaInterface.h" #include "net/SdpCodec.h" #include "mp/MpMediaTask.h" #include "mp/MpMisc.h" #include "mp/MpCodec.h" #include "mp/MpCallFlowGraph.h" #include "mp/dmaTask.h" #include "net/SdpCodecFactory.h" #include "mi/CpMediaInterfaceFactoryFactory.h" #ifdef INCLUDE_RTCP /* [ */ #include "rtcp/RTCManager.h" #endif /* INCLUDE_RTCP ] */ // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // GLOBAL FUNCTION #define CONFIG_PHONESET_SEND_INBAND_DTMF "PHONESET_SEND_INBAND_DTMF" #define MAX_MANAGED_FLOW_GRAPHS 16 // STATIC VARIABLE INITIALIZATIONS int sipXmediaFactoryImpl::miInstanceCount=0; static CpMediaInterfaceFactory* spFactory = NULL; static int siInstanceCount=0; extern "C" CpMediaInterfaceFactory* sipXmediaFactoryFactory(OsConfigDb* pConfigDb) { // TODO: Add locking if (spFactory == NULL) { spFactory = new CpMediaInterfaceFactory(); spFactory->setFactoryImplementation(new sipXmediaFactoryImpl(pConfigDb)); } siInstanceCount++ ; // Assert some sane value assert(siInstanceCount < 11) ; return spFactory; } extern "C" void sipxDestroyMediaFactoryFactory() { // TODO: Add locking siInstanceCount-- ; assert(siInstanceCount >= 0) ; if (siInstanceCount == 0) { if (spFactory) { delete spFactory ; spFactory = NULL ; } } } /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor sipXmediaFactoryImpl::sipXmediaFactoryImpl(OsConfigDb* pConfigDb) { int maxFlowGraph = -1 ; UtlString strInBandDTMF ; if (pConfigDb) { pConfigDb->get("PHONESET_MAX_ACTIVE_CALLS_ALLOWED", maxFlowGraph) ; pConfigDb->get(CONFIG_PHONESET_SEND_INBAND_DTMF, strInBandDTMF) ; strInBandDTMF.toUpper() ; OsSysLog::add(FAC_MP, PRI_DEBUG, "sipXmediaFactoryImpl::sipXmediaFactoryImpl maxFlowGraph = %d", maxFlowGraph); } // Max Flow graphs if (maxFlowGraph <=0 ) { maxFlowGraph = MAX_MANAGED_FLOW_GRAPHS; } if (miInstanceCount == 0) { mpStartUp(8000, 80, 16*maxFlowGraph, pConfigDb); } // Should we send inband DTMF by default? if (strInBandDTMF.compareTo("DISABLE") == 0) { MpCallFlowGraph::setInbandDTMF(false) ; } else { MpCallFlowGraph::setInbandDTMF(true) ; } // init the media processing task mpMediaTask = MpMediaTask::getMediaTask(maxFlowGraph); #ifdef INCLUDE_RTCP /* [ */ mpiRTCPControl = CRTCManager::getRTCPControl(); #endif /* INCLUDE_RTCP ] */ if (miInstanceCount == 0) { mpStartTasks(); } miGain = 7 ; ++miInstanceCount; } // Destructor sipXmediaFactoryImpl::~sipXmediaFactoryImpl() { // TODO: Shutdown --miInstanceCount; if (miInstanceCount == 0) { // Temporarily comment out this function because it causes the program hung. //mpStopTasks(); mpShutdown(); } } /* ============================ MANIPULATORS ============================== */ CpMediaInterface* sipXmediaFactoryImpl::createMediaInterface( const char* publicAddress, const char* localAddress, int numCodecs, SdpCodec* sdpCodecArray[], const char* locale, int expeditedIpTos, const char* szStunServer, int stunOptions, int iStunKeepAliveSecs ) { return new CpPhoneMediaInterface(this, publicAddress, localAddress, numCodecs, sdpCodecArray, locale, expeditedIpTos, szStunServer, iStunKeepAliveSecs) ; } OsStatus sipXmediaFactoryImpl::setSpeakerVolume(int iVolume) { OsStatus rc = OS_SUCCESS ; MpCodec_setVolume(iVolume) ; return rc ; } OsStatus sipXmediaFactoryImpl::setSpeakerDevice(const UtlString& device) { OsStatus rc = OS_SUCCESS ; DmaTask::setCallDevice(device.data()) ; return rc ; } OsStatus sipXmediaFactoryImpl::setMicrophoneGain(int iGain) { OsStatus rc ; miGain = iGain ; rc = MpCodec_setGain(miGain) ; return rc ; } OsStatus sipXmediaFactoryImpl::setMicrophoneDevice(const UtlString& device) { OsStatus rc = OS_SUCCESS ; DmaTask::setInputDevice(device.data()) ; return rc ; } OsStatus sipXmediaFactoryImpl::muteMicrophone(UtlBoolean bMute) { if (bMute) { MpCodec_setGain(0) ; } else { MpCodec_setGain(miGain) ; } return OS_SUCCESS ; } OsStatus sipXmediaFactoryImpl::enableAudioAEC(UtlBoolean bEnable) { return OS_SUCCESS; } OsStatus sipXmediaFactoryImpl::enableOutOfBandDTMF(UtlBoolean bEnable) { return OS_SUCCESS; } OsStatus sipXmediaFactoryImpl::buildCodecFactory(SdpCodecFactory *pFactory, const UtlString& sPreferences, const UtlString& sVideoPreferences, int* iRejected) { OsStatus rc = OS_FAILED; int numCodecs = 0; UtlString codecName; UtlString codecList; *iRejected = 0; #ifdef HAVE_GIPS /* [ */ numCodecs = 6; SdpCodec::SdpCodecTypes codecs[6]; codecs[0] = SdpCodec::SDP_CODEC_GIPS_PCMU; codecs[1] = SdpCodec::SDP_CODEC_GIPS_PCMA; codecs[2] = SdpCodec::SDP_CODEC_GIPS_IPCMU; codecs[3] = SdpCodec::SDP_CODEC_GIPS_IPCMA; codecs[4] = SdpCodec::SDP_CODEC_GIPS_IPCMWB; codecs[5] = SdpCodec::SDP_CODEC_TONES; #else /* HAVE_GIPS ] [ */ numCodecs = 3; SdpCodec::SdpCodecTypes codecs[3]; codecs[0] = SdpCodec::SDP_CODEC_GIPS_PCMU; codecs[1] = SdpCodec::SDP_CODEC_GIPS_PCMA; codecs[2] = SdpCodec::SDP_CODEC_TONES; #endif /* HAVE_GIPS ] */ if (pFactory) { pFactory->clearCodecs(); // add preferred codecs first if (sPreferences.length() > 0) { UtlString references = sPreferences; *iRejected = pFactory->buildSdpCodecFactory(references); OsSysLog::add(FAC_MP, PRI_DEBUG, "sipXmediaFactoryImpl::buildCodecFactory: sReferences = %s with NumReject %d", references.data(), *iRejected); // Now pick preferences out of all available codecs SdpCodec** codecsArray = NULL; pFactory->getCodecs(numCodecs, codecsArray); UtlString preferences; for (int i = 0; i < numCodecs; i++) { if (getCodecNameByType(codecsArray[i]->getCodecType(), codecName) == OS_SUCCESS) { preferences = preferences + " " + codecName; } } pFactory->clearCodecs(); *iRejected = pFactory->buildSdpCodecFactory(preferences); OsSysLog::add(FAC_MP, PRI_DEBUG, "sipXmediaFactoryImpl::buildCodecFactory: supported codecs = %s with NumReject %d", preferences.data(), *iRejected); // Free up the codecs and the array for (int i = 0; i < numCodecs; i++) { delete codecsArray[i]; codecsArray[i] = NULL; } delete[] codecsArray; codecsArray = NULL; rc = OS_SUCCESS; } else { // Build up the supported codecs *iRejected = pFactory->buildSdpCodecFactory(numCodecs, codecs); rc = OS_SUCCESS; } } return rc; } OsStatus sipXmediaFactoryImpl::updateVideoPreviewWindow(void* displayContext) { return OS_NOT_SUPPORTED ; } /* ============================ ACCESSORS ================================= */ OsStatus sipXmediaFactoryImpl::getSpeakerVolume(int& iVolume) const { OsStatus rc = OS_SUCCESS ; iVolume = MpCodec_getVolume() ; return rc ; } OsStatus sipXmediaFactoryImpl::getSpeakerDevice(UtlString& device) const { OsStatus rc = OS_SUCCESS ; device = DmaTask::getCallDevice() ; return rc ; } OsStatus sipXmediaFactoryImpl::getMicrophoneGain(int& iGain) const { OsStatus rc = OS_SUCCESS ; iGain = MpCodec_getGain() ; return rc ; } OsStatus sipXmediaFactoryImpl::getMicrophoneDevice(UtlString& device) const { OsStatus rc = OS_SUCCESS ; device = DmaTask::getMicDevice() ; return rc ; } OsStatus sipXmediaFactoryImpl::isAudioAECEnabled(UtlBoolean& bEnabled) const { bEnabled = false; return OS_SUCCESS; } OsStatus sipXmediaFactoryImpl::isOutOfBandDTMFEnabled(UtlBoolean& bEnabled) const { bEnabled = false; return OS_SUCCESS; } OsStatus sipXmediaFactoryImpl::getNumOfCodecs(int& iCodecs) const { iCodecs = 3; return OS_SUCCESS; } OsStatus sipXmediaFactoryImpl::getCodec(int iCodec, UtlString& codec, int &bandWidth) const { OsStatus rc = OS_SUCCESS; switch (iCodec) { #ifdef HAVE_GIPS /* [ */ case 0: codec = (const char*) SdpCodec::SDP_CODEC_GIPS_PCMU; break; case 1: codec = (const char*) SdpCodec::SDP_CODEC_GIPS_PCMA; break; #else /* HAVE_GIPS ] [ */ case 0: codec = (const char*) SdpCodec::SDP_CODEC_GIPS_PCMU; break; case 1: codec = (const char*) SdpCodec::SDP_CODEC_GIPS_PCMA; break; #endif /* HAVE_GIPS ] */ case 2: codec = (const char*) SdpCodec::SDP_CODEC_TONES; break; default: rc = OS_FAILED; } return rc; } OsStatus sipXmediaFactoryImpl::setVideoPreviewDisplay(void* pDisplay) { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::setVideoQuality(int quality) { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::setVideoParameters(int bitRate, int frameRate) { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getVideoQuality(int& quality) const { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getVideoBitRate(int& bitRate) const { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getVideoFrameRate(int& frameRate) const { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getCodecNameByType(SdpCodec::SdpCodecTypes type, UtlString& codecName) const { OsStatus rc = OS_FAILED; codecName = ""; switch (type) { case SdpCodec::SDP_CODEC_TONES: codecName = GIPS_CODEC_ID_TELEPHONE; break; case SdpCodec::SDP_CODEC_G729A: codecName = GIPS_CODEC_ID_G729; break; case SdpCodec::SDP_CODEC_GIPS_PCMA: codecName = GIPS_CODEC_ID_PCMA; break; case SdpCodec::SDP_CODEC_GIPS_PCMU: codecName = GIPS_CODEC_ID_PCMU; break; case SdpCodec::SDP_CODEC_GIPS_IPCMA: codecName = GIPS_CODEC_ID_EG711A; break; case SdpCodec::SDP_CODEC_GIPS_IPCMU: codecName = GIPS_CODEC_ID_EG711U; break; case SdpCodec::SDP_CODEC_GIPS_IPCMWB: codecName = GIPS_CODEC_ID_IPCMWB; break; case SdpCodec::SDP_CODEC_GIPS_ILBC: codecName = GIPS_CODEC_ID_ILBC; break; case SdpCodec::SDP_CODEC_GIPS_ISAC: codecName = GIPS_CODEC_ID_ISAC; break; default: OsSysLog::add(FAC_MP, PRI_WARNING, "sipXmediaFactoryImpl::getCodecNameByType unsupported type %d.", type); } if (codecName != "") { rc = OS_SUCCESS; } return rc; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <commit_msg>Fixed multiple declaration of local variable.<commit_after>// // // Copyright (C) 2005-2006 SIPez LLC. // Licensed to SIPfoundry under a Contributor Agreement. // // Copyright (C) 2004-2006 SIPfoundry Inc. // Licensed by SIPfoundry under the LGPL license. // // Copyright (C) 2004-2006 Pingtel Corp. // Licensed to SIPfoundry under a Contributor Agreement. // // $$ ////////////////////////////////////////////////////////////////////////////// // SYSTEM INCLUDES #include <stdlib.h> // APPLICATION INCLUDES #include "os/OsConfigDb.h" #include "include/sipXmediaFactoryImpl.h" #include "include/CpPhoneMediaInterface.h" #include "net/SdpCodec.h" #include "mp/MpMediaTask.h" #include "mp/MpMisc.h" #include "mp/MpCodec.h" #include "mp/MpCallFlowGraph.h" #include "mp/dmaTask.h" #include "net/SdpCodecFactory.h" #include "mi/CpMediaInterfaceFactoryFactory.h" #ifdef INCLUDE_RTCP /* [ */ #include "rtcp/RTCManager.h" #endif /* INCLUDE_RTCP ] */ // EXTERNAL FUNCTIONS // EXTERNAL VARIABLES // CONSTANTS // GLOBAL FUNCTION #define CONFIG_PHONESET_SEND_INBAND_DTMF "PHONESET_SEND_INBAND_DTMF" #define MAX_MANAGED_FLOW_GRAPHS 16 // STATIC VARIABLE INITIALIZATIONS int sipXmediaFactoryImpl::miInstanceCount=0; static CpMediaInterfaceFactory* spFactory = NULL; static int siInstanceCount=0; extern "C" CpMediaInterfaceFactory* sipXmediaFactoryFactory(OsConfigDb* pConfigDb) { // TODO: Add locking if (spFactory == NULL) { spFactory = new CpMediaInterfaceFactory(); spFactory->setFactoryImplementation(new sipXmediaFactoryImpl(pConfigDb)); } siInstanceCount++ ; // Assert some sane value assert(siInstanceCount < 11) ; return spFactory; } extern "C" void sipxDestroyMediaFactoryFactory() { // TODO: Add locking siInstanceCount-- ; assert(siInstanceCount >= 0) ; if (siInstanceCount == 0) { if (spFactory) { delete spFactory ; spFactory = NULL ; } } } /* //////////////////////////// PUBLIC //////////////////////////////////// */ /* ============================ CREATORS ================================== */ // Constructor sipXmediaFactoryImpl::sipXmediaFactoryImpl(OsConfigDb* pConfigDb) { int maxFlowGraph = -1 ; UtlString strInBandDTMF ; if (pConfigDb) { pConfigDb->get("PHONESET_MAX_ACTIVE_CALLS_ALLOWED", maxFlowGraph) ; pConfigDb->get(CONFIG_PHONESET_SEND_INBAND_DTMF, strInBandDTMF) ; strInBandDTMF.toUpper() ; OsSysLog::add(FAC_MP, PRI_DEBUG, "sipXmediaFactoryImpl::sipXmediaFactoryImpl maxFlowGraph = %d", maxFlowGraph); } // Max Flow graphs if (maxFlowGraph <=0 ) { maxFlowGraph = MAX_MANAGED_FLOW_GRAPHS; } if (miInstanceCount == 0) { mpStartUp(8000, 80, 16*maxFlowGraph, pConfigDb); } // Should we send inband DTMF by default? if (strInBandDTMF.compareTo("DISABLE") == 0) { MpCallFlowGraph::setInbandDTMF(false) ; } else { MpCallFlowGraph::setInbandDTMF(true) ; } // init the media processing task mpMediaTask = MpMediaTask::getMediaTask(maxFlowGraph); #ifdef INCLUDE_RTCP /* [ */ mpiRTCPControl = CRTCManager::getRTCPControl(); #endif /* INCLUDE_RTCP ] */ if (miInstanceCount == 0) { mpStartTasks(); } miGain = 7 ; ++miInstanceCount; } // Destructor sipXmediaFactoryImpl::~sipXmediaFactoryImpl() { // TODO: Shutdown --miInstanceCount; if (miInstanceCount == 0) { // Temporarily comment out this function because it causes the program hung. //mpStopTasks(); mpShutdown(); } } /* ============================ MANIPULATORS ============================== */ CpMediaInterface* sipXmediaFactoryImpl::createMediaInterface( const char* publicAddress, const char* localAddress, int numCodecs, SdpCodec* sdpCodecArray[], const char* locale, int expeditedIpTos, const char* szStunServer, int stunOptions, int iStunKeepAliveSecs ) { return new CpPhoneMediaInterface(this, publicAddress, localAddress, numCodecs, sdpCodecArray, locale, expeditedIpTos, szStunServer, iStunKeepAliveSecs) ; } OsStatus sipXmediaFactoryImpl::setSpeakerVolume(int iVolume) { OsStatus rc = OS_SUCCESS ; MpCodec_setVolume(iVolume) ; return rc ; } OsStatus sipXmediaFactoryImpl::setSpeakerDevice(const UtlString& device) { OsStatus rc = OS_SUCCESS ; DmaTask::setCallDevice(device.data()) ; return rc ; } OsStatus sipXmediaFactoryImpl::setMicrophoneGain(int iGain) { OsStatus rc ; miGain = iGain ; rc = MpCodec_setGain(miGain) ; return rc ; } OsStatus sipXmediaFactoryImpl::setMicrophoneDevice(const UtlString& device) { OsStatus rc = OS_SUCCESS ; DmaTask::setInputDevice(device.data()) ; return rc ; } OsStatus sipXmediaFactoryImpl::muteMicrophone(UtlBoolean bMute) { if (bMute) { MpCodec_setGain(0) ; } else { MpCodec_setGain(miGain) ; } return OS_SUCCESS ; } OsStatus sipXmediaFactoryImpl::enableAudioAEC(UtlBoolean bEnable) { return OS_SUCCESS; } OsStatus sipXmediaFactoryImpl::enableOutOfBandDTMF(UtlBoolean bEnable) { return OS_SUCCESS; } OsStatus sipXmediaFactoryImpl::buildCodecFactory(SdpCodecFactory *pFactory, const UtlString& sPreferences, const UtlString& sVideoPreferences, int* iRejected) { OsStatus rc = OS_FAILED; int numCodecs = 0; UtlString codecName; UtlString codecList; *iRejected = 0; #ifdef HAVE_GIPS /* [ */ numCodecs = 6; SdpCodec::SdpCodecTypes codecs[6]; codecs[0] = SdpCodec::SDP_CODEC_GIPS_PCMU; codecs[1] = SdpCodec::SDP_CODEC_GIPS_PCMA; codecs[2] = SdpCodec::SDP_CODEC_GIPS_IPCMU; codecs[3] = SdpCodec::SDP_CODEC_GIPS_IPCMA; codecs[4] = SdpCodec::SDP_CODEC_GIPS_IPCMWB; codecs[5] = SdpCodec::SDP_CODEC_TONES; #else /* HAVE_GIPS ] [ */ numCodecs = 3; SdpCodec::SdpCodecTypes codecs[3]; codecs[0] = SdpCodec::SDP_CODEC_GIPS_PCMU; codecs[1] = SdpCodec::SDP_CODEC_GIPS_PCMA; codecs[2] = SdpCodec::SDP_CODEC_TONES; #endif /* HAVE_GIPS ] */ if (pFactory) { pFactory->clearCodecs(); // add preferred codecs first if (sPreferences.length() > 0) { UtlString references = sPreferences; *iRejected = pFactory->buildSdpCodecFactory(references); OsSysLog::add(FAC_MP, PRI_DEBUG, "sipXmediaFactoryImpl::buildCodecFactory: sReferences = %s with NumReject %d", references.data(), *iRejected); // Now pick preferences out of all available codecs SdpCodec** codecsArray = NULL; pFactory->getCodecs(numCodecs, codecsArray); UtlString preferences; int i; for (i = 0; i < numCodecs; i++) { if (getCodecNameByType(codecsArray[i]->getCodecType(), codecName) == OS_SUCCESS) { preferences = preferences + " " + codecName; } } pFactory->clearCodecs(); *iRejected = pFactory->buildSdpCodecFactory(preferences); OsSysLog::add(FAC_MP, PRI_DEBUG, "sipXmediaFactoryImpl::buildCodecFactory: supported codecs = %s with NumReject %d", preferences.data(), *iRejected); // Free up the codecs and the array for (i = 0; i < numCodecs; i++) { delete codecsArray[i]; codecsArray[i] = NULL; } delete[] codecsArray; codecsArray = NULL; rc = OS_SUCCESS; } else { // Build up the supported codecs *iRejected = pFactory->buildSdpCodecFactory(numCodecs, codecs); rc = OS_SUCCESS; } } return rc; } OsStatus sipXmediaFactoryImpl::updateVideoPreviewWindow(void* displayContext) { return OS_NOT_SUPPORTED ; } /* ============================ ACCESSORS ================================= */ OsStatus sipXmediaFactoryImpl::getSpeakerVolume(int& iVolume) const { OsStatus rc = OS_SUCCESS ; iVolume = MpCodec_getVolume() ; return rc ; } OsStatus sipXmediaFactoryImpl::getSpeakerDevice(UtlString& device) const { OsStatus rc = OS_SUCCESS ; device = DmaTask::getCallDevice() ; return rc ; } OsStatus sipXmediaFactoryImpl::getMicrophoneGain(int& iGain) const { OsStatus rc = OS_SUCCESS ; iGain = MpCodec_getGain() ; return rc ; } OsStatus sipXmediaFactoryImpl::getMicrophoneDevice(UtlString& device) const { OsStatus rc = OS_SUCCESS ; device = DmaTask::getMicDevice() ; return rc ; } OsStatus sipXmediaFactoryImpl::isAudioAECEnabled(UtlBoolean& bEnabled) const { bEnabled = false; return OS_SUCCESS; } OsStatus sipXmediaFactoryImpl::isOutOfBandDTMFEnabled(UtlBoolean& bEnabled) const { bEnabled = false; return OS_SUCCESS; } OsStatus sipXmediaFactoryImpl::getNumOfCodecs(int& iCodecs) const { iCodecs = 3; return OS_SUCCESS; } OsStatus sipXmediaFactoryImpl::getCodec(int iCodec, UtlString& codec, int &bandWidth) const { OsStatus rc = OS_SUCCESS; switch (iCodec) { #ifdef HAVE_GIPS /* [ */ case 0: codec = (const char*) SdpCodec::SDP_CODEC_GIPS_PCMU; break; case 1: codec = (const char*) SdpCodec::SDP_CODEC_GIPS_PCMA; break; #else /* HAVE_GIPS ] [ */ case 0: codec = (const char*) SdpCodec::SDP_CODEC_GIPS_PCMU; break; case 1: codec = (const char*) SdpCodec::SDP_CODEC_GIPS_PCMA; break; #endif /* HAVE_GIPS ] */ case 2: codec = (const char*) SdpCodec::SDP_CODEC_TONES; break; default: rc = OS_FAILED; } return rc; } OsStatus sipXmediaFactoryImpl::setVideoPreviewDisplay(void* pDisplay) { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::setVideoQuality(int quality) { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::setVideoParameters(int bitRate, int frameRate) { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getVideoQuality(int& quality) const { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getVideoBitRate(int& bitRate) const { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getVideoFrameRate(int& frameRate) const { return OS_NOT_YET_IMPLEMENTED; } OsStatus sipXmediaFactoryImpl::getCodecNameByType(SdpCodec::SdpCodecTypes type, UtlString& codecName) const { OsStatus rc = OS_FAILED; codecName = ""; switch (type) { case SdpCodec::SDP_CODEC_TONES: codecName = GIPS_CODEC_ID_TELEPHONE; break; case SdpCodec::SDP_CODEC_G729A: codecName = GIPS_CODEC_ID_G729; break; case SdpCodec::SDP_CODEC_GIPS_PCMA: codecName = GIPS_CODEC_ID_PCMA; break; case SdpCodec::SDP_CODEC_GIPS_PCMU: codecName = GIPS_CODEC_ID_PCMU; break; case SdpCodec::SDP_CODEC_GIPS_IPCMA: codecName = GIPS_CODEC_ID_EG711A; break; case SdpCodec::SDP_CODEC_GIPS_IPCMU: codecName = GIPS_CODEC_ID_EG711U; break; case SdpCodec::SDP_CODEC_GIPS_IPCMWB: codecName = GIPS_CODEC_ID_IPCMWB; break; case SdpCodec::SDP_CODEC_GIPS_ILBC: codecName = GIPS_CODEC_ID_ILBC; break; case SdpCodec::SDP_CODEC_GIPS_ISAC: codecName = GIPS_CODEC_ID_ISAC; break; default: OsSysLog::add(FAC_MP, PRI_WARNING, "sipXmediaFactoryImpl::getCodecNameByType unsupported type %d.", type); } if (codecName != "") { rc = OS_SUCCESS; } return rc; } /* ============================ INQUIRY =================================== */ /* //////////////////////////// PROTECTED ///////////////////////////////// */ /* //////////////////////////// PRIVATE /////////////////////////////////// */ /* ============================ FUNCTIONS ================================= */ <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ /// deplate.cc /// /// Converts a plate file to GeoTIFF tiles on disk. #include <vw/Image.h> #include <vw/FileIO.h> #include <vw/Plate/PlateView.h> #include <vw/Plate/PlateCarreePlateManager.h> using namespace vw; using namespace vw::platefile; #include <boost/filesystem/path.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; namespace fs = boost::filesystem; struct Options { Options() : west(0), east(0), north(0), south(0), tile_size(0), tile_size_deg(0), pds_dem_mode(false), pds_imagery_mode(false) {} // Input for project file std::string plate_file_name; // Settings int west, east, north, south, tile_size, tile_size_deg; double tile_ppd; bool pds_dem_mode, pds_imagery_mode; int level; // Output std::string output_datum, output_prefix; }; // ConvertToPDSImagery // .. coverts an image into the range of 1-254 where 0 is invalid and 255 is reserved. template <class PixelT> class ConvertToPDSImagery : public ReturnFixedType<typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type,uint8>::type> { typedef typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type,uint8>::type return_type; typedef typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type,double>::type return_double_type; typedef typename CompoundChannelType<PixelT>::type input_channel_type; public: return_type operator()( PixelT value ) const { if ( is_transparent(value) ) { return return_type(); } else { return_double_type result = channel_cast<double>(non_alpha_channels(value))*253.0/ChannelRange<input_channel_type>::max(); for ( uint8 i = 0; i < CompoundNumChannels<return_double_type>::value; i++ ) { if (result[i] < 0) result[i] = 0; if (result[i] > 253) result[i] = 253; } return channel_cast<uint8>(result)+1; } } }; template <class ImageT> UnaryPerPixelView<ImageT, ConvertToPDSImagery<typename ImageT::pixel_type> > inline convert_to_pds_imagery( ImageViewBase<ImageT> const& image ) { typedef ConvertToPDSImagery<typename ImageT::pixel_type> func_type; return UnaryPerPixelView<ImageT, func_type>( image.impl(), func_type() ); } template <class PixelT> void do_tiles(boost::shared_ptr<PlateFile> platefile, Options& opt) { PlateCarreePlateManager<PixelT> pm(platefile); cartography::GeoReference output_georef; output_georef = pm.georeference(platefile->num_levels()-1); cartography::Datum datum; datum.set_well_known_datum( opt.output_datum ); output_georef.set_datum( datum ); PlateView<PixelT> plate_view(opt.plate_file_name); if ( opt.level != -1 ) plate_view.set_level( opt.level ); ImageViewRef<PixelT> plate_view_ref = plate_view; double scale_change = 1; if ( opt.tile_ppd > 0 ) { // Finding out our current PPD and attempting to match double curr_ppd = norm_2(output_georef.lonlat_to_pixel(Vector2(0,0))- output_georef.lonlat_to_pixel(Vector2(1,0))); scale_change = opt.tile_ppd / curr_ppd; plate_view_ref = resample( plate_view, scale_change, scale_change, ZeroEdgeExtension()); Matrix3x3 scale; scale.set_identity(); scale(0,0) /= scale_change; scale(1,1) /= scale_change; output_georef.set_transform( output_georef.transform()*scale ); // Double check curr_ppd = norm_2(output_georef.lonlat_to_pixel(Vector2(0,0))- output_georef.lonlat_to_pixel(Vector2(1,0))); } std::cout << "Converting " << opt.plate_file_name << " to " << opt.output_prefix << "\n"; std::cout << output_georef << "\n"; // Get the output georeference. vw::BBox2i output_bbox; output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.west, opt.north))); output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.east, opt.north))); output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.west, opt.south))); output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.east, opt.south))); std::cout << "\t--> Output bbox: " << output_bbox << "\n"; if ( opt.tile_size_deg > 0 ) { if ( opt.tile_ppd > 0 ) { opt.tile_size = opt.tile_size_deg * opt.tile_ppd; } else { // User must have specified out to be sized in degrees opt.tile_size = norm_2(output_georef.lonlat_to_pixel(Vector2(0,0)) - output_georef.lonlat_to_pixel(Vector2(opt.tile_size_deg,0))); } } // Compute the bounding box for each tile. std::vector<BBox2i> crop_bboxes = image_blocks(crop(plate_view_ref, output_bbox), opt.tile_size, opt.tile_size); for (unsigned i = 0; i < crop_bboxes.size(); ++i) { // The crop bboxes start at (0,0), and we want them to start at // the upper left corner of the output_bbox. crop_bboxes[i].min() += output_bbox.min(); crop_bboxes[i].max() += output_bbox.min(); { // Checking to see if this section is transparent std::list<TileHeader> theaders = plate_view.search_for_tiles( crop_bboxes[i] / scale_change ); if (theaders.empty()) continue; } cartography::GeoReference tile_georef = output_georef; Vector2 top_left_ll = output_georef.pixel_to_lonlat(crop_bboxes[i].min()); Matrix3x3 T = tile_georef.transform(); T(0,2) = top_left_ll(0); T(1,2) = top_left_ll(1); tile_georef.set_transform(T); std::cout << "\t--> Generating tile " << (i+1) << " / " << crop_bboxes.size() << " : " << crop_bboxes[i] << "\n" << "\t with transform " << tile_georef.transform() << "\n"; std::ostringstream output_filename; output_filename << opt.output_prefix << "_" << abs(round(top_left_ll[0])); if ( top_left_ll[0] < 0 ) output_filename << "W_"; else output_filename << "E_"; output_filename << abs(round(top_left_ll[1])); if ( top_left_ll[1] >= 0 ) output_filename << "N.tif"; else output_filename << "S.tif"; ImageView<PixelT> cropped_view = crop(plate_view_ref, crop_bboxes[i]); DiskImageResourceGDAL::Options gdal_options; gdal_options["COMPRESS"] = "LZW"; if ( opt.pds_dem_mode ) { ImageViewRef<typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type ,int16>::type > dem_image = apply_mask(alpha_to_mask(channel_cast<int16>(cropped_view)),-32767); DiskImageResourceGDAL rsrc(output_filename.str(), dem_image.format(), Vector2i(256,256), gdal_options); write_georeference(rsrc, tile_georef); write_image(rsrc, dem_image, TerminalProgressCallback( "plate.tools", "\t Writing: ")); } else if ( opt.pds_imagery_mode ) { ImageViewRef<typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type ,uint8>::type > dem_image = convert_to_pds_imagery( cropped_view ); DiskImageResourceGDAL rsrc(output_filename.str(), dem_image.format(), Vector2i(256,256), gdal_options); write_georeference(rsrc, tile_georef); write_image(rsrc, dem_image, TerminalProgressCallback( "plate.tools", "\t Writing: ")); } else { DiskImageResourceGDAL rsrc(output_filename.str(), cropped_view.format(), Vector2i(256,256), gdal_options); write_georeference(rsrc, tile_georef); write_image(rsrc, cropped_view, TerminalProgressCallback( "plate.tools", "\t Writing: ")); } } } void handle_arguments( int argc, char *argv[], Options& opt ) { po::options_description general_options("Chops platefile into georeferenced squares.\n\nGeneral Options"); general_options.add_options() ("output-prefix,o", po::value(&opt.output_prefix), "Specify the base output directory") ("level,l", po::value(&opt.level)->default_value(-1), "Level inside the plate in which to process. -1 will error out at show the number of levels available.") ("west,w", po::value(&opt.west)->default_value(-180), "Specify west edge of the region to extract (deg).") ("east,e", po::value(&opt.east)->default_value(180), "Specify east edge of the region to extract (deg).") ("north,n", po::value(&opt.north)->default_value(90), "Specify north edge of the region to extract (deg).") ("south,s", po::value(&opt.south)->default_value(-90), "Specify south edge of the region to extract (deg).") ("tile-size-px,t", po::value(&opt.tile_size)->default_value(4096), "Specify the size of each output dem in pixels.") ("tile-size-deg,d", po::value(&opt.tile_size_deg), "Specify the size of each output dem in degrees.") ("tile-px-per-degree,p", po::value(&opt.tile_ppd), "Specify the output tiles' pixel per degrees.") ("output-datum", po::value(&opt.output_datum)->default_value("WGS84"), "Specify the output datum to use, [WGS84, WGS72, D_MOON, D_MARS]") ("export-pds-dem", "Export using int16 channel value with a -32767 nodata value") ("export-pds-imagery", "Export using uint8 channel value with a 0 nodata value") ("help", "Display this help message"); po::options_description positional(""); positional.add_options() ("plate-file", po::value(&opt.plate_file_name)); po::positional_options_description positional_desc; positional_desc.add("plate-file", 1); po::options_description all_options; all_options.add(general_options).add(positional); po::variables_map vm; try { po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm ); po::notify( vm ); } catch (po::error &e) { vw_throw( ArgumentErr() << "Error parsing input:\n\t" << e.what() << general_options ); } std::ostringstream usage; usage << "Usage: " << argv[0] << " <platefile-url> <optional project settings> \n"; if ( vm.count("help") ) vw_throw( ArgumentErr() << usage.str() << general_options ); if ( opt.plate_file_name.empty() ) vw_throw( ArgumentErr() << "Missing input platefile!\n" << usage.str() << general_options ); opt.pds_dem_mode = vm.count("export-pds-dem"); opt.pds_imagery_mode = vm.count("export-pds-imagery"); if( opt.output_prefix == "" ) { opt.output_prefix = fs::path(opt.plate_file_name).stem(); int indx = opt.output_prefix.rfind("/"); if ( indx > 0 ) opt.output_prefix = opt.output_prefix.substr(indx+1); } } int main( int argc, char *argv[] ) { Options opt; try { handle_arguments( argc, argv, opt ); boost::shared_ptr<PlateFile> platefile(new PlateFile(opt.plate_file_name)); std::cout << "Opened " << opt.plate_file_name << ". Depth: " << platefile->num_levels() << " levels.\n"; PixelFormatEnum pixel_format = platefile->pixel_format(); ChannelTypeEnum channel_type = platefile->channel_type(); switch(pixel_format) { case VW_PIXEL_GRAYA: switch(channel_type) { case VW_CHANNEL_UINT8: do_tiles<PixelGrayA<uint8> >(platefile, opt); break; case VW_CHANNEL_INT16: do_tiles<PixelGrayA<int16> >(platefile, opt); break; case VW_CHANNEL_FLOAT32: do_tiles<PixelGrayA<float32> >(platefile, opt); break; default: vw_throw(ArgumentErr() << "Platefile contains a channel type not supported by image2plate.\n"); } break; case VW_PIXEL_RGB: case VW_PIXEL_RGBA: default: switch(channel_type) { case VW_CHANNEL_UINT8: do_tiles<PixelRGBA<uint8> >(platefile, opt); break; default: vw_throw(ArgumentErr() << "Platefile contains a channel type not supported by image2plate.\n"); } break; } } catch ( const ArgumentErr& e ) { vw_out() << e.what() << std::endl; return 1; } catch ( const Exception& e ) { std::cerr << "VW Error: " << e.what() << std::endl; return 1; } catch ( const std::bad_alloc& e ) { std::cerr << "Error: Ran out of Memory!" << std::endl; return 1; } catch ( const std::exception& e ) { std::cerr << "Error: " << e.what() << std::endl; return 1; } } <commit_msg>Have plate2dem record it's nodata value in file<commit_after>// __BEGIN_LICENSE__ // Copyright (C) 2006-2010 United States Government as represented by // the Administrator of the National Aeronautics and Space Administration. // All Rights Reserved. // __END_LICENSE__ /// deplate.cc /// /// Converts a plate file to GeoTIFF tiles on disk. #include <vw/Image.h> #include <vw/FileIO.h> #include <vw/Plate/PlateView.h> #include <vw/Plate/PlateCarreePlateManager.h> using namespace vw; using namespace vw::platefile; #include <boost/filesystem/path.hpp> #include <boost/program_options.hpp> namespace po = boost::program_options; namespace fs = boost::filesystem; struct Options { Options() : west(0), east(0), north(0), south(0), tile_size(0), tile_size_deg(0), pds_dem_mode(false), pds_imagery_mode(false) {} // Input for project file std::string plate_file_name; // Settings int west, east, north, south, tile_size, tile_size_deg; double tile_ppd; bool pds_dem_mode, pds_imagery_mode; int level; // Output std::string output_datum, output_prefix; }; // ConvertToPDSImagery // .. coverts an image into the range of 1-254 where 0 is invalid and 255 is reserved. template <class PixelT> class ConvertToPDSImagery : public ReturnFixedType<typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type,uint8>::type> { typedef typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type,uint8>::type return_type; typedef typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type,double>::type return_double_type; typedef typename CompoundChannelType<PixelT>::type input_channel_type; public: return_type operator()( PixelT value ) const { if ( is_transparent(value) ) { return return_type(); } else { return_double_type result = channel_cast<double>(non_alpha_channels(value))*253.0/ChannelRange<input_channel_type>::max(); for ( uint8 i = 0; i < CompoundNumChannels<return_double_type>::value; i++ ) { if (result[i] < 0) result[i] = 0; if (result[i] > 253) result[i] = 253; } return channel_cast<uint8>(result)+1; } } }; template <class ImageT> UnaryPerPixelView<ImageT, ConvertToPDSImagery<typename ImageT::pixel_type> > inline convert_to_pds_imagery( ImageViewBase<ImageT> const& image ) { typedef ConvertToPDSImagery<typename ImageT::pixel_type> func_type; return UnaryPerPixelView<ImageT, func_type>( image.impl(), func_type() ); } template <class PixelT> void do_tiles(boost::shared_ptr<PlateFile> platefile, Options& opt) { PlateCarreePlateManager<PixelT> pm(platefile); cartography::GeoReference output_georef; output_georef = pm.georeference(platefile->num_levels()-1); cartography::Datum datum; datum.set_well_known_datum( opt.output_datum ); output_georef.set_datum( datum ); PlateView<PixelT> plate_view(opt.plate_file_name); if ( opt.level != -1 ) plate_view.set_level( opt.level ); ImageViewRef<PixelT> plate_view_ref = plate_view; double scale_change = 1; if ( opt.tile_ppd > 0 ) { // Finding out our current PPD and attempting to match double curr_ppd = norm_2(output_georef.lonlat_to_pixel(Vector2(0,0))- output_georef.lonlat_to_pixel(Vector2(1,0))); scale_change = opt.tile_ppd / curr_ppd; plate_view_ref = resample( plate_view, scale_change, scale_change, ZeroEdgeExtension()); Matrix3x3 scale; scale.set_identity(); scale(0,0) /= scale_change; scale(1,1) /= scale_change; output_georef.set_transform( output_georef.transform()*scale ); // Double check curr_ppd = norm_2(output_georef.lonlat_to_pixel(Vector2(0,0))- output_georef.lonlat_to_pixel(Vector2(1,0))); } std::cout << "Converting " << opt.plate_file_name << " to " << opt.output_prefix << "\n"; std::cout << output_georef << "\n"; // Get the output georeference. vw::BBox2i output_bbox; output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.west, opt.north))); output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.east, opt.north))); output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.west, opt.south))); output_bbox.grow(output_georef.lonlat_to_pixel(Vector2(opt.east, opt.south))); std::cout << "\t--> Output bbox: " << output_bbox << "\n"; if ( opt.tile_size_deg > 0 ) { if ( opt.tile_ppd > 0 ) { opt.tile_size = opt.tile_size_deg * opt.tile_ppd; } else { // User must have specified out to be sized in degrees opt.tile_size = norm_2(output_georef.lonlat_to_pixel(Vector2(0,0)) - output_georef.lonlat_to_pixel(Vector2(opt.tile_size_deg,0))); } } // Compute the bounding box for each tile. std::vector<BBox2i> crop_bboxes = image_blocks(crop(plate_view_ref, output_bbox), opt.tile_size, opt.tile_size); for (unsigned i = 0; i < crop_bboxes.size(); ++i) { // The crop bboxes start at (0,0), and we want them to start at // the upper left corner of the output_bbox. crop_bboxes[i].min() += output_bbox.min(); crop_bboxes[i].max() += output_bbox.min(); { // Checking to see if this section is transparent std::list<TileHeader> theaders = plate_view.search_for_tiles( crop_bboxes[i] / scale_change ); if (theaders.empty()) continue; } cartography::GeoReference tile_georef = output_georef; Vector2 top_left_ll = output_georef.pixel_to_lonlat(crop_bboxes[i].min()); Matrix3x3 T = tile_georef.transform(); T(0,2) = top_left_ll(0); T(1,2) = top_left_ll(1); tile_georef.set_transform(T); std::cout << "\t--> Generating tile " << (i+1) << " / " << crop_bboxes.size() << " : " << crop_bboxes[i] << "\n" << "\t with transform " << tile_georef.transform() << "\n"; std::ostringstream output_filename; output_filename << opt.output_prefix << "_" << abs(round(top_left_ll[0])); if ( top_left_ll[0] < 0 ) output_filename << "W_"; else output_filename << "E_"; output_filename << abs(round(top_left_ll[1])); if ( top_left_ll[1] >= 0 ) output_filename << "N.tif"; else output_filename << "S.tif"; ImageView<PixelT> cropped_view = crop(plate_view_ref, crop_bboxes[i]); DiskImageResourceGDAL::Options gdal_options; gdal_options["COMPRESS"] = "LZW"; if ( opt.pds_dem_mode ) { ImageViewRef<typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type ,int16>::type > dem_image = apply_mask(alpha_to_mask(channel_cast<int16>(cropped_view)),-32767); DiskImageResourceGDAL rsrc(output_filename.str(), dem_image.format(), Vector2i(256,256), gdal_options); rsrc.set_nodata_value( -32767 ); write_georeference(rsrc, tile_georef); write_image(rsrc, dem_image, TerminalProgressCallback( "plate.tools", "\t Writing: ")); } else if ( opt.pds_imagery_mode ) { ImageViewRef<typename CompoundChannelCast<typename PixelWithoutAlpha<PixelT>::type ,uint8>::type > dem_image = convert_to_pds_imagery( cropped_view ); DiskImageResourceGDAL rsrc(output_filename.str(), dem_image.format(), Vector2i(256,256), gdal_options); rsrc.set_nodata_value( 0 ); write_georeference(rsrc, tile_georef); write_image(rsrc, dem_image, TerminalProgressCallback( "plate.tools", "\t Writing: ")); } else { DiskImageResourceGDAL rsrc(output_filename.str(), cropped_view.format(), Vector2i(256,256), gdal_options); write_georeference(rsrc, tile_georef); write_image(rsrc, cropped_view, TerminalProgressCallback( "plate.tools", "\t Writing: ")); } } } void handle_arguments( int argc, char *argv[], Options& opt ) { po::options_description general_options("Chops platefile into georeferenced squares.\n\nGeneral Options"); general_options.add_options() ("output-prefix,o", po::value(&opt.output_prefix), "Specify the base output directory") ("level,l", po::value(&opt.level)->default_value(-1), "Level inside the plate in which to process. -1 will error out at show the number of levels available.") ("west,w", po::value(&opt.west)->default_value(-180), "Specify west edge of the region to extract (deg).") ("east,e", po::value(&opt.east)->default_value(180), "Specify east edge of the region to extract (deg).") ("north,n", po::value(&opt.north)->default_value(90), "Specify north edge of the region to extract (deg).") ("south,s", po::value(&opt.south)->default_value(-90), "Specify south edge of the region to extract (deg).") ("tile-size-px,t", po::value(&opt.tile_size)->default_value(4096), "Specify the size of each output dem in pixels.") ("tile-size-deg,d", po::value(&opt.tile_size_deg), "Specify the size of each output dem in degrees.") ("tile-px-per-degree,p", po::value(&opt.tile_ppd), "Specify the output tiles' pixel per degrees.") ("output-datum", po::value(&opt.output_datum)->default_value("WGS84"), "Specify the output datum to use, [WGS84, WGS72, D_MOON, D_MARS]") ("export-pds-dem", "Export using int16 channel value with a -32767 nodata value") ("export-pds-imagery", "Export using uint8 channel value with a 0 nodata value") ("help", "Display this help message"); po::options_description positional(""); positional.add_options() ("plate-file", po::value(&opt.plate_file_name)); po::positional_options_description positional_desc; positional_desc.add("plate-file", 1); po::options_description all_options; all_options.add(general_options).add(positional); po::variables_map vm; try { po::store( po::command_line_parser( argc, argv ).options(all_options).positional(positional_desc).run(), vm ); po::notify( vm ); } catch (po::error &e) { vw_throw( ArgumentErr() << "Error parsing input:\n\t" << e.what() << general_options ); } std::ostringstream usage; usage << "Usage: " << argv[0] << " <platefile-url> <optional project settings> \n"; if ( vm.count("help") ) vw_throw( ArgumentErr() << usage.str() << general_options ); if ( opt.plate_file_name.empty() ) vw_throw( ArgumentErr() << "Missing input platefile!\n" << usage.str() << general_options ); opt.pds_dem_mode = vm.count("export-pds-dem"); opt.pds_imagery_mode = vm.count("export-pds-imagery"); if( opt.output_prefix == "" ) { opt.output_prefix = fs::path(opt.plate_file_name).stem(); int indx = opt.output_prefix.rfind("/"); if ( indx > 0 ) opt.output_prefix = opt.output_prefix.substr(indx+1); } } int main( int argc, char *argv[] ) { Options opt; try { handle_arguments( argc, argv, opt ); boost::shared_ptr<PlateFile> platefile(new PlateFile(opt.plate_file_name)); std::cout << "Opened " << opt.plate_file_name << ". Depth: " << platefile->num_levels() << " levels.\n"; PixelFormatEnum pixel_format = platefile->pixel_format(); ChannelTypeEnum channel_type = platefile->channel_type(); switch(pixel_format) { case VW_PIXEL_GRAYA: switch(channel_type) { case VW_CHANNEL_UINT8: do_tiles<PixelGrayA<uint8> >(platefile, opt); break; case VW_CHANNEL_INT16: do_tiles<PixelGrayA<int16> >(platefile, opt); break; case VW_CHANNEL_FLOAT32: do_tiles<PixelGrayA<float32> >(platefile, opt); break; default: vw_throw(ArgumentErr() << "Platefile contains a channel type not supported by image2plate.\n"); } break; case VW_PIXEL_RGB: case VW_PIXEL_RGBA: default: switch(channel_type) { case VW_CHANNEL_UINT8: do_tiles<PixelRGBA<uint8> >(platefile, opt); break; default: vw_throw(ArgumentErr() << "Platefile contains a channel type not supported by image2plate.\n"); } break; } } catch ( const ArgumentErr& e ) { vw_out() << e.what() << std::endl; return 1; } catch ( const Exception& e ) { std::cerr << "VW Error: " << e.what() << std::endl; return 1; } catch ( const std::bad_alloc& e ) { std::cerr << "Error: Ran out of Memory!" << std::endl; return 1; } catch ( const std::exception& e ) { std::cerr << "Error: " << e.what() << std::endl; return 1; } } <|endoftext|>
<commit_before>// __BEGIN_LICENSE__ // // Copyright (C) 2006 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration // (NASA). All Rights Reserved. // // Copyright 2006 Carnegie Mellon University. All rights reserved. // // This software is distributed under the NASA Open Source Agreement // (NOSA), version 1.3. The NOSA has been approved by the Open Source // Initiative. See the file COPYING at the top of the distribution // directory tree for the complete NOSA document. // // THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY // KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT // LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO // SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR // A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT // THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT // DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. // // __END_LICENSE__ #ifdef _MSC_VER #pragma warning(disable:4244) #pragma warning(disable:4267) #pragma warning(disable:4996) #endif #include <stdlib.h> #include <iostream> #include <fstream> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <vw/Core/Cache.h> #include <vw/Math/Matrix.h> #include <vw/Image/Transform.h> #include <vw/FileIO/DiskImageResource.h> #include <vw/FileIO/DiskImageResourceJPEG.h> #include <vw/FileIO/DiskImageView.h> #include <vw/Cartography/GeoReference.h> #include <vw/Cartography/GeoTransform.h> #include <vw/Cartography/FileIO.h> #include <vw/Mosaic/ImageComposite.h> #include <vw/Mosaic/KMLQuadTreeGenerator.h> using namespace vw; using namespace vw::math; using namespace vw::cartography; using namespace vw::mosaic; int main( int argc, char *argv[] ) { std::vector<std::string> image_files; std::string output_file_name; std::string output_file_type; float north_lat, south_lat; float east_lon, west_lon; unsigned utm_zone; int patch_size, patch_overlap; float jpeg_quality; unsigned cache_size; po::options_description desc("Options"); desc.add_options() ("help", "Display this help message") ("input-file", po::value<std::vector<std::string> >(&image_files), "Explicitly specify the input file") ("output-name,o", po::value<std::string>(&output_file_name)->default_value("output"), "Specify the base output filename") ("file-type", po::value<std::string>(&output_file_type)->default_value("jpg"), "Output file type") ("north", po::value<float>(&north_lat)->default_value(90.0), "The northernmost latitude in degrees") ("south", po::value<float>(&south_lat)->default_value(-90.0), "The southernmost latitude in degrees") ("east", po::value<float>(&east_lon)->default_value(180.0), "The easternmost latitude in degrees") ("west", po::value<float>(&west_lon)->default_value(-180.0), "The westernmost latitude in degrees") ("utm", po::value<unsigned>(&utm_zone), "Specify a UTM zone") ("size", po::value<int>(&patch_size)->default_value(256), "Patch size, in pixels") ("overlap", po::value<int>(&patch_overlap)->default_value(0), "Patch overlap, in pixels (must be even)") ("jpeg-quality", po::value<float>(&jpeg_quality)->default_value(0.75), "JPEG quality factor (0.0 to 1.0)") ("cache", po::value<unsigned>(&cache_size)->default_value(1024), "Cache size, in megabytes") ("verbose", "Verbose output"); po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm ); po::notify( vm ); if( vm.count("help") ) { std::cout << desc << std::endl; return 1; } if( vm.count("input-file") < 1 ) { std::cout << "Error: Must specify exactly one input file!" << std::endl; std::cout << desc << std::endl; return 1; } if( patch_size <= 0 ) { std::cerr << "Error: The patch size must be a positive number! (You specified " << patch_size << ".)" << std::endl; std::cout << desc << std::endl; return 1; } if( patch_overlap<0 || patch_overlap>=patch_size || patch_overlap%2==1 ) { std::cerr << "Error: The patch overlap must be an even number nonnegative number" << std::endl; std::cerr << "smaller than the patch size! (You specified " << patch_overlap << ".)" << std::endl; std::cout << desc << std::endl; return 1; } if( vm.count("verbose") ) { set_debug_level(VerboseDebugMessage); } DiskImageResourceJPEG::set_default_quality( jpeg_quality ); Cache::system_cache().resize( cache_size*1024*1024 ); GeoReference output_georef; output_georef.set_well_known_geogcs("WGS84"); int total_resolution = 1024; // Read in georeference info and compute total resolution bool manual = false; std::vector<GeoReference> georeferences; for( unsigned i=0; i<image_files.size(); ++i ) { DiskImageResourceGDAL file_resource( image_files[i] ); GeoReference input_georef; file_resource.read_georeference( input_georef ); // This is sort of a klugey way to check for a georef if( input_georef.proj4_str() == "" && input_georef.transform() == identity_matrix<3>() ) { if( image_files.size() == 1 ) { vw_out(InfoMessage) << "No georeferencing info found. Assuming Plate Carree WGS84: " << east_lon << " to " << west_lon << " E, " << south_lat << " to " << north_lat << " N." << std::endl; input_georef.set_well_known_geogcs("WGS84"); Matrix3x3 m; m(0,0) = (east_lon - west_lon) / file_resource.cols(); m(0,2) = west_lon + 0.5*m(0,0); m(1,1) = (south_lat - north_lat) / file_resource.rows(); m(1,2) = north_lat + 0.5*m(1,1); m(2,2) = 1; input_georef.set_transform( m ); manual = true; } else { vw_out(ErrorMessage) << "Error: No georeferencing info found for input file \"" << image_files[i] << "\"!" << std::endl; vw_out(ErrorMessage) << "(Manually-specified bounds are only allowed for single image files.)" << std::endl; exit(1); } } else if( vm.count("utm") ) input_georef.set_UTM( utm_zone ); georeferences.push_back( input_georef ); GeoTransform geotx( input_georef, output_georef ); Vector2 center_pixel( file_resource.cols()/2, file_resource.rows()/2 ); int resolution = GlobalKMLTransform::compute_resolution( geotx, center_pixel ); if( resolution > total_resolution ) total_resolution = resolution; } // Configure the composite ImageComposite<PixelRGBA<uint8> > composite; composite.set_draft_mode( true ); GlobalKMLTransform kmltx( total_resolution ); // Add the transformed input files to the composite for( unsigned i=0; i<image_files.size(); ++i ) { std::cout << "Adding file " << image_files[i] << std::endl; GeoTransform geotx( georeferences[i], output_georef ); DiskImageView<PixelRGBA<uint8> > source( image_files[i] ); BBox2i bbox = compute_transformed_bbox_fast_int( source, compose(kmltx,geotx) ); // Constant edge extension is better for transformations that // preserve the rectangularity of the image. At the moment we // only do this for manual transforms, alas. if( manual ) { // If the image is being super-sampled the computed bounding // box may be missing a pixel at the edges relative to what // you might expect, which can create visible artifacts if // it happens at the boundaries of the coordinate system. if( west_lon == -180 ) bbox.min().x() = 0; if( east_lon == 180 ) bbox.max().x() = total_resolution; if( north_lat == 90 ) bbox.min().y() = total_resolution/4; if( south_lat == -90 ) bbox.max().y() = 3*total_resolution/4; composite.insert( crop( transform( source, compose(kmltx,geotx), ConstantEdgeExtension() ), bbox ), bbox.min().x(), bbox.min().y() ); } else { composite.insert( crop( transform( source, compose(kmltx,geotx) ), bbox ), bbox.min().x(), bbox.min().y() ); } } // Prepare the composite std::cout << "Preparing composite..." << std::endl; BBox2i total_bbox(0,0,total_resolution,total_resolution); composite.prepare( total_bbox ); BBox2i data_bbox = composite.bbox(); data_bbox.crop( total_bbox ); // Prepare the quadtree KMLQuadTreeGenerator<PixelRGBA<uint8> > quadtree( output_file_name, composite, BBox2(-180,-180,360,360) ); quadtree.set_max_lod_pixels(512); quadtree.set_crop_bbox( data_bbox ); quadtree.set_crop_images( true ); quadtree.set_output_image_file_type( output_file_type ); // Generate the composite std::cout << "Compositing..." << std::endl; quadtree.generate(); return 0; } <commit_msg>Added a max-lod-pixels command-line option.<commit_after>// __BEGIN_LICENSE__ // // Copyright (C) 2006 United States Government as represented by the // Administrator of the National Aeronautics and Space Administration // (NASA). All Rights Reserved. // // Copyright 2006 Carnegie Mellon University. All rights reserved. // // This software is distributed under the NASA Open Source Agreement // (NOSA), version 1.3. The NOSA has been approved by the Open Source // Initiative. See the file COPYING at the top of the distribution // directory tree for the complete NOSA document. // // THE SUBJECT SOFTWARE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY OF ANY // KIND, EITHER EXPRESSED, IMPLIED, OR STATUTORY, INCLUDING, BUT NOT // LIMITED TO, ANY WARRANTY THAT THE SUBJECT SOFTWARE WILL CONFORM TO // SPECIFICATIONS, ANY IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR // A PARTICULAR PURPOSE, OR FREEDOM FROM INFRINGEMENT, ANY WARRANTY THAT // THE SUBJECT SOFTWARE WILL BE ERROR FREE, OR ANY WARRANTY THAT // DOCUMENTATION, IF PROVIDED, WILL CONFORM TO THE SUBJECT SOFTWARE. // // __END_LICENSE__ #ifdef _MSC_VER #pragma warning(disable:4244) #pragma warning(disable:4267) #pragma warning(disable:4996) #endif #include <stdlib.h> #include <iostream> #include <fstream> #include <boost/program_options.hpp> namespace po = boost::program_options; #include <vw/Core/Cache.h> #include <vw/Math/Matrix.h> #include <vw/Image/Transform.h> #include <vw/FileIO/DiskImageResource.h> #include <vw/FileIO/DiskImageResourceJPEG.h> #include <vw/FileIO/DiskImageView.h> #include <vw/Cartography/GeoReference.h> #include <vw/Cartography/GeoTransform.h> #include <vw/Cartography/FileIO.h> #include <vw/Mosaic/ImageComposite.h> #include <vw/Mosaic/KMLQuadTreeGenerator.h> using namespace vw; using namespace vw::math; using namespace vw::cartography; using namespace vw::mosaic; int main( int argc, char *argv[] ) { std::vector<std::string> image_files; std::string output_file_name; std::string output_file_type; float north_lat, south_lat; float east_lon, west_lon; unsigned utm_zone; int patch_size, patch_overlap; float jpeg_quality; unsigned cache_size; int max_lod_pixels; po::options_description desc("Options"); desc.add_options() ("help", "Display this help message") ("input-file", po::value<std::vector<std::string> >(&image_files), "Explicitly specify the input file") ("output-name,o", po::value<std::string>(&output_file_name)->default_value("output"), "Specify the base output filename") ("file-type", po::value<std::string>(&output_file_type)->default_value("jpg"), "Output file type") ("north", po::value<float>(&north_lat)->default_value(90.0), "The northernmost latitude in degrees") ("south", po::value<float>(&south_lat)->default_value(-90.0), "The southernmost latitude in degrees") ("east", po::value<float>(&east_lon)->default_value(180.0), "The easternmost latitude in degrees") ("west", po::value<float>(&west_lon)->default_value(-180.0), "The westernmost latitude in degrees") ("utm", po::value<unsigned>(&utm_zone), "Specify a UTM zone") ("size", po::value<int>(&patch_size)->default_value(256), "Patch size, in pixels") ("overlap", po::value<int>(&patch_overlap)->default_value(0), "Patch overlap, in pixels (must be even)") ("jpeg-quality", po::value<float>(&jpeg_quality)->default_value(0.75), "JPEG quality factor (0.0 to 1.0)") ("cache", po::value<unsigned>(&cache_size)->default_value(1024), "Cache size, in megabytes") ("max-lod-pixels", po::value<int>(&max_lod_pixels)->default_value(-1), "Max LoD in pixels, or -1 for none") ("verbose", "Verbose output"); po::positional_options_description p; p.add("input-file", -1); po::variables_map vm; po::store( po::command_line_parser( argc, argv ).options(desc).positional(p).run(), vm ); po::notify( vm ); if( vm.count("help") ) { std::cout << desc << std::endl; return 1; } if( vm.count("input-file") < 1 ) { std::cout << "Error: Must specify exactly one input file!" << std::endl; std::cout << desc << std::endl; return 1; } if( patch_size <= 0 ) { std::cerr << "Error: The patch size must be a positive number! (You specified " << patch_size << ".)" << std::endl; std::cout << desc << std::endl; return 1; } if( patch_overlap<0 || patch_overlap>=patch_size || patch_overlap%2==1 ) { std::cerr << "Error: The patch overlap must be an even number nonnegative number" << std::endl; std::cerr << "smaller than the patch size! (You specified " << patch_overlap << ".)" << std::endl; std::cout << desc << std::endl; return 1; } if( vm.count("verbose") ) { set_debug_level(VerboseDebugMessage); } DiskImageResourceJPEG::set_default_quality( jpeg_quality ); Cache::system_cache().resize( cache_size*1024*1024 ); GeoReference output_georef; output_georef.set_well_known_geogcs("WGS84"); int total_resolution = 1024; // Read in georeference info and compute total resolution bool manual = false; std::vector<GeoReference> georeferences; for( unsigned i=0; i<image_files.size(); ++i ) { DiskImageResourceGDAL file_resource( image_files[i] ); GeoReference input_georef; file_resource.read_georeference( input_georef ); // This is sort of a klugey way to check for a georef if( input_georef.proj4_str() == "" && input_georef.transform() == identity_matrix<3>() ) { if( image_files.size() == 1 ) { vw_out(InfoMessage) << "No georeferencing info found. Assuming Plate Carree WGS84: " << east_lon << " to " << west_lon << " E, " << south_lat << " to " << north_lat << " N." << std::endl; input_georef.set_well_known_geogcs("WGS84"); Matrix3x3 m; m(0,0) = (east_lon - west_lon) / file_resource.cols(); m(0,2) = west_lon + 0.5*m(0,0); m(1,1) = (south_lat - north_lat) / file_resource.rows(); m(1,2) = north_lat + 0.5*m(1,1); m(2,2) = 1; input_georef.set_transform( m ); manual = true; } else { vw_out(ErrorMessage) << "Error: No georeferencing info found for input file \"" << image_files[i] << "\"!" << std::endl; vw_out(ErrorMessage) << "(Manually-specified bounds are only allowed for single image files.)" << std::endl; exit(1); } } else if( vm.count("utm") ) input_georef.set_UTM( utm_zone ); georeferences.push_back( input_georef ); GeoTransform geotx( input_georef, output_georef ); Vector2 center_pixel( file_resource.cols()/2, file_resource.rows()/2 ); int resolution = GlobalKMLTransform::compute_resolution( geotx, center_pixel ); if( resolution > total_resolution ) total_resolution = resolution; } // Configure the composite ImageComposite<PixelRGBA<uint8> > composite; composite.set_draft_mode( true ); GlobalKMLTransform kmltx( total_resolution ); // Add the transformed input files to the composite for( unsigned i=0; i<image_files.size(); ++i ) { std::cout << "Adding file " << image_files[i] << std::endl; GeoTransform geotx( georeferences[i], output_georef ); DiskImageView<PixelRGBA<uint8> > source( image_files[i] ); BBox2i bbox = compute_transformed_bbox_fast_int( source, compose(kmltx,geotx) ); // Constant edge extension is better for transformations that // preserve the rectangularity of the image. At the moment we // only do this for manual transforms, alas. if( manual ) { // If the image is being super-sampled the computed bounding // box may be missing a pixel at the edges relative to what // you might expect, which can create visible artifacts if // it happens at the boundaries of the coordinate system. if( west_lon == -180 ) bbox.min().x() = 0; if( east_lon == 180 ) bbox.max().x() = total_resolution; if( north_lat == 90 ) bbox.min().y() = total_resolution/4; if( south_lat == -90 ) bbox.max().y() = 3*total_resolution/4; composite.insert( crop( transform( source, compose(kmltx,geotx), ConstantEdgeExtension() ), bbox ), bbox.min().x(), bbox.min().y() ); } else { composite.insert( crop( transform( source, compose(kmltx,geotx) ), bbox ), bbox.min().x(), bbox.min().y() ); } } // Prepare the composite std::cout << "Preparing composite..." << std::endl; BBox2i total_bbox(0,0,total_resolution,total_resolution); composite.prepare( total_bbox ); BBox2i data_bbox = composite.bbox(); data_bbox.crop( total_bbox ); // Prepare the quadtree KMLQuadTreeGenerator<PixelRGBA<uint8> > quadtree( output_file_name, composite, BBox2(-180,-180,360,360) ); quadtree.set_max_lod_pixels(max_lod_pixels); quadtree.set_crop_bbox( data_bbox ); quadtree.set_crop_images( true ); quadtree.set_output_image_file_type( output_file_type ); // Generate the composite std::cout << "Compositing..." << std::endl; quadtree.generate(); return 0; } <|endoftext|>
<commit_before>#include "jobwidget.h" WARNINGS_DISABLE #include <QAction> #include <QCheckBox> #include <QComboBox> #include <QEvent> #include <QKeySequence> #include <QLabel> #include <QMenu> #include <QMessageBox> #include <QPoint> #include <QSpinBox> #include <QStringList> #include <QTabWidget> #include <QUrl> #include <QVariant> #include <Qt> #include "ui_jobwidget.h" WARNINGS_ENABLE #include "TSettings.h" #include "messages/archiverestoreoptions.h" #include "archivelistwidget.h" #include "debug.h" #include "elidedclickablelabel.h" #include "filepickerwidget.h" #include "persistentmodel/archive.h" #include "persistentmodel/job.h" #include "restoredialog.h" #include "utils.h" JobDetailsWidget::JobDetailsWidget(QWidget *parent) : QWidget(parent), _ui(new Ui::JobDetailsWidget), _saveEnabled(false) { _ui->setupUi(this); _ui->archiveListWidget->setAttribute(Qt::WA_MacShowFocusRect, false); _ui->infoLabel->hide(); updateUi(); _fsEventUpdate.setSingleShot(true); connect(&_fsEventUpdate, &QTimer::timeout, this, &JobDetailsWidget::verifyJob); connect(_ui->infoLabel, &ElidedClickableLabel::clicked, this, &JobDetailsWidget::showJobPathsWarn); connect(_ui->jobNameLineEdit, &QLineEdit::textChanged, [this]() { emit enableSave(canSaveNew()); }); connect(_ui->jobTreeWidget, &FilePickerWidget::selectionChanged, [this]() { if(_job->objectKey().isEmpty()) emit enableSave(canSaveNew()); else save(); }); connect(_ui->jobTreeWidget, &FilePickerWidget::settingChanged, [this]() { if(!_job->objectKey().isEmpty()) save(); }); connect(_ui->scheduleComboBox, static_cast<void (QComboBox::*)(int)>( &QComboBox::currentIndexChanged), this, &JobDetailsWidget::save); connect(_ui->preservePathsCheckBox, &QCheckBox::toggled, this, &JobDetailsWidget::save); connect(_ui->traverseMountCheckBox, &QCheckBox::toggled, this, &JobDetailsWidget::save); connect(_ui->followSymLinksCheckBox, &QCheckBox::toggled, this, &JobDetailsWidget::save); connect(_ui->skipNoDumpCheckBox, &QCheckBox::toggled, this, &JobDetailsWidget::save); connect(_ui->skipFilesSizeSpinBox, &QSpinBox::editingFinished, this, &JobDetailsWidget::save); connect(_ui->skipFilesCheckBox, &QCheckBox::toggled, this, &JobDetailsWidget::save); connect(_ui->skipFilesLineEdit, &QLineEdit::editingFinished, this, &JobDetailsWidget::save); connect(_ui->hideButton, &QPushButton::clicked, this, &JobDetailsWidget::collapse); connect(_ui->restoreButton, &QPushButton::clicked, this, &JobDetailsWidget::restoreButtonClicked); connect(_ui->backupButton, &QPushButton::clicked, this, &JobDetailsWidget::backupButtonClicked); connect(_ui->archiveListWidget, &ArchiveListWidget::inspectArchive, this, &JobDetailsWidget::inspectJobArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::inspectArchive, _ui->archiveListWidget, &ArchiveListWidget::selectArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::restoreArchive, this, &JobDetailsWidget::restoreJobArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::deleteArchives, this, &JobDetailsWidget::deleteJobArchives); connect(_ui->skipFilesDefaultsButton, &QPushButton::clicked, [this]() { TSettings settings; _ui->skipFilesLineEdit->setText( settings.value("app/skip_system_files", DEFAULT_SKIP_SYSTEM_FILES) .toString()); }); connect(_ui->archiveListWidget, &ArchiveListWidget::customContextMenuRequested, this, &JobDetailsWidget::showArchiveListMenu); connect(_ui->actionDelete, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::deleteSelectedItems); connect(_ui->actionRestore, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::restoreSelectedItem); connect(_ui->actionInspect, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::inspectSelectedItem); } JobDetailsWidget::~JobDetailsWidget() { delete _ui; } JobPtr JobDetailsWidget::job() const { return _job; } void JobDetailsWidget::setJob(const JobPtr &job) { if(_job) { _job->removeWatcher(); disconnect(_job.data(), &Job::fsEvent, this, &JobDetailsWidget::fsEventReceived); disconnect(_job.data(), &Job::changed, this, &JobDetailsWidget::updateDetails); disconnect(_job.data(), &Job::purged, this, &JobDetailsWidget::collapse); } _saveEnabled = false; _job = job; // Creating a new job? if(_job->objectKey().isEmpty()) { _ui->restoreButton->hide(); _ui->backupButton->hide(); _ui->infoLabel->hide(); _ui->jobNameLabel->hide(); _ui->jobNameLineEdit->setText(_job->name()); _ui->jobNameLineEdit->show(); _ui->jobNameLineEdit->setFocus(); } else { _ui->restoreButton->show(); _ui->backupButton->show(); _ui->jobNameLabel->show(); _ui->jobNameLineEdit->hide(); connect(_job.data(), &Job::changed, this, &JobDetailsWidget::updateDetails); connect(_job.data(), &Job::fsEvent, this, &JobDetailsWidget::fsEventReceived); connect(_job.data(), &Job::purged, this, &JobDetailsWidget::collapse); job->installWatcher(); } _ui->tabWidget->setCurrentWidget(_ui->jobTreeTab); updateDetails(); _saveEnabled = true; } void JobDetailsWidget::save() { if(_saveEnabled && !_job->name().isEmpty()) { DEBUG << "SAVE JOB"; _job->setUrls(_ui->jobTreeWidget->getSelectedUrls()); _job->removeWatcher(); _job->installWatcher(); _job->setOptionScheduledEnabled( static_cast<JobSchedule>(_ui->scheduleComboBox->currentIndex())); _job->setOptionPreservePaths(_ui->preservePathsCheckBox->isChecked()); _job->setOptionTraverseMount(_ui->traverseMountCheckBox->isChecked()); _job->setOptionFollowSymLinks(_ui->followSymLinksCheckBox->isChecked()); _job->setOptionSkipNoDump(_ui->skipNoDumpCheckBox->isChecked()); _job->setOptionSkipFilesSize(_ui->skipFilesSizeSpinBox->value()); _job->setOptionSkipFiles(_ui->skipFilesCheckBox->isChecked()); _job->setOptionSkipFilesPatterns(_ui->skipFilesLineEdit->text()); _job->setSettingShowHidden(_ui->jobTreeWidget->settingShowHidden()); _job->setSettingShowSystem(_ui->jobTreeWidget->settingShowSystem()); _job->setSettingHideSymlinks(_ui->jobTreeWidget->settingHideSymlinks()); _job->save(); verifyJob(); } } void JobDetailsWidget::saveNew() { if(!canSaveNew()) return; DEBUG << "SAVE NEW JOB"; _job->setName(_ui->jobNameLineEdit->text()); if(!_job->archives().isEmpty()) { QMessageBox::StandardButton confirm = QMessageBox::question(this, "Add job", tr("Assign %1 found archives to this Job?") .arg(_job->archives().count()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); QList<ArchivePtr> empty; if(confirm == QMessageBox::No) _job->setArchives(empty); } save(); for(const ArchivePtr &archive : _job->archives()) { archive->setJobRef(_job->objectKey()); archive->save(); } emit jobAdded(_job); } void JobDetailsWidget::updateMatchingArchives(QList<ArchivePtr> archives) { if(!archives.isEmpty()) { _ui->infoLabel->setStyleSheet(""); _ui->infoLabel->setText(tr("Found %1 unassigned archives matching this" " Job description. Go to Archives tab below" " to review.") .arg(archives.count())); _ui->infoLabel->show(); _ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf( _ui->archiveListTab), true); } else { _ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf( _ui->archiveListTab), false); } _job->setArchives(archives); _ui->archiveListWidget->setArchives(_job->archives()); _ui->tabWidget->setTabText( _ui->tabWidget->indexOf(_ui->archiveListTab), tr("Archives (%1)").arg(_job->archives().count())); } void JobDetailsWidget::changeEvent(QEvent *event) { if(event->type() == QEvent::LanguageChange) { _ui->retranslateUi(this); updateUi(); if(_job) { if(_job->objectKey().isEmpty()) canSaveNew(); else updateDetails(); } } QWidget::changeEvent(event); } void JobDetailsWidget::updateDetails() { if(!_job) return; DEBUG << "UPDATE JOB DETAILS"; _saveEnabled = false; _ui->jobNameLabel->setText(_job->name()); _ui->jobTreeWidget->setSettingShowHidden(_job->settingShowHidden()); _ui->jobTreeWidget->setSettingShowSystem(_job->settingShowSystem()); _ui->jobTreeWidget->setSettingHideSymlinks(_job->settingHideSymlinks()); _ui->jobTreeWidget->blockSignals(true); _ui->jobTreeWidget->setSelectedUrls(_job->urls()); _ui->jobTreeWidget->blockSignals(false); _ui->archiveListWidget->setArchives(_job->archives()); _ui->scheduleComboBox->setCurrentIndex( static_cast<int>(_job->optionScheduledEnabled())); _ui->preservePathsCheckBox->setChecked(_job->optionPreservePaths()); _ui->traverseMountCheckBox->setChecked(_job->optionTraverseMount()); _ui->followSymLinksCheckBox->setChecked(_job->optionFollowSymLinks()); _ui->skipNoDumpCheckBox->setChecked(_job->optionSkipNoDump()); _ui->skipFilesSizeSpinBox->setValue(_job->optionSkipFilesSize()); _ui->skipFilesCheckBox->setChecked(_job->optionSkipFiles()); _ui->skipFilesLineEdit->setText(_job->optionSkipFilesPatterns()); _ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf(_ui->archiveListTab), _job->archives().count()); _ui->tabWidget->setTabText( _ui->tabWidget->indexOf(_ui->archiveListTab), tr("Archives (%1)").arg(_job->archives().count())); verifyJob(); _saveEnabled = true; // Needed when morphing a job from the Backup tab to Jobs tab. There's // probably a better way of doing this. canSaveNew(); } void JobDetailsWidget::restoreButtonClicked() { if(_job && !_job->archives().isEmpty()) { ArchivePtr archive = _job->archives().first(); RestoreDialog *restoreDialog = new RestoreDialog(this, archive); restoreDialog->show(); connect(restoreDialog, &RestoreDialog::accepted, [this, restoreDialog] { emit restoreJobArchive(restoreDialog->archive(), restoreDialog->getOptions()); }); } } void JobDetailsWidget::backupButtonClicked() { if(_job) emit backupJob(_job); } bool JobDetailsWidget::canSaveNew() { QString name = _ui->jobNameLineEdit->text(); _ui->infoLabel->setStyleSheet(""); _ui->infoLabel->clear(); _ui->infoLabel->hide(); if(_job->objectKey().isEmpty() && !name.isEmpty()) { // Check that we don't have any leading or trailing whitespace if(name.simplified() != name) { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText(tr( "Job name cannot contain a leading or trailing whitespace.")); _ui->infoLabel->show(); return false; } JobPtr newJob(new Job); newJob->setName(name); if(!newJob->doesKeyExist(newJob->name())) { emit findMatchingArchives(newJob->archivePrefix()); if(!_ui->jobTreeWidget->getSelectedUrls().isEmpty()) { return true; } else { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText(tr("No backup paths selected.")); _ui->infoLabel->show(); } } else { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText( tr("Job name must be unique amongst existing" " Jobs.")); _ui->infoLabel->show(); } } return false; } void JobDetailsWidget::showArchiveListMenu(const QPoint &pos) { QPoint globalPos = _ui->archiveListWidget->viewport()->mapToGlobal(pos); QMenu archiveListMenu(_ui->archiveListWidget); if(!_ui->archiveListWidget->selectedItems().isEmpty()) { if(_ui->archiveListWidget->selectedItems().count() == 1) { archiveListMenu.addAction(_ui->actionInspect); archiveListMenu.addAction(_ui->actionRestore); } archiveListMenu.addAction(_ui->actionDelete); } archiveListMenu.exec(globalPos); } void JobDetailsWidget::fsEventReceived() { _fsEventUpdate.start(250); // coalesce update events with a 250ms time delay } void JobDetailsWidget::showJobPathsWarn() { if(_job->urls().isEmpty()) return; QMessageBox *msg = new QMessageBox(this); msg->setAttribute(Qt::WA_DeleteOnClose, true); msg->setText(tr("Previously selected backup paths for this Job are not" " accessible anymore and thus backups may be incomplete." " Mount missing drives or make a new selection. Press Show" " details to list all backup paths for Job %1:") .arg(_job->name())); QStringList urls; for(const QUrl &url : _job->urls()) urls << url.toLocalFile(); msg->setDetailedText(urls.join('\n')); msg->show(); } void JobDetailsWidget::verifyJob() { if(_job->objectKey().isEmpty()) return; _ui->jobTreeWidget->blockSignals(true); _ui->jobTreeWidget->setSelectedUrls(_job->urls()); _ui->jobTreeWidget->blockSignals(false); bool validUrls = _job->validateUrls(); _ui->infoLabel->setVisible(!validUrls); if(!validUrls) { if(_job->urls().isEmpty()) { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText(tr("This Job has no backup paths selected. " "Please make a selection.")); } else { _ui->infoLabel->setText( tr("Previously selected backup paths are not" " accessible. Click here for details.")); } } } void JobDetailsWidget::updateUi() { _ui->hideButton->setToolTip(_ui->hideButton->toolTip().arg( QKeySequence(Qt::Key_Escape).toString(QKeySequence::NativeText))); } <commit_msg>JobDetailsWidget: reorganize constructor, updateDetails<commit_after>#include "jobwidget.h" WARNINGS_DISABLE #include <QAction> #include <QCheckBox> #include <QComboBox> #include <QEvent> #include <QKeySequence> #include <QLabel> #include <QMenu> #include <QMessageBox> #include <QPoint> #include <QSpinBox> #include <QStringList> #include <QTabWidget> #include <QUrl> #include <QVariant> #include <Qt> #include "ui_jobwidget.h" WARNINGS_ENABLE #include "TSettings.h" #include "messages/archiverestoreoptions.h" #include "archivelistwidget.h" #include "debug.h" #include "elidedclickablelabel.h" #include "filepickerwidget.h" #include "persistentmodel/archive.h" #include "persistentmodel/job.h" #include "restoredialog.h" #include "utils.h" JobDetailsWidget::JobDetailsWidget(QWidget *parent) : QWidget(parent), _ui(new Ui::JobDetailsWidget), _saveEnabled(false) { _ui->setupUi(this); _ui->archiveListWidget->setAttribute(Qt::WA_MacShowFocusRect, false); _ui->infoLabel->hide(); updateUi(); _fsEventUpdate.setSingleShot(true); connect(&_fsEventUpdate, &QTimer::timeout, this, &JobDetailsWidget::verifyJob); connect(_ui->infoLabel, &ElidedClickableLabel::clicked, this, &JobDetailsWidget::showJobPathsWarn); connect(_ui->hideButton, &QPushButton::clicked, this, &JobDetailsWidget::collapse); connect(_ui->restoreButton, &QPushButton::clicked, this, &JobDetailsWidget::restoreButtonClicked); connect(_ui->backupButton, &QPushButton::clicked, this, &JobDetailsWidget::backupButtonClicked); connect(_ui->jobNameLineEdit, &QLineEdit::textChanged, [this]() { emit enableSave(canSaveNew()); }); connect(_ui->jobTreeWidget, &FilePickerWidget::selectionChanged, [this]() { if(_job->objectKey().isEmpty()) emit enableSave(canSaveNew()); else save(); }); connect(_ui->jobTreeWidget, &FilePickerWidget::settingChanged, [this]() { if(!_job->objectKey().isEmpty()) save(); }); connect(_ui->skipFilesDefaultsButton, &QPushButton::clicked, [this]() { TSettings settings; _ui->skipFilesLineEdit->setText( settings.value("app/skip_system_files", DEFAULT_SKIP_SYSTEM_FILES) .toString()); }); connect(_ui->scheduleComboBox, static_cast<void (QComboBox::*)(int)>( &QComboBox::currentIndexChanged), this, &JobDetailsWidget::save); connect(_ui->preservePathsCheckBox, &QCheckBox::toggled, this, &JobDetailsWidget::save); connect(_ui->traverseMountCheckBox, &QCheckBox::toggled, this, &JobDetailsWidget::save); connect(_ui->followSymLinksCheckBox, &QCheckBox::toggled, this, &JobDetailsWidget::save); connect(_ui->skipNoDumpCheckBox, &QCheckBox::toggled, this, &JobDetailsWidget::save); connect(_ui->skipFilesSizeSpinBox, &QSpinBox::editingFinished, this, &JobDetailsWidget::save); connect(_ui->skipFilesCheckBox, &QCheckBox::toggled, this, &JobDetailsWidget::save); connect(_ui->skipFilesLineEdit, &QLineEdit::editingFinished, this, &JobDetailsWidget::save); connect(_ui->archiveListWidget, &ArchiveListWidget::inspectArchive, this, &JobDetailsWidget::inspectJobArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::inspectArchive, _ui->archiveListWidget, &ArchiveListWidget::selectArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::restoreArchive, this, &JobDetailsWidget::restoreJobArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::deleteArchives, this, &JobDetailsWidget::deleteJobArchives); connect(_ui->archiveListWidget, &ArchiveListWidget::customContextMenuRequested, this, &JobDetailsWidget::showArchiveListMenu); connect(_ui->actionDelete, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::deleteSelectedItems); connect(_ui->actionRestore, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::restoreSelectedItem); connect(_ui->actionInspect, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::inspectSelectedItem); } JobDetailsWidget::~JobDetailsWidget() { delete _ui; } JobPtr JobDetailsWidget::job() const { return _job; } void JobDetailsWidget::setJob(const JobPtr &job) { if(_job) { _job->removeWatcher(); disconnect(_job.data(), &Job::fsEvent, this, &JobDetailsWidget::fsEventReceived); disconnect(_job.data(), &Job::changed, this, &JobDetailsWidget::updateDetails); disconnect(_job.data(), &Job::purged, this, &JobDetailsWidget::collapse); } _saveEnabled = false; _job = job; // Creating a new job? if(_job->objectKey().isEmpty()) { _ui->restoreButton->hide(); _ui->backupButton->hide(); _ui->infoLabel->hide(); _ui->jobNameLabel->hide(); _ui->jobNameLineEdit->setText(_job->name()); _ui->jobNameLineEdit->show(); _ui->jobNameLineEdit->setFocus(); } else { _ui->restoreButton->show(); _ui->backupButton->show(); _ui->jobNameLabel->show(); _ui->jobNameLineEdit->hide(); connect(_job.data(), &Job::changed, this, &JobDetailsWidget::updateDetails); connect(_job.data(), &Job::fsEvent, this, &JobDetailsWidget::fsEventReceived); connect(_job.data(), &Job::purged, this, &JobDetailsWidget::collapse); job->installWatcher(); } _ui->tabWidget->setCurrentWidget(_ui->jobTreeTab); updateDetails(); _saveEnabled = true; } void JobDetailsWidget::save() { if(_saveEnabled && !_job->name().isEmpty()) { DEBUG << "SAVE JOB"; _job->setUrls(_ui->jobTreeWidget->getSelectedUrls()); _job->removeWatcher(); _job->installWatcher(); _job->setOptionScheduledEnabled( static_cast<JobSchedule>(_ui->scheduleComboBox->currentIndex())); _job->setOptionPreservePaths(_ui->preservePathsCheckBox->isChecked()); _job->setOptionTraverseMount(_ui->traverseMountCheckBox->isChecked()); _job->setOptionFollowSymLinks(_ui->followSymLinksCheckBox->isChecked()); _job->setOptionSkipNoDump(_ui->skipNoDumpCheckBox->isChecked()); _job->setOptionSkipFilesSize(_ui->skipFilesSizeSpinBox->value()); _job->setOptionSkipFiles(_ui->skipFilesCheckBox->isChecked()); _job->setOptionSkipFilesPatterns(_ui->skipFilesLineEdit->text()); _job->setSettingShowHidden(_ui->jobTreeWidget->settingShowHidden()); _job->setSettingShowSystem(_ui->jobTreeWidget->settingShowSystem()); _job->setSettingHideSymlinks(_ui->jobTreeWidget->settingHideSymlinks()); _job->save(); verifyJob(); } } void JobDetailsWidget::saveNew() { if(!canSaveNew()) return; DEBUG << "SAVE NEW JOB"; _job->setName(_ui->jobNameLineEdit->text()); if(!_job->archives().isEmpty()) { QMessageBox::StandardButton confirm = QMessageBox::question(this, "Add job", tr("Assign %1 found archives to this Job?") .arg(_job->archives().count()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); QList<ArchivePtr> empty; if(confirm == QMessageBox::No) _job->setArchives(empty); } save(); for(const ArchivePtr &archive : _job->archives()) { archive->setJobRef(_job->objectKey()); archive->save(); } emit jobAdded(_job); } void JobDetailsWidget::updateMatchingArchives(QList<ArchivePtr> archives) { if(!archives.isEmpty()) { _ui->infoLabel->setStyleSheet(""); _ui->infoLabel->setText(tr("Found %1 unassigned archives matching this" " Job description. Go to Archives tab below" " to review.") .arg(archives.count())); _ui->infoLabel->show(); _ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf( _ui->archiveListTab), true); } else { _ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf( _ui->archiveListTab), false); } _job->setArchives(archives); _ui->archiveListWidget->setArchives(_job->archives()); _ui->tabWidget->setTabText( _ui->tabWidget->indexOf(_ui->archiveListTab), tr("Archives (%1)").arg(_job->archives().count())); } void JobDetailsWidget::changeEvent(QEvent *event) { if(event->type() == QEvent::LanguageChange) { _ui->retranslateUi(this); updateUi(); if(_job) { if(_job->objectKey().isEmpty()) canSaveNew(); else updateDetails(); } } QWidget::changeEvent(event); } void JobDetailsWidget::updateDetails() { if(!_job) return; DEBUG << "UPDATE JOB DETAILS"; _saveEnabled = false; _ui->jobNameLabel->setText(_job->name()); _ui->jobTreeWidget->blockSignals(true); _ui->jobTreeWidget->setSelectedUrls(_job->urls()); _ui->jobTreeWidget->blockSignals(false); _ui->jobTreeWidget->setSettingShowHidden(_job->settingShowHidden()); _ui->jobTreeWidget->setSettingShowSystem(_job->settingShowSystem()); _ui->jobTreeWidget->setSettingHideSymlinks(_job->settingHideSymlinks()); _ui->scheduleComboBox->setCurrentIndex( static_cast<int>(_job->optionScheduledEnabled())); _ui->preservePathsCheckBox->setChecked(_job->optionPreservePaths()); _ui->traverseMountCheckBox->setChecked(_job->optionTraverseMount()); _ui->followSymLinksCheckBox->setChecked(_job->optionFollowSymLinks()); _ui->skipNoDumpCheckBox->setChecked(_job->optionSkipNoDump()); _ui->skipFilesSizeSpinBox->setValue(_job->optionSkipFilesSize()); _ui->skipFilesCheckBox->setChecked(_job->optionSkipFiles()); _ui->skipFilesLineEdit->setText(_job->optionSkipFilesPatterns()); _ui->archiveListWidget->setArchives(_job->archives()); _ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf(_ui->archiveListTab), _job->archives().count()); _ui->tabWidget->setTabText( _ui->tabWidget->indexOf(_ui->archiveListTab), tr("Archives (%1)").arg(_job->archives().count())); verifyJob(); _saveEnabled = true; // Needed when morphing a job from the Backup tab to Jobs tab. There's // probably a better way of doing this. canSaveNew(); } void JobDetailsWidget::restoreButtonClicked() { if(_job && !_job->archives().isEmpty()) { ArchivePtr archive = _job->archives().first(); RestoreDialog *restoreDialog = new RestoreDialog(this, archive); restoreDialog->show(); connect(restoreDialog, &RestoreDialog::accepted, [this, restoreDialog] { emit restoreJobArchive(restoreDialog->archive(), restoreDialog->getOptions()); }); } } void JobDetailsWidget::backupButtonClicked() { if(_job) emit backupJob(_job); } bool JobDetailsWidget::canSaveNew() { QString name = _ui->jobNameLineEdit->text(); _ui->infoLabel->setStyleSheet(""); _ui->infoLabel->clear(); _ui->infoLabel->hide(); if(_job->objectKey().isEmpty() && !name.isEmpty()) { // Check that we don't have any leading or trailing whitespace if(name.simplified() != name) { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText(tr( "Job name cannot contain a leading or trailing whitespace.")); _ui->infoLabel->show(); return false; } JobPtr newJob(new Job); newJob->setName(name); if(!newJob->doesKeyExist(newJob->name())) { emit findMatchingArchives(newJob->archivePrefix()); if(!_ui->jobTreeWidget->getSelectedUrls().isEmpty()) { return true; } else { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText(tr("No backup paths selected.")); _ui->infoLabel->show(); } } else { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText( tr("Job name must be unique amongst existing" " Jobs.")); _ui->infoLabel->show(); } } return false; } void JobDetailsWidget::showArchiveListMenu(const QPoint &pos) { QMenu archiveListMenu(_ui->archiveListWidget); if(!_ui->archiveListWidget->selectedItems().isEmpty()) { if(_ui->archiveListWidget->selectedItems().count() == 1) { archiveListMenu.addAction(_ui->actionInspect); archiveListMenu.addAction(_ui->actionRestore); } archiveListMenu.addAction(_ui->actionDelete); } QPoint globalPos = _ui->archiveListWidget->viewport()->mapToGlobal(pos); archiveListMenu.exec(globalPos); } void JobDetailsWidget::fsEventReceived() { _fsEventUpdate.start(250); // coalesce update events with a 250ms time delay } void JobDetailsWidget::showJobPathsWarn() { if(_job->urls().isEmpty()) return; QMessageBox *msg = new QMessageBox(this); msg->setAttribute(Qt::WA_DeleteOnClose, true); msg->setText(tr("Previously selected backup paths for this Job are not" " accessible anymore and thus backups may be incomplete." " Mount missing drives or make a new selection. Press Show" " details to list all backup paths for Job %1:") .arg(_job->name())); QStringList urls; for(const QUrl &url : _job->urls()) urls << url.toLocalFile(); msg->setDetailedText(urls.join('\n')); msg->show(); } void JobDetailsWidget::verifyJob() { if(_job->objectKey().isEmpty()) return; _ui->jobTreeWidget->blockSignals(true); _ui->jobTreeWidget->setSelectedUrls(_job->urls()); _ui->jobTreeWidget->blockSignals(false); bool validUrls = _job->validateUrls(); _ui->infoLabel->setVisible(!validUrls); if(!validUrls) { if(_job->urls().isEmpty()) { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText(tr("This Job has no backup paths selected. " "Please make a selection.")); } else { _ui->infoLabel->setText( tr("Previously selected backup paths are not" " accessible. Click here for details.")); } } } void JobDetailsWidget::updateUi() { _ui->hideButton->setToolTip(_ui->hideButton->toolTip().arg( QKeySequence(Qt::Key_Escape).toString(QKeySequence::NativeText))); } <|endoftext|>
<commit_before>#include "jobwidget.h" #include "debug.h" #include "restoredialog.h" #include "utils.h" #include "ui_jobwidget.h" #include <QMenu> #include <QMessageBox> #include <TSettings.h> JobWidget::JobWidget(QWidget *parent) : QWidget(parent), _ui(new Ui::JobWidget), _saveEnabled(false) { _ui->setupUi(this); _ui->archiveListWidget->setAttribute(Qt::WA_MacShowFocusRect, false); _ui->infoLabel->hide(); updateUi(); _fsEventUpdate.setSingleShot(true); connect(&_fsEventUpdate, &QTimer::timeout, this, &JobWidget::verifyJob); connect(_ui->infoLabel, &ElidedLabel::clicked, this, &JobWidget::showJobPathsWarn); connect(_ui->jobNameLineEdit, &QLineEdit::textChanged, [&]() { emit enableSave(canSaveNew()); }); connect(_ui->jobTreeWidget, &FilePickerWidget::selectionChanged, [&]() { if(_job->objectKey().isEmpty()) emit enableSave(canSaveNew()); else save(); }); connect(_ui->jobTreeWidget, &FilePickerWidget::settingChanged, [&]() { if(!_job->objectKey().isEmpty()) save(); }); connect(_ui->scheduleComboBox, static_cast<void (QComboBox::*)(int)>( &QComboBox::currentIndexChanged), this, &JobWidget::save); connect(_ui->preservePathsCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui->traverseMountCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui->followSymLinksCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui->skipNoDumpCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui->skipFilesSizeSpinBox, &QSpinBox::editingFinished, this, &JobWidget::save); connect(_ui->skipFilesCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui->skipFilesLineEdit, &QLineEdit::editingFinished, this, &JobWidget::save); connect(_ui->hideButton, &QPushButton::clicked, this, &JobWidget::collapse); connect(_ui->restoreButton, &QPushButton::clicked, this, &JobWidget::restoreButtonClicked); connect(_ui->backupButton, &QPushButton::clicked, this, &JobWidget::backupButtonClicked); connect(_ui->archiveListWidget, &ArchiveListWidget::inspectArchive, this, &JobWidget::inspectJobArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::inspectArchive, _ui->archiveListWidget, &ArchiveListWidget::selectArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::restoreArchive, this, &JobWidget::restoreJobArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::deleteArchives, this, &JobWidget::deleteJobArchives); connect(_ui->skipFilesDefaultsButton, &QPushButton::clicked, [&]() { TSettings settings; _ui->skipFilesLineEdit->setText( settings.value("app/skip_system_files", DEFAULT_SKIP_SYSTEM_FILES) .toString()); }); connect(_ui->archiveListWidget, &ArchiveListWidget::customContextMenuRequested, this, &JobWidget::showArchiveListMenu); connect(_ui->actionDelete, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::deleteSelectedItems); connect(_ui->actionRestore, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::restoreSelectedItem); connect(_ui->actionInspect, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::inspectSelectedItem); } JobWidget::~JobWidget() { delete _ui; } JobPtr JobWidget::job() const { return _job; } void JobWidget::setJob(const JobPtr &job) { if(_job) { _job->removeWatcher(); disconnect(_job.data(), &Job::fsEvent, this, &JobWidget::fsEventReceived); disconnect(_job.data(), &Job::changed, this, &JobWidget::updateDetails); disconnect(_job.data(), &Job::purged, this, &JobWidget::collapse); } _saveEnabled = false; _job = job; // Creating a new job? if(_job->objectKey().isEmpty()) { _ui->restoreButton->hide(); _ui->backupButton->hide(); _ui->infoLabel->hide(); _ui->jobNameLabel->hide(); _ui->jobNameLineEdit->setText(_job->name()); _ui->jobNameLineEdit->show(); _ui->jobNameLineEdit->setFocus(); } else { _ui->restoreButton->show(); _ui->backupButton->show(); _ui->jobNameLabel->show(); _ui->jobNameLineEdit->hide(); connect(_job.data(), &Job::changed, this, &JobWidget::updateDetails); connect(_job.data(), &Job::fsEvent, this, &JobWidget::fsEventReceived); connect(_job.data(), &Job::purged, this, &JobWidget::collapse); job->installWatcher(); } _ui->tabWidget->setCurrentWidget(_ui->jobTreeTab); updateDetails(); _saveEnabled = true; } void JobWidget::save() { if(_saveEnabled && !_job->name().isEmpty()) { DEBUG << "SAVE JOB"; _job->setUrls(_ui->jobTreeWidget->getSelectedUrls()); _job->removeWatcher(); _job->installWatcher(); _job->setOptionScheduledEnabled( static_cast<JobSchedule>(_ui->scheduleComboBox->currentIndex())); _job->setOptionPreservePaths(_ui->preservePathsCheckBox->isChecked()); _job->setOptionTraverseMount(_ui->traverseMountCheckBox->isChecked()); _job->setOptionFollowSymLinks(_ui->followSymLinksCheckBox->isChecked()); _job->setOptionSkipNoDump(_ui->skipNoDumpCheckBox->isChecked()); _job->setOptionSkipFilesSize(_ui->skipFilesSizeSpinBox->value()); _job->setOptionSkipFiles(_ui->skipFilesCheckBox->isChecked()); _job->setOptionSkipFilesPatterns(_ui->skipFilesLineEdit->text()); _job->setSettingShowHidden(_ui->jobTreeWidget->settingShowHidden()); _job->setSettingShowSystem(_ui->jobTreeWidget->settingShowSystem()); _job->setSettingHideSymlinks(_ui->jobTreeWidget->settingHideSymlinks()); _job->save(); verifyJob(); } } void JobWidget::saveNew() { if(!canSaveNew()) return; DEBUG << "SAVE NEW JOB"; _job->setName(_ui->jobNameLineEdit->text()); if(!_job->archives().isEmpty()) { QMessageBox::StandardButton confirm = QMessageBox::question(this, "Add job", tr("Assign %1 found archives to this Job?") .arg(_job->archives().count()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); QList<ArchivePtr> empty; if(confirm == QMessageBox::No) _job->setArchives(empty); } save(); for(const ArchivePtr &archive : _job->archives()) { archive->setJobRef(_job->objectKey()); archive->save(); } emit jobAdded(_job); } void JobWidget::updateMatchingArchives(QList<ArchivePtr> archives) { if(!archives.isEmpty()) { _ui->infoLabel->setStyleSheet(""); _ui->infoLabel->setText(tr("Found %1 unassigned archives matching this" " Job description. Go to Archives tab below" " to review.") .arg(archives.count())); _ui->infoLabel->show(); _ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf( _ui->archiveListTab), true); } else { _ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf( _ui->archiveListTab), false); } _job->setArchives(archives); _ui->archiveListWidget->setArchives(_job->archives()); _ui->tabWidget->setTabText(_ui->tabWidget->indexOf(_ui->archiveListTab), tr("Archives (%1)").arg(_job->archives().count())); } void JobWidget::changeEvent(QEvent *event) { if(event->type() == QEvent::LanguageChange) { _ui->retranslateUi(this); updateUi(); if(_job) { if(_job->objectKey().isEmpty()) canSaveNew(); else updateDetails(); } } QWidget::changeEvent(event); } void JobWidget::updateDetails() { if(!_job) return; DEBUG << "UPDATE JOB DETAILS"; _saveEnabled = false; _ui->jobNameLabel->setText(_job->name()); _ui->jobTreeWidget->setSettingShowHidden(_job->settingShowHidden()); _ui->jobTreeWidget->setSettingShowSystem(_job->settingShowSystem()); _ui->jobTreeWidget->setSettingHideSymlinks(_job->settingHideSymlinks()); _ui->jobTreeWidget->blockSignals(true); _ui->jobTreeWidget->setSelectedUrls(_job->urls()); _ui->jobTreeWidget->blockSignals(false); _ui->archiveListWidget->setArchives(_job->archives()); _ui->scheduleComboBox->setCurrentIndex( static_cast<int>(_job->optionScheduledEnabled())); _ui->preservePathsCheckBox->setChecked(_job->optionPreservePaths()); _ui->traverseMountCheckBox->setChecked(_job->optionTraverseMount()); _ui->followSymLinksCheckBox->setChecked(_job->optionFollowSymLinks()); _ui->skipNoDumpCheckBox->setChecked(_job->optionSkipNoDump()); _ui->skipFilesSizeSpinBox->setValue(_job->optionSkipFilesSize()); _ui->skipFilesCheckBox->setChecked(_job->optionSkipFiles()); _ui->skipFilesLineEdit->setText(_job->optionSkipFilesPatterns()); _ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf(_ui->archiveListTab), _job->archives().count()); _ui->tabWidget->setTabText(_ui->tabWidget->indexOf(_ui->archiveListTab), tr("Archives (%1)").arg(_job->archives().count())); verifyJob(); _saveEnabled = true; // Needed when morphing a job from the Backup tab to Jobs tab. There's // probably a better way of doing this. canSaveNew(); } void JobWidget::restoreButtonClicked() { if(_job && !_job->archives().isEmpty()) { ArchivePtr archive = _job->archives().first(); RestoreDialog *restoreDialog = new RestoreDialog(this, archive); restoreDialog->show(); connect(restoreDialog, &RestoreDialog::accepted, [=] { emit restoreJobArchive(restoreDialog->archive(), restoreDialog->getOptions()); }); } } void JobWidget::backupButtonClicked() { if(_job) emit backupJob(_job); } bool JobWidget::canSaveNew() { _ui->infoLabel->setStyleSheet(""); _ui->infoLabel->clear(); _ui->infoLabel->hide(); if(_job->objectKey().isEmpty() && !_ui->jobNameLineEdit->text().isEmpty()) { JobPtr newJob(new Job); newJob->setName(_ui->jobNameLineEdit->text()); if(!newJob->doesKeyExist(newJob->name())) { emit findMatchingArchives(newJob->archivePrefix()); if(!_ui->jobTreeWidget->getSelectedUrls().isEmpty()) { return true; } else { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText(tr("No backup paths selected.")); _ui->infoLabel->show(); } } else { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText( tr("Job name must be unique amongst existing" " Jobs.")); _ui->infoLabel->show(); } } return false; } void JobWidget::showArchiveListMenu(const QPoint &pos) { QPoint globalPos = _ui->archiveListWidget->viewport()->mapToGlobal(pos); QMenu archiveListMenu(_ui->archiveListWidget); if(!_ui->archiveListWidget->selectedItems().isEmpty()) { if(_ui->archiveListWidget->selectedItems().count() == 1) { archiveListMenu.addAction(_ui->actionInspect); archiveListMenu.addAction(_ui->actionRestore); } archiveListMenu.addAction(_ui->actionDelete); } archiveListMenu.exec(globalPos); } void JobWidget::fsEventReceived() { _fsEventUpdate.start(250); // coalesce update events with a 250ms time delay } void JobWidget::showJobPathsWarn() { if(_job->urls().isEmpty()) return; QMessageBox *msg = new QMessageBox(this); msg->setAttribute(Qt::WA_DeleteOnClose, true); msg->setText(tr("Previously selected backup paths for this Job are not" " accessible anymore and thus backups may be incomplete." " Mount missing drives or make a new selection. Press Show" " details to list all backup paths for Job %1:") .arg(_job->name())); QStringList urls; for(const QUrl &url : _job->urls()) urls << url.toLocalFile(); msg->setDetailedText(urls.join('\n')); msg->show(); } void JobWidget::verifyJob() { if(_job->objectKey().isEmpty()) return; _ui->jobTreeWidget->blockSignals(true); _ui->jobTreeWidget->setSelectedUrls(_job->urls()); _ui->jobTreeWidget->blockSignals(false); bool validUrls = _job->validateUrls(); _ui->infoLabel->setVisible(!validUrls); if(!validUrls) { if(_job->urls().isEmpty()) { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText(tr("This Job has no backup paths selected. " "Please make a selection.")); } else { _ui->infoLabel->setText( tr("Previously selected backup paths are not" " accessible. Click here for details.")); } } } void JobWidget::updateUi() { _ui->hideButton->setToolTip(_ui->hideButton->toolTip().arg( QKeySequence(Qt::Key_Escape).toString(QKeySequence::NativeText))); } <commit_msg>JobWidget: simplify canSaveNew()<commit_after>#include "jobwidget.h" #include "debug.h" #include "restoredialog.h" #include "utils.h" #include "ui_jobwidget.h" #include <QMenu> #include <QMessageBox> #include <TSettings.h> JobWidget::JobWidget(QWidget *parent) : QWidget(parent), _ui(new Ui::JobWidget), _saveEnabled(false) { _ui->setupUi(this); _ui->archiveListWidget->setAttribute(Qt::WA_MacShowFocusRect, false); _ui->infoLabel->hide(); updateUi(); _fsEventUpdate.setSingleShot(true); connect(&_fsEventUpdate, &QTimer::timeout, this, &JobWidget::verifyJob); connect(_ui->infoLabel, &ElidedLabel::clicked, this, &JobWidget::showJobPathsWarn); connect(_ui->jobNameLineEdit, &QLineEdit::textChanged, [&]() { emit enableSave(canSaveNew()); }); connect(_ui->jobTreeWidget, &FilePickerWidget::selectionChanged, [&]() { if(_job->objectKey().isEmpty()) emit enableSave(canSaveNew()); else save(); }); connect(_ui->jobTreeWidget, &FilePickerWidget::settingChanged, [&]() { if(!_job->objectKey().isEmpty()) save(); }); connect(_ui->scheduleComboBox, static_cast<void (QComboBox::*)(int)>( &QComboBox::currentIndexChanged), this, &JobWidget::save); connect(_ui->preservePathsCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui->traverseMountCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui->followSymLinksCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui->skipNoDumpCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui->skipFilesSizeSpinBox, &QSpinBox::editingFinished, this, &JobWidget::save); connect(_ui->skipFilesCheckBox, &QCheckBox::toggled, this, &JobWidget::save); connect(_ui->skipFilesLineEdit, &QLineEdit::editingFinished, this, &JobWidget::save); connect(_ui->hideButton, &QPushButton::clicked, this, &JobWidget::collapse); connect(_ui->restoreButton, &QPushButton::clicked, this, &JobWidget::restoreButtonClicked); connect(_ui->backupButton, &QPushButton::clicked, this, &JobWidget::backupButtonClicked); connect(_ui->archiveListWidget, &ArchiveListWidget::inspectArchive, this, &JobWidget::inspectJobArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::inspectArchive, _ui->archiveListWidget, &ArchiveListWidget::selectArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::restoreArchive, this, &JobWidget::restoreJobArchive); connect(_ui->archiveListWidget, &ArchiveListWidget::deleteArchives, this, &JobWidget::deleteJobArchives); connect(_ui->skipFilesDefaultsButton, &QPushButton::clicked, [&]() { TSettings settings; _ui->skipFilesLineEdit->setText( settings.value("app/skip_system_files", DEFAULT_SKIP_SYSTEM_FILES) .toString()); }); connect(_ui->archiveListWidget, &ArchiveListWidget::customContextMenuRequested, this, &JobWidget::showArchiveListMenu); connect(_ui->actionDelete, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::deleteSelectedItems); connect(_ui->actionRestore, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::restoreSelectedItem); connect(_ui->actionInspect, &QAction::triggered, _ui->archiveListWidget, &ArchiveListWidget::inspectSelectedItem); } JobWidget::~JobWidget() { delete _ui; } JobPtr JobWidget::job() const { return _job; } void JobWidget::setJob(const JobPtr &job) { if(_job) { _job->removeWatcher(); disconnect(_job.data(), &Job::fsEvent, this, &JobWidget::fsEventReceived); disconnect(_job.data(), &Job::changed, this, &JobWidget::updateDetails); disconnect(_job.data(), &Job::purged, this, &JobWidget::collapse); } _saveEnabled = false; _job = job; // Creating a new job? if(_job->objectKey().isEmpty()) { _ui->restoreButton->hide(); _ui->backupButton->hide(); _ui->infoLabel->hide(); _ui->jobNameLabel->hide(); _ui->jobNameLineEdit->setText(_job->name()); _ui->jobNameLineEdit->show(); _ui->jobNameLineEdit->setFocus(); } else { _ui->restoreButton->show(); _ui->backupButton->show(); _ui->jobNameLabel->show(); _ui->jobNameLineEdit->hide(); connect(_job.data(), &Job::changed, this, &JobWidget::updateDetails); connect(_job.data(), &Job::fsEvent, this, &JobWidget::fsEventReceived); connect(_job.data(), &Job::purged, this, &JobWidget::collapse); job->installWatcher(); } _ui->tabWidget->setCurrentWidget(_ui->jobTreeTab); updateDetails(); _saveEnabled = true; } void JobWidget::save() { if(_saveEnabled && !_job->name().isEmpty()) { DEBUG << "SAVE JOB"; _job->setUrls(_ui->jobTreeWidget->getSelectedUrls()); _job->removeWatcher(); _job->installWatcher(); _job->setOptionScheduledEnabled( static_cast<JobSchedule>(_ui->scheduleComboBox->currentIndex())); _job->setOptionPreservePaths(_ui->preservePathsCheckBox->isChecked()); _job->setOptionTraverseMount(_ui->traverseMountCheckBox->isChecked()); _job->setOptionFollowSymLinks(_ui->followSymLinksCheckBox->isChecked()); _job->setOptionSkipNoDump(_ui->skipNoDumpCheckBox->isChecked()); _job->setOptionSkipFilesSize(_ui->skipFilesSizeSpinBox->value()); _job->setOptionSkipFiles(_ui->skipFilesCheckBox->isChecked()); _job->setOptionSkipFilesPatterns(_ui->skipFilesLineEdit->text()); _job->setSettingShowHidden(_ui->jobTreeWidget->settingShowHidden()); _job->setSettingShowSystem(_ui->jobTreeWidget->settingShowSystem()); _job->setSettingHideSymlinks(_ui->jobTreeWidget->settingHideSymlinks()); _job->save(); verifyJob(); } } void JobWidget::saveNew() { if(!canSaveNew()) return; DEBUG << "SAVE NEW JOB"; _job->setName(_ui->jobNameLineEdit->text()); if(!_job->archives().isEmpty()) { QMessageBox::StandardButton confirm = QMessageBox::question(this, "Add job", tr("Assign %1 found archives to this Job?") .arg(_job->archives().count()), QMessageBox::Yes | QMessageBox::No, QMessageBox::No); QList<ArchivePtr> empty; if(confirm == QMessageBox::No) _job->setArchives(empty); } save(); for(const ArchivePtr &archive : _job->archives()) { archive->setJobRef(_job->objectKey()); archive->save(); } emit jobAdded(_job); } void JobWidget::updateMatchingArchives(QList<ArchivePtr> archives) { if(!archives.isEmpty()) { _ui->infoLabel->setStyleSheet(""); _ui->infoLabel->setText(tr("Found %1 unassigned archives matching this" " Job description. Go to Archives tab below" " to review.") .arg(archives.count())); _ui->infoLabel->show(); _ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf( _ui->archiveListTab), true); } else { _ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf( _ui->archiveListTab), false); } _job->setArchives(archives); _ui->archiveListWidget->setArchives(_job->archives()); _ui->tabWidget->setTabText(_ui->tabWidget->indexOf(_ui->archiveListTab), tr("Archives (%1)").arg(_job->archives().count())); } void JobWidget::changeEvent(QEvent *event) { if(event->type() == QEvent::LanguageChange) { _ui->retranslateUi(this); updateUi(); if(_job) { if(_job->objectKey().isEmpty()) canSaveNew(); else updateDetails(); } } QWidget::changeEvent(event); } void JobWidget::updateDetails() { if(!_job) return; DEBUG << "UPDATE JOB DETAILS"; _saveEnabled = false; _ui->jobNameLabel->setText(_job->name()); _ui->jobTreeWidget->setSettingShowHidden(_job->settingShowHidden()); _ui->jobTreeWidget->setSettingShowSystem(_job->settingShowSystem()); _ui->jobTreeWidget->setSettingHideSymlinks(_job->settingHideSymlinks()); _ui->jobTreeWidget->blockSignals(true); _ui->jobTreeWidget->setSelectedUrls(_job->urls()); _ui->jobTreeWidget->blockSignals(false); _ui->archiveListWidget->setArchives(_job->archives()); _ui->scheduleComboBox->setCurrentIndex( static_cast<int>(_job->optionScheduledEnabled())); _ui->preservePathsCheckBox->setChecked(_job->optionPreservePaths()); _ui->traverseMountCheckBox->setChecked(_job->optionTraverseMount()); _ui->followSymLinksCheckBox->setChecked(_job->optionFollowSymLinks()); _ui->skipNoDumpCheckBox->setChecked(_job->optionSkipNoDump()); _ui->skipFilesSizeSpinBox->setValue(_job->optionSkipFilesSize()); _ui->skipFilesCheckBox->setChecked(_job->optionSkipFiles()); _ui->skipFilesLineEdit->setText(_job->optionSkipFilesPatterns()); _ui->tabWidget->setTabEnabled(_ui->tabWidget->indexOf(_ui->archiveListTab), _job->archives().count()); _ui->tabWidget->setTabText(_ui->tabWidget->indexOf(_ui->archiveListTab), tr("Archives (%1)").arg(_job->archives().count())); verifyJob(); _saveEnabled = true; // Needed when morphing a job from the Backup tab to Jobs tab. There's // probably a better way of doing this. canSaveNew(); } void JobWidget::restoreButtonClicked() { if(_job && !_job->archives().isEmpty()) { ArchivePtr archive = _job->archives().first(); RestoreDialog *restoreDialog = new RestoreDialog(this, archive); restoreDialog->show(); connect(restoreDialog, &RestoreDialog::accepted, [=] { emit restoreJobArchive(restoreDialog->archive(), restoreDialog->getOptions()); }); } } void JobWidget::backupButtonClicked() { if(_job) emit backupJob(_job); } bool JobWidget::canSaveNew() { QString name = _ui->jobNameLineEdit->text(); _ui->infoLabel->setStyleSheet(""); _ui->infoLabel->clear(); _ui->infoLabel->hide(); if(_job->objectKey().isEmpty() && !name.isEmpty()) { JobPtr newJob(new Job); newJob->setName(name); if(!newJob->doesKeyExist(newJob->name())) { emit findMatchingArchives(newJob->archivePrefix()); if(!_ui->jobTreeWidget->getSelectedUrls().isEmpty()) { return true; } else { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText(tr("No backup paths selected.")); _ui->infoLabel->show(); } } else { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText( tr("Job name must be unique amongst existing" " Jobs.")); _ui->infoLabel->show(); } } return false; } void JobWidget::showArchiveListMenu(const QPoint &pos) { QPoint globalPos = _ui->archiveListWidget->viewport()->mapToGlobal(pos); QMenu archiveListMenu(_ui->archiveListWidget); if(!_ui->archiveListWidget->selectedItems().isEmpty()) { if(_ui->archiveListWidget->selectedItems().count() == 1) { archiveListMenu.addAction(_ui->actionInspect); archiveListMenu.addAction(_ui->actionRestore); } archiveListMenu.addAction(_ui->actionDelete); } archiveListMenu.exec(globalPos); } void JobWidget::fsEventReceived() { _fsEventUpdate.start(250); // coalesce update events with a 250ms time delay } void JobWidget::showJobPathsWarn() { if(_job->urls().isEmpty()) return; QMessageBox *msg = new QMessageBox(this); msg->setAttribute(Qt::WA_DeleteOnClose, true); msg->setText(tr("Previously selected backup paths for this Job are not" " accessible anymore and thus backups may be incomplete." " Mount missing drives or make a new selection. Press Show" " details to list all backup paths for Job %1:") .arg(_job->name())); QStringList urls; for(const QUrl &url : _job->urls()) urls << url.toLocalFile(); msg->setDetailedText(urls.join('\n')); msg->show(); } void JobWidget::verifyJob() { if(_job->objectKey().isEmpty()) return; _ui->jobTreeWidget->blockSignals(true); _ui->jobTreeWidget->setSelectedUrls(_job->urls()); _ui->jobTreeWidget->blockSignals(false); bool validUrls = _job->validateUrls(); _ui->infoLabel->setVisible(!validUrls); if(!validUrls) { if(_job->urls().isEmpty()) { _ui->infoLabel->setStyleSheet("#infoLabel { color: darkred; }"); _ui->infoLabel->setText(tr("This Job has no backup paths selected. " "Please make a selection.")); } else { _ui->infoLabel->setText( tr("Previously selected backup paths are not" " accessible. Click here for details.")); } } } void JobWidget::updateUi() { _ui->hideButton->setToolTip(_ui->hideButton->toolTip().arg( QKeySequence(Qt::Key_Escape).toString(QKeySequence::NativeText))); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rscyacc.cxx,v $ * * $Revision: 1.7 $ * * last change: $Author: hr $ $Date: 2006-06-20 05:47:10 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <stdio.h> #include <ctype.h> #include <string.h> #include <tools/rc.h> #ifndef _RSCERROR_H #include <rscerror.h> #endif #ifndef _RSCTOOLS_HXX #include <rsctools.hxx> #endif #ifndef _RSCCLASS_HXX #include <rscclass.hxx> #endif #ifndef _RSCCONT_HXX #include <rsccont.hxx> #endif #ifndef _RSCTREE_HXX #include <rsctree.hxx> #endif #ifndef _RSCDB_HXX #include <rscdb.hxx> #endif #ifndef _RSCDEF_HXX #include <rscdef.hxx> #endif #ifndef _RSCPAR_HXX #include <rscpar.hxx> #endif #include "rsclex.hxx" /************** V a r i a b l e n ****************************************/ ObjectStack S; RscTop * pCurClass; sal_uInt32 nCurMask; char szErrBuf[ 100 ]; /************** H i l f s F u n k t i o n e n ****************************/ RSCINST GetVarInst( const RSCINST & rInst, const char * pVarName ) { RSCINST aInst; aInst = rInst.pClass->GetVariable( rInst, pHS->getID( pVarName ), RSCINST() ); if( !aInst.pData ) pTC->pEH->Error( ERR_NOVARIABLENAME, rInst.pClass, RscId() ); return( aInst ); } void SetNumber( const RSCINST & rInst, const char * pVarName, INT32 lValue ) { RSCINST aInst; aInst = GetVarInst( rInst, pVarName ); if( aInst.pData ){ ERRTYPE aError; aError = aInst.pClass->SetNumber( aInst, lValue ); if( aError.IsError() ) pTC->pEH->Error( aError, aInst.pClass, RscId() ); } } void SetConst( const RSCINST & rInst, const char * pVarName, Atom nValueId, INT32 nVal ) { RSCINST aInst; aInst = GetVarInst( rInst, pVarName ); if( aInst.pData ) { ERRTYPE aError; aError = aInst.pClass->SetConst( aInst, nValueId, nVal ); if( aError.IsError() ) pTC->pEH->Error( aError, aInst.pClass, RscId() ); } } void SetString( const RSCINST & rInst, const char * pVarName, const char * pStr ) { RSCINST aInst; aInst = GetVarInst( rInst, pVarName ); if( aInst.pData ){ ERRTYPE aError; aError = aInst.pClass->SetString( aInst, pStr ); if( aError.IsError() ) pTC->pEH->Error( aError, aInst.pClass, RscId() ); } } RscId MakeRscId( RscExpType aExpType ) { if( !aExpType.IsNothing() ){ INT32 lValue; if( !aExpType.Evaluate( &lValue ) ) pTC->pEH->Error( ERR_ZERODIVISION, NULL, RscId() ); if( lValue < 1 || lValue > (INT32)0x7FFF ) { pTC->pEH->Error( ERR_IDRANGE, NULL, RscId(), ByteString::CreateFromInt32( lValue ).GetBuffer() ); } if( aExpType.IsDefinition() ) return RscId( aExpType.aExp.pDef ); else return RscId( lValue ); } return RscId(); } BOOL DoClassHeader( RSCHEADER * pHeader, BOOL bMember ) { RSCINST aCopyInst; RscId aName1 = MakeRscId( pHeader->nName1 ); RscId aName2 = MakeRscId( pHeader->nName2 ); if( pHeader->pRefClass ) aCopyInst.pClass = pHeader->pRefClass; else aCopyInst.pClass = pHeader->pClass; if( TYPE_COPY == pHeader->nTyp ) { ObjNode * pCopyObj = aCopyInst.pClass->GetObjNode( aName2 ); if( !pCopyObj ) { ByteString aMsg( pHS->getString( aCopyInst.pClass->GetId() ) ); aMsg += ' '; aMsg += aName2.GetName(); pTC->pEH->Error( ERR_NOCOPYOBJ, pHeader->pClass, aName1, aMsg.GetBuffer() ); } else aCopyInst.pData = pCopyObj->GetRscObj(); } if( bMember ) { // Angabe von Superklassen oder abgeleiteten Klassen ist jetzt erlaubt if( S.Top().pClass->InHierarchy( pHeader->pClass ) || pHeader->pClass->InHierarchy( S.Top().pClass) ) { if( aCopyInst.IsInst() ) { RSCINST aTmpI( S.Top() ); aTmpI.pClass->Destroy( aTmpI ); aTmpI.pClass->Create( &aTmpI, aCopyInst ); }; } else pTC->pEH->Error( ERR_FALSETYPE, S.Top().pClass, aName1, pHS->getString( pHeader->pClass->GetId() ) ); } else { if( S.IsEmpty() ) { if( (INT32)aName1 < 256 ) pTC->pEH->Error( WRN_GLOBALID, pHeader->pClass, aName1 ); if( aCopyInst.IsInst() ) S.Push( pHeader->pClass->Create( NULL, aCopyInst ) ); else S.Push( pHeader->pClass->Create( NULL, RSCINST() ) ); ObjNode * pNode = new ObjNode( aName1, S.Top().pData, pFI->GetFileIndex() ); pTC->pEH->StdOut( "." ); if( !aName1.IsId() ) pTC->pEH->Error( ERR_IDEXPECTED, pHeader->pClass, aName1 ); else if( !pHeader->pClass->PutObjNode( pNode ) ) pTC->pEH->Error( ERR_DOUBLEID, pHeader->pClass, aName1 ); } else { RSCINST aTmpI; ERRTYPE aError; if( (INT32)aName1 >= 256 && aName1.IsId() ) pTC->pEH->Error( WRN_LOCALID, pHeader->pClass, aName1 ); aError = S.Top().pClass->GetElement( S.Top(), aName1, pHeader->pClass, aCopyInst, &aTmpI ); if( aError.IsWarning() ) pTC->pEH->Error( aError, pHeader->pClass, aName1 ); else if( aError.IsError() ) { if( ERR_CONT_INVALIDTYPE == aError ) pTC->pEH->Error( aError, S.Top().pClass, aName1, pHS->getString( pHeader->pClass->GetId() ) ); else pTC->pEH->Error( aError, S.Top().pClass, aName1 ); S.Top().pClass->GetElement( S.Top(), RscId(), pHeader->pClass, RSCINST(), &aTmpI ); if( !aTmpI.IsInst() ) return( FALSE ); } S.Push( aTmpI ); }; }; if( TYPE_REF == pHeader->nTyp ) { ERRTYPE aError; aError = S.Top().pClass->SetRef( S.Top(), aName2 ); pTC->pEH->Error( aError, S.Top().pClass, aName1 ); } return( TRUE ); } RSCINST GetFirstTupelEle( const RSCINST & rTop ) { // Aufwaertskompatible, Tupel probieren RSCINST aInst; ERRTYPE aErr; aErr = rTop.pClass->GetElement( rTop, RscId(), NULL, RSCINST(), &aInst ); if( !aErr.IsError() ) aInst = aInst.pClass->GetTupelVar( aInst, 0, RSCINST() ); return aInst; } /************** Y a c c C o d e ****************************************/ //#define YYDEBUG 1 #define TYPE_Atom 0 #define TYPE_RESID 1 #ifdef UNX #define YYMAXDEPTH 2000 #else #ifdef W30 #define YYMAXDEPTH 300 #else #define YYMAXDEPTH 800 #endif #endif #if defined _MSC_VER #pragma warning(push, 1) #pragma warning(disable:4129 4701) #endif #include "yyrscyacc.cxx" #if defined _MSC_VER #pragma warning(pop) #endif <commit_msg>INTEGRATION: CWS warningfixes02 (1.7.8); FILE MERGED 2006/07/03 06:44:08 sb 1.7.8.1: #i66723# Disable MSC warning 4273 (bison problem?).<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: rscyacc.cxx,v $ * * $Revision: 1.8 $ * * last change: $Author: kz $ $Date: 2006-07-19 17:14:17 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #include <stdio.h> #include <ctype.h> #include <string.h> #include <tools/rc.h> #ifndef _RSCERROR_H #include <rscerror.h> #endif #ifndef _RSCTOOLS_HXX #include <rsctools.hxx> #endif #ifndef _RSCCLASS_HXX #include <rscclass.hxx> #endif #ifndef _RSCCONT_HXX #include <rsccont.hxx> #endif #ifndef _RSCTREE_HXX #include <rsctree.hxx> #endif #ifndef _RSCDB_HXX #include <rscdb.hxx> #endif #ifndef _RSCDEF_HXX #include <rscdef.hxx> #endif #ifndef _RSCPAR_HXX #include <rscpar.hxx> #endif #include "rsclex.hxx" /************** V a r i a b l e n ****************************************/ ObjectStack S; RscTop * pCurClass; sal_uInt32 nCurMask; char szErrBuf[ 100 ]; /************** H i l f s F u n k t i o n e n ****************************/ RSCINST GetVarInst( const RSCINST & rInst, const char * pVarName ) { RSCINST aInst; aInst = rInst.pClass->GetVariable( rInst, pHS->getID( pVarName ), RSCINST() ); if( !aInst.pData ) pTC->pEH->Error( ERR_NOVARIABLENAME, rInst.pClass, RscId() ); return( aInst ); } void SetNumber( const RSCINST & rInst, const char * pVarName, INT32 lValue ) { RSCINST aInst; aInst = GetVarInst( rInst, pVarName ); if( aInst.pData ){ ERRTYPE aError; aError = aInst.pClass->SetNumber( aInst, lValue ); if( aError.IsError() ) pTC->pEH->Error( aError, aInst.pClass, RscId() ); } } void SetConst( const RSCINST & rInst, const char * pVarName, Atom nValueId, INT32 nVal ) { RSCINST aInst; aInst = GetVarInst( rInst, pVarName ); if( aInst.pData ) { ERRTYPE aError; aError = aInst.pClass->SetConst( aInst, nValueId, nVal ); if( aError.IsError() ) pTC->pEH->Error( aError, aInst.pClass, RscId() ); } } void SetString( const RSCINST & rInst, const char * pVarName, const char * pStr ) { RSCINST aInst; aInst = GetVarInst( rInst, pVarName ); if( aInst.pData ){ ERRTYPE aError; aError = aInst.pClass->SetString( aInst, pStr ); if( aError.IsError() ) pTC->pEH->Error( aError, aInst.pClass, RscId() ); } } RscId MakeRscId( RscExpType aExpType ) { if( !aExpType.IsNothing() ){ INT32 lValue; if( !aExpType.Evaluate( &lValue ) ) pTC->pEH->Error( ERR_ZERODIVISION, NULL, RscId() ); if( lValue < 1 || lValue > (INT32)0x7FFF ) { pTC->pEH->Error( ERR_IDRANGE, NULL, RscId(), ByteString::CreateFromInt32( lValue ).GetBuffer() ); } if( aExpType.IsDefinition() ) return RscId( aExpType.aExp.pDef ); else return RscId( lValue ); } return RscId(); } BOOL DoClassHeader( RSCHEADER * pHeader, BOOL bMember ) { RSCINST aCopyInst; RscId aName1 = MakeRscId( pHeader->nName1 ); RscId aName2 = MakeRscId( pHeader->nName2 ); if( pHeader->pRefClass ) aCopyInst.pClass = pHeader->pRefClass; else aCopyInst.pClass = pHeader->pClass; if( TYPE_COPY == pHeader->nTyp ) { ObjNode * pCopyObj = aCopyInst.pClass->GetObjNode( aName2 ); if( !pCopyObj ) { ByteString aMsg( pHS->getString( aCopyInst.pClass->GetId() ) ); aMsg += ' '; aMsg += aName2.GetName(); pTC->pEH->Error( ERR_NOCOPYOBJ, pHeader->pClass, aName1, aMsg.GetBuffer() ); } else aCopyInst.pData = pCopyObj->GetRscObj(); } if( bMember ) { // Angabe von Superklassen oder abgeleiteten Klassen ist jetzt erlaubt if( S.Top().pClass->InHierarchy( pHeader->pClass ) || pHeader->pClass->InHierarchy( S.Top().pClass) ) { if( aCopyInst.IsInst() ) { RSCINST aTmpI( S.Top() ); aTmpI.pClass->Destroy( aTmpI ); aTmpI.pClass->Create( &aTmpI, aCopyInst ); }; } else pTC->pEH->Error( ERR_FALSETYPE, S.Top().pClass, aName1, pHS->getString( pHeader->pClass->GetId() ) ); } else { if( S.IsEmpty() ) { if( (INT32)aName1 < 256 ) pTC->pEH->Error( WRN_GLOBALID, pHeader->pClass, aName1 ); if( aCopyInst.IsInst() ) S.Push( pHeader->pClass->Create( NULL, aCopyInst ) ); else S.Push( pHeader->pClass->Create( NULL, RSCINST() ) ); ObjNode * pNode = new ObjNode( aName1, S.Top().pData, pFI->GetFileIndex() ); pTC->pEH->StdOut( "." ); if( !aName1.IsId() ) pTC->pEH->Error( ERR_IDEXPECTED, pHeader->pClass, aName1 ); else if( !pHeader->pClass->PutObjNode( pNode ) ) pTC->pEH->Error( ERR_DOUBLEID, pHeader->pClass, aName1 ); } else { RSCINST aTmpI; ERRTYPE aError; if( (INT32)aName1 >= 256 && aName1.IsId() ) pTC->pEH->Error( WRN_LOCALID, pHeader->pClass, aName1 ); aError = S.Top().pClass->GetElement( S.Top(), aName1, pHeader->pClass, aCopyInst, &aTmpI ); if( aError.IsWarning() ) pTC->pEH->Error( aError, pHeader->pClass, aName1 ); else if( aError.IsError() ) { if( ERR_CONT_INVALIDTYPE == aError ) pTC->pEH->Error( aError, S.Top().pClass, aName1, pHS->getString( pHeader->pClass->GetId() ) ); else pTC->pEH->Error( aError, S.Top().pClass, aName1 ); S.Top().pClass->GetElement( S.Top(), RscId(), pHeader->pClass, RSCINST(), &aTmpI ); if( !aTmpI.IsInst() ) return( FALSE ); } S.Push( aTmpI ); }; }; if( TYPE_REF == pHeader->nTyp ) { ERRTYPE aError; aError = S.Top().pClass->SetRef( S.Top(), aName2 ); pTC->pEH->Error( aError, S.Top().pClass, aName1 ); } return( TRUE ); } RSCINST GetFirstTupelEle( const RSCINST & rTop ) { // Aufwaertskompatible, Tupel probieren RSCINST aInst; ERRTYPE aErr; aErr = rTop.pClass->GetElement( rTop, RscId(), NULL, RSCINST(), &aInst ); if( !aErr.IsError() ) aInst = aInst.pClass->GetTupelVar( aInst, 0, RSCINST() ); return aInst; } /************** Y a c c C o d e ****************************************/ //#define YYDEBUG 1 #define TYPE_Atom 0 #define TYPE_RESID 1 #ifdef UNX #define YYMAXDEPTH 2000 #else #ifdef W30 #define YYMAXDEPTH 300 #else #define YYMAXDEPTH 800 #endif #endif #if defined _MSC_VER #pragma warning(push, 1) #pragma warning(disable:4129 4273 4701) #endif #include "yyrscyacc.cxx" #if defined _MSC_VER #pragma warning(pop) #endif <|endoftext|>
<commit_before>/********************************************************************** Copyright (c) 2016 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 "intersector_lds.h" #include "calc.h" #include "executable.h" #include "../accelerator/bvh2.h" #include "../primitive/mesh.h" #include "../primitive/instance.h" #include "../translator/q_bvh_translator.h" #include "../world/world.h" namespace RadeonRays { struct IntersectorLDS::GpuData { // Device Calc::Device *device; // BVH nodes Calc::Buffer *bvh; Calc::Executable *executable; Calc::Function *isect_func; Calc::Function *occlude_func; GpuData(Calc::Device *device) : device(device) , bvh(nullptr) , executable(nullptr) , isect_func(nullptr) , occlude_func(nullptr) { } ~GpuData() { device->DeleteBuffer(bvh); executable->DeleteFunction(isect_func); executable->DeleteFunction(occlude_func); device->DeleteExecutable(executable); } }; IntersectorLDS::IntersectorLDS(Calc::Device *device) : Intersector(device) , m_gpuData(new GpuData(device)) , m_bvh(nullptr) { std::string buildopts; #ifdef RR_RAY_MASK buildopts.append("-D RR_RAY_MASK "); // TODO: what is this for?!? (gboisse) #endif #ifdef USE_SAFE_MATH buildopts.append("-D USE_SAFE_MATH "); #endif #ifndef RR_EMBED_KERNELS // TODO: add implementation (gboisse) #else #if USE_OPENCL if (device->GetPlatform() == Calc::Platform::kOpenCL) { m_gpuData->executable = m_device->CompileExecutable(g_intersect_bvh2_lds_opencl, std::strlen(g_intersect_bvh2_lds_opencl), buildopts.c_str()); } #endif #if USE_VULKAN if (m_gpudata->executable == nullptr && device->GetPlatform() == Calc::Platform::kVulkan) { // TODO: implement (gboisse) m_gpuData->executable = m_device->CompileExecutable(g_bvh2_vulkan, std::strlen(g_bvh2_vulkan), buildopts.c_str()); } #endif #endif m_gpuData->isect_func = m_gpuData->executable->CreateFunction("intersect_main"); m_gpuData->occlude_func = m_gpuData->executable->CreateFunction("occluded_main"); } void IntersectorLDS::Process(const World &world) { // If something has been changed we need to rebuild BVH if (!m_bvh || world.has_changed() || world.GetStateChange() != ShapeImpl::kStateChangeNone) { // Free previous data if (m_bvh) { m_device->DeleteBuffer(m_gpuData->bvh); //m_device->DeleteBuffer(m_gpuData->vertices); } // Look up build options for world auto builder = world.options_.GetOption("bvh.builder"); auto nbins = world.options_.GetOption("bvh.sah.num_bins"); auto tcost = world.options_.GetOption("bvh.sah.traversal_cost"); bool use_sah = false; int num_bins = (nbins ? static_cast<int>(nbins->AsFloat()) : 64); float traversal_cost = (tcost ? tcost->AsFloat() : 10.0f); if (builder && builder->AsString() == "sah") { use_sah = true; } // Create the bvh m_bvh.reset(new Bvh2(traversal_cost, num_bins, use_sah)); // Partition the array into meshes and instances std::vector<const Shape *> shapes(world.shapes_); auto firstinst = std::partition(shapes.begin(), shapes.end(), [&](Shape const* shape) { return !static_cast<ShapeImpl const*>(shape)->is_instance(); }); // TODO: deal with the instance stuff (gboisse) m_bvh->Build(shapes.begin(), firstinst); // TODO: what if we don't want to use fp16? (gboisse) QBvhTranslator translator; translator.Process(*m_bvh); // Update GPU data auto bvh_size_in_bytes = translator.GetSizeInBytes(); m_gpuData->bvh = m_device->CreateBuffer(bvh_size_in_bytes, Calc::BufferType::kRead); // Get the pointer to mapped data Calc::Event *e = nullptr; QBvhTranslator::Node *bvhdata = nullptr; m_device->MapBuffer(m_gpuData->bvh, 0, 0, bvh_size_in_bytes, Calc::MapType::kMapWrite, (void **)&bvhdata, &e); e->Wait(); m_device->DeleteEvent(e); // } } void IntersectorLDS::Intersect(std::uint32_t queue_idx, const Calc::Buffer *rays, const Calc::Buffer *num_rays, std::uint32_t max_rays, Calc::Buffer *hits, const Calc::Event *wait_event, Calc::Event **event) const { // } void IntersectorLDS::Occluded(std::uint32_t queue_idx, const Calc::Buffer *rays, const Calc::Buffer *num_rays, std::uint32_t max_rays, Calc::Buffer *hits, const Calc::Event *wait_event, Calc::Event **event) const { // } } <commit_msg>Copying BVH data to GPU memory<commit_after>/********************************************************************** Copyright (c) 2016 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 "intersector_lds.h" #include "calc.h" #include "executable.h" #include "../accelerator/bvh2.h" #include "../primitive/mesh.h" #include "../primitive/instance.h" #include "../translator/q_bvh_translator.h" #include "../world/world.h" namespace RadeonRays { struct IntersectorLDS::GpuData { // Device Calc::Device *device; // BVH nodes Calc::Buffer *bvh; Calc::Executable *executable; Calc::Function *isect_func; Calc::Function *occlude_func; GpuData(Calc::Device *device) : device(device) , bvh(nullptr) , executable(nullptr) , isect_func(nullptr) , occlude_func(nullptr) { } ~GpuData() { device->DeleteBuffer(bvh); executable->DeleteFunction(isect_func); executable->DeleteFunction(occlude_func); device->DeleteExecutable(executable); } }; IntersectorLDS::IntersectorLDS(Calc::Device *device) : Intersector(device) , m_gpuData(new GpuData(device)) , m_bvh(nullptr) { std::string buildopts; #ifdef RR_RAY_MASK buildopts.append("-D RR_RAY_MASK "); // TODO: what is this for?!? (gboisse) #endif #ifdef USE_SAFE_MATH buildopts.append("-D USE_SAFE_MATH "); #endif #ifndef RR_EMBED_KERNELS // TODO: add implementation (gboisse) #else #if USE_OPENCL if (device->GetPlatform() == Calc::Platform::kOpenCL) { m_gpuData->executable = m_device->CompileExecutable(g_intersect_bvh2_lds_opencl, std::strlen(g_intersect_bvh2_lds_opencl), buildopts.c_str()); } #endif #if USE_VULKAN if (m_gpudata->executable == nullptr && device->GetPlatform() == Calc::Platform::kVulkan) { // TODO: implement (gboisse) m_gpuData->executable = m_device->CompileExecutable(g_bvh2_vulkan, std::strlen(g_bvh2_vulkan), buildopts.c_str()); } #endif #endif m_gpuData->isect_func = m_gpuData->executable->CreateFunction("intersect_main"); m_gpuData->occlude_func = m_gpuData->executable->CreateFunction("occluded_main"); } void IntersectorLDS::Process(const World &world) { // If something has been changed we need to rebuild BVH if (!m_bvh || world.has_changed() || world.GetStateChange() != ShapeImpl::kStateChangeNone) { // Free previous data if (m_bvh) { m_device->DeleteBuffer(m_gpuData->bvh); //m_device->DeleteBuffer(m_gpuData->vertices); } // Look up build options for world auto builder = world.options_.GetOption("bvh.builder"); auto nbins = world.options_.GetOption("bvh.sah.num_bins"); auto tcost = world.options_.GetOption("bvh.sah.traversal_cost"); bool use_sah = false; int num_bins = (nbins ? static_cast<int>(nbins->AsFloat()) : 64); float traversal_cost = (tcost ? tcost->AsFloat() : 10.0f); if (builder && builder->AsString() == "sah") { use_sah = true; } // Create the bvh m_bvh.reset(new Bvh2(traversal_cost, num_bins, use_sah)); // Partition the array into meshes and instances std::vector<const Shape *> shapes(world.shapes_); auto firstinst = std::partition(shapes.begin(), shapes.end(), [&](Shape const* shape) { return !static_cast<ShapeImpl const*>(shape)->is_instance(); }); // TODO: deal with the instance stuff (gboisse) m_bvh->Build(shapes.begin(), firstinst); // TODO: what if we don't want to use fp16? (gboisse) QBvhTranslator translator; translator.Process(*m_bvh); // Update GPU data auto bvh_size_in_bytes = translator.GetSizeInBytes(); m_gpuData->bvh = m_device->CreateBuffer(bvh_size_in_bytes, Calc::BufferType::kRead); // Get the pointer to mapped data Calc::Event *e = nullptr; QBvhTranslator::Node *bvhdata = nullptr; m_device->MapBuffer(m_gpuData->bvh, 0, 0, bvh_size_in_bytes, Calc::MapType::kMapWrite, (void **)&bvhdata, &e); e->Wait(); m_device->DeleteEvent(e); // Copy BVH data std::size_t i = 0; for (auto it = translator.nodes_.begin(); it != translator.nodes_.end(); ++it) bvhdata[i++] = *it; // Unmap gpu data m_device->UnmapBuffer(m_gpuData->bvh, 0, bvhdata, &e); e->Wait(); m_device->DeleteEvent(e); } } void IntersectorLDS::Intersect(std::uint32_t queue_idx, const Calc::Buffer *rays, const Calc::Buffer *num_rays, std::uint32_t max_rays, Calc::Buffer *hits, const Calc::Event *wait_event, Calc::Event **event) const { // } void IntersectorLDS::Occluded(std::uint32_t queue_idx, const Calc::Buffer *rays, const Calc::Buffer *num_rays, std::uint32_t max_rays, Calc::Buffer *hits, const Calc::Event *wait_event, Calc::Event **event) const { // } } <|endoftext|>
<commit_before>/*-------------ConjGrad.cpp---------------------------------------------------// * * Conjugate Gradient Method * * Purpose: This file intends to solve a simple linear algebra equation: * Ax = b * Where A is a square matrix of dimension N and x, b are vectors * of length N. * * Notes: We can write this entire code without std:: vector. Think about it * Need to make sure we are indexing arrays appropriately. * Think about using LAPACK / BLAS * matmag is not for matrices yet. Fix that. * ConjGrad function not working or tested yet. * *-----------------------------------------------------------------------------*/ #include <iostream> #include <vector> #include <memory> #include <cassert> #include <cmath> // Struct to hold 2d array struct array2D{ // initial pointers to array std::unique_ptr<double[]> data; size_t rows, columns; // defines our interface with array creation and creates struct memebers array2D(size_t n, size_t m) : data(new double[(n)*(m)]), rows(n), columns(m) { for(size_t i = 0; i < n*m; i++){ data[i] = 0; } } // These are interfaces for array calls. Basically setting the row length. double operator() (size_t row, size_t col) const { return data[row * columns + col]; } double& operator() (size_t row, size_t col) { return data[row * columns + col]; } }; // Smaller function for Matrix multiply array2D matmul(const array2D &A, const array2D &B); // Function for addition array2D matadd(const array2D &A, const array2D &B); array2D matdiff(const array2D &A, const array2D &B); // Function for scaling array2D matscale(const array2D &A, double scale); // Function for finding the magnitude of a vector... Note not array yet. double matmag(const array2D &A); // Function for Conj Gradient -- All the big stuff happens here void conjgrad(const array2D &A, const array2D &b, array2D &x_0, double thresh); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(){ array2D a(2,2), b(2,1); a(0,0) = 4; a(1,0) = 1; a(0,1) = 1; a(1,1) = 3; b(0,0) = 2; b(0,1) = 1; array2D c = matmul(a, b); for (size_t i = 0; i < c.rows; i++){ for (size_t j = 0; j < c.columns; j++){ std::cout << c(i,j) << '\t'; } std::cout << '\n'; } } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // Smaller function for Matrix multiply array2D matmul(const array2D &A, const array2D &B){ if (A.columns != B.rows){ std::cout << "Incorrect inner dimensions for multiplication." << '\n'; assert(A.columns == B.rows); } // Check to make sure we are creating C with an appropriate size array2D C(A.rows, B.columns); for (size_t i = 0; i < C.rows; i++){ for (size_t j = 0; j < C.columns; j++){ for (size_t k = 0; k < A.columns; k++){ C(i, j) += A(i, k) * B(k, j); } } } return C; } // Function for Conj Gradient -- All the big stuff happens here void conjgrad(const array2D &A, const array2D &b, array2D &x_0, double thresh){ // Not working. Messily break if someone tries to use it. std::cout << "Not working" << '\n'; assert(thresh < 0); array2D r(x_0.rows, x_0.columns), p(x_0.rows,x_0.columns); double alpha, diff; // definingin first r array2D r_0 = matdiff(b, matmul(A,x_0)); // setting x arbitrarily high to start array2D x = matscale(x_0, 4); // *grumble... gustorn... grumble* array2D p_0 = matscale(r_0,1); /* while (diff > thresh){ } */ } // Function for scaling array2D matadd(const array2D &A, const array2D &B){ if (A.rows != B.rows || A.columns != B.columns){ std::cout << "incorrect dimensions with addition" << '\n'; assert(A.rows == B.rows || A.columns == B.columns); } array2D C(A.rows, B.columns); for (size_t i = 0; i < C.rows; i++){ for (size_t j = 0; j < C.columns; j++){ C(i, j) = A(i, j) + B(i, j); } } return C; } // Function for scaling array2D matdiff(const array2D &A, const array2D &B){ if (A.rows != B.rows || A.columns != B.columns){ std::cout << "incorrect dimensions with addition" << '\n'; assert(A.rows == B.rows || A.columns == B.columns); } array2D C(A.rows, B.columns); for (size_t i = 0; i < C.rows; i++){ for (size_t j = 0; j < C.columns; j++){ C(i, j) = A(i, j) - B(i, j); } } return C; } // Function for scaling array2D matscale(const array2D &A, double scale){ array2D C(A.rows, A.columns); for (size_t i = 0; i < C.rows; i++){ for (size_t j = 0; j < C.columns; j++){ C(i, j) = A(i, j) * scale; } } return C; } // Function for finding magnitude for a single columned array // Note: We should probably set this function to work for all types of matrices double matmag(const array2D &A){ double mag = 0; if (A.columns > 1){ std::cout << "Not implemented yet for larger than 1 column." << '\n'; assert(A.columns < 1); } for (size_t i = 0; i < A.rows; i++){ mag += A(i,0)*A(i,0); } mag = sqrt(mag); return mag; } <commit_msg>Seems to be working for wikipedia example.<commit_after>/*-------------ConjGrad.cpp---------------------------------------------------// * * Conjugate Gradient Method * * Purpose: This file intends to solve a simple linear algebra equation: * Ax = b * Where A is a square matrix of dimension N and x, b are vectors * of length N. * * Notes: We can write this entire code without std:: vector. Think about it * Need to make sure we are indexing arrays appropriately. * Think about using LAPACK / BLAS * matmag is not for matrices yet. Fix that. * ConjGrad function not working or tested yet. * *-----------------------------------------------------------------------------*/ #include <iostream> #include <vector> #include <memory> #include <cassert> #include <cmath> // Struct to hold 2d array struct array2D{ // initial pointers to array std::unique_ptr<double[]> data; size_t rows, columns; // defines our interface with array creation and creates struct memebers array2D(size_t n, size_t m) : data(new double[(n)*(m)]), rows(n), columns(m) { for(size_t i = 0; i < n*m; i++){ data[i] = 0; } } // These are interfaces for array calls. Basically setting the row length. double operator() (size_t row, size_t col) const { return data[row * columns + col]; } double& operator() (size_t row, size_t col) { return data[row * columns + col]; } }; // Smaller function for Matrix multiply array2D matmul(const array2D &A, const array2D &B); // Function for addition array2D matadd(const array2D &A, const array2D &B); array2D matdiff(const array2D &A, const array2D &B); // Function for scaling array2D matscale(const array2D &A, double scale); // Function for finding the magnitude of a vector... Note not array yet. double magnitude(const array2D &A); // Function for finding the transpose array2D transpose(const array2D &A); // For bpaf because he said I was lazy void matprint(const array2D &A); // Function for Conj Gradient -- All the big stuff happens here void conjgrad(const array2D &A, const array2D &b, array2D &x_0, double thresh); /*----------------------------------------------------------------------------// * MAIN *-----------------------------------------------------------------------------*/ int main(){ double thresh = 0.001; array2D a(2,2), b(2,1), x(2,1); a(0,0) = 4; a(1,0) = 1; a(0,1) = 1; a(1,1) = 3; x(0,0) = 2; x(0,1) = 1; b(0,0) = 1; b(0,1) = 2; array2D c = matmul(a, x); std::cout << "Simple matrix multiplication check:" << '\n'; matprint(c); std::cout << '\n'; conjgrad(a, b, x, thresh); std::cout << "Conjugate Gradient output with threshold " << thresh << '\n'; matprint(x); } /*----------------------------------------------------------------------------// * SUBROUTINES *-----------------------------------------------------------------------------*/ // Smaller function for Matrix multiply array2D matmul(const array2D &A, const array2D &B){ if (A.columns != B.rows){ std::cout << "Incorrect inner dimensions for multiplication." << '\n'; assert(A.columns == B.rows); } // Check to make sure we are creating C with an appropriate size array2D C(A.rows, B.columns); for (size_t i = 0; i < C.rows; i++){ for (size_t j = 0; j < C.columns; j++){ for (size_t k = 0; k < A.columns; k++){ C(i, j) += A(i, k) * B(k, j); } } } return C; } // Function for scaling array2D matadd(const array2D &A, const array2D &B){ if (A.rows != B.rows || A.columns != B.columns){ std::cout << "incorrect dimensions with addition" << '\n'; assert(A.rows == B.rows || A.columns == B.columns); } array2D C(A.rows, B.columns); for (size_t i = 0; i < C.rows; i++){ for (size_t j = 0; j < C.columns; j++){ C(i, j) = A(i, j) + B(i, j); } } return C; } // Function for scaling array2D matdiff(const array2D &A, const array2D &B){ if (A.rows != B.rows || A.columns != B.columns){ std::cout << "incorrect dimensions with difference" << '\n'; assert(A.rows == B.rows || A.columns == B.columns); } array2D C(A.rows, B.columns); for (size_t i = 0; i < C.rows; i++){ for (size_t j = 0; j < C.columns; j++){ C(i, j) = A(i, j) - B(i, j); } } return C; } // Function for scaling array2D matscale(const array2D &A, double scale){ array2D C(A.rows, A.columns); for (size_t i = 0; i < C.rows; i++){ for (size_t j = 0; j < C.columns; j++){ C(i, j) = A(i, j) * scale; } } return C; } // Function for finding magnitude for a single columned array // Note: We should probably set this function to work for all types of matrices double magnitude(const array2D &A){ double mag = 0; if (A.columns > 1){ std::cout << "Not implemented yet for larger than 1 column." << '\n'; assert(A.columns < 1); } for (size_t i = 0; i < A.rows; i++){ mag += A(i,0)*A(i,0); } mag = sqrt(mag); return mag; } // Function for finding the transpose array2D transpose(const array2D &A){ array2D C(A.columns, A.rows); for (size_t i = 0; i < A.rows; i++){ for (size_t j = 0; j < A.columns; j++){ C(j, i) = A(i, j); } } return C; } void matprint(const array2D &A){ for (size_t i = 0; i < A.rows; i++){ for (size_t j = 0; j < A.columns; j++){ std::cout << A(i,j) << '\t'; } std::cout << '\n'; } } // Function for Conj Gradient -- All the big stuff happens here void conjgrad(const array2D &A, const array2D &b, array2D &x_0, double thresh){ array2D r(x_0.rows, x_0.columns), p(x_0.rows,x_0.columns), temp1(1,1), temp2(1,1); double alpha, diff, beta; // definingin first r array2D r_0 = matdiff(b, matmul(A,x_0)); // setting x arbitrarily high to start array2D x = matscale(x_0, 4); // *grumble... gustorn... grumble* array2D p_0 = matscale(r_0,1); diff = magnitude(matdiff(x, x_0)); while (diff > thresh){ // Note, matmul will output a array2D with one element. temp1 = matmul(transpose(r_0), r_0); temp2 = matmul(transpose(p_0), matmul(A, p_0)); alpha = temp1(0,0) / temp2(0,0); x = matadd(x_0, matscale(p_0,alpha)); r = matadd(r_0, matmul(matscale(A,-alpha),p_0)); temp1 = matmul(transpose(r),r); temp2 = matmul(transpose(r_0),r_0); p = matadd(r, matscale(p_0,beta)); diff = magnitude(matdiff(x, x_0)); // set all the values to naughts x_0 = matscale(x,1); r_0 = matscale(r,1); p_0 = matscale(p,1); } } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: unomodel.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: rt $ $Date: 2005-04-04 08:03:43 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef UNOMODEL_HXX #define UNOMODEL_HXX #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSET_HPP_ #include <com/sun/star/beans/XMultiPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_ #include <com/sun/star/beans/XPropertyState.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_VIEW_XRENDERABLE_HPP_ #include <com/sun/star/view/XRenderable.hpp> #endif #ifndef _SFX_SFXBASEMODEL_HXX_ #include <sfx2/sfxbasemodel.hxx> #endif #ifndef _COMPHELPER_PROPERTYSETHELPER_HXX_ #include <comphelper/propertysethelper.hxx> #endif class SmFormat; //----------------------------------------------------------------------------- class SmModel : public SfxBaseModel, public comphelper::PropertySetHelper, public com::sun::star::lang::XServiceInfo, public com::sun::star::view::XRenderable { protected: virtual void _setPropertyValues( const comphelper::PropertyMapEntry** ppEntries, const ::com::sun::star::uno::Any* pValues ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException ); virtual void _getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, ::com::sun::star::uno::Any* pValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException ); public: SmModel( SfxObjectShell *pObjSh = 0 ); virtual ~SmModel() throw (); //XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( ) throw(); virtual void SAL_CALL release( ) throw(); //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId(); //XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException); //XRenderable virtual sal_Int32 SAL_CALL getRendererCount( const ::com::sun::star::uno::Any& rSelection, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rxOptions ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getRenderer( sal_Int32 nRenderer, const ::com::sun::star::uno::Any& rSelection, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rxOptions ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL render( sal_Int32 nRenderer, const ::com::sun::star::uno::Any& rSelection, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rxOptions ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); //XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName(void) throw( ::com::sun::star::uno::RuntimeException ); virtual BOOL SAL_CALL supportsService(const rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames(void) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setParent( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xParent ) throw( ::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException ); static ::com::sun::star::uno::Sequence< rtl::OUString > getSupportedServiceNames_Static(); static ::rtl::OUString getImplementationName_Static(); }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.11.64); FILE MERGED 2005/09/05 17:37:24 rt 1.11.64.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: unomodel.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: rt $ $Date: 2005-09-07 15:01:21 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef UNOMODEL_HXX #define UNOMODEL_HXX #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSET_HPP_ #include <com/sun/star/beans/XPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XMULTIPROPERTYSET_HPP_ #include <com/sun/star/beans/XMultiPropertySet.hpp> #endif #ifndef _COM_SUN_STAR_BEANS_XPROPERTYSTATE_HPP_ #include <com/sun/star/beans/XPropertyState.hpp> #endif #ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_ #include <com/sun/star/lang/XServiceInfo.hpp> #endif #ifndef _COM_SUN_STAR_VIEW_XRENDERABLE_HPP_ #include <com/sun/star/view/XRenderable.hpp> #endif #ifndef _SFX_SFXBASEMODEL_HXX_ #include <sfx2/sfxbasemodel.hxx> #endif #ifndef _COMPHELPER_PROPERTYSETHELPER_HXX_ #include <comphelper/propertysethelper.hxx> #endif class SmFormat; //----------------------------------------------------------------------------- class SmModel : public SfxBaseModel, public comphelper::PropertySetHelper, public com::sun::star::lang::XServiceInfo, public com::sun::star::view::XRenderable { protected: virtual void _setPropertyValues( const comphelper::PropertyMapEntry** ppEntries, const ::com::sun::star::uno::Any* pValues ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::beans::PropertyVetoException, ::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::lang::WrappedTargetException ); virtual void _getPropertyValues( const comphelper::PropertyMapEntry** ppEntries, ::com::sun::star::uno::Any* pValue ) throw(::com::sun::star::beans::UnknownPropertyException, ::com::sun::star::lang::WrappedTargetException ); public: SmModel( SfxObjectShell *pObjSh = 0 ); virtual ~SmModel() throw (); //XInterface virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type& aType ) throw(::com::sun::star::uno::RuntimeException); virtual void SAL_CALL acquire( ) throw(); virtual void SAL_CALL release( ) throw(); //XTypeProvider virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes( ) throw(::com::sun::star::uno::RuntimeException); static const ::com::sun::star::uno::Sequence< sal_Int8 > & getUnoTunnelId(); //XUnoTunnel virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& aIdentifier ) throw(::com::sun::star::uno::RuntimeException); //XRenderable virtual sal_Int32 SAL_CALL getRendererCount( const ::com::sun::star::uno::Any& rSelection, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rxOptions ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue > SAL_CALL getRenderer( sal_Int32 nRenderer, const ::com::sun::star::uno::Any& rSelection, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rxOptions ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); virtual void SAL_CALL render( sal_Int32 nRenderer, const ::com::sun::star::uno::Any& rSelection, const ::com::sun::star::uno::Sequence< ::com::sun::star::beans::PropertyValue >& rxOptions ) throw (::com::sun::star::lang::IllegalArgumentException, ::com::sun::star::uno::RuntimeException); //XServiceInfo virtual rtl::OUString SAL_CALL getImplementationName(void) throw( ::com::sun::star::uno::RuntimeException ); virtual BOOL SAL_CALL supportsService(const rtl::OUString& ServiceName) throw( ::com::sun::star::uno::RuntimeException ); virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames(void) throw( ::com::sun::star::uno::RuntimeException ); virtual void SAL_CALL setParent( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& xParent ) throw( ::com::sun::star::lang::NoSupportException, ::com::sun::star::uno::RuntimeException ); static ::com::sun::star::uno::Sequence< rtl::OUString > getSupportedServiceNames_Static(); static ::rtl::OUString getImplementationName_Static(); }; #endif <|endoftext|>
<commit_before>/* * This file is part of TelepathyQt4Logger * * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/> * * 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "tpl-tool.h" #include <tools/_gen/tpl-tool.moc.hpp> #include <TelepathyQt4Logger/utils.h> #include <QApplication> #include <TelepathyQt4/Account> #include <TelepathyQt4/AccountSet> #include <TelepathyQt4/AccountManager> #include <TelepathyQt4/ContactManager> #include <TelepathyQt4/Connection> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4Logger/Entity> #include <TelepathyQt4Logger/Event> #include <TelepathyQt4Logger/TextEvent> #include <TelepathyQt4Logger/LogManager> #include <TelepathyQt4Logger/PendingDates> #include <TelepathyQt4Logger/PendingEntities> #include <TelepathyQt4Logger/PendingEvents> #include <TelepathyQt4Logger/PendingSearch> #include <TelepathyQt4Logger/Init> #include <glib-object.h> #include <QGst/Init> #include <QDebug> TplToolApplication::TplToolApplication(int &argc, char **argv) : QCoreApplication(argc, argv) { debugfn(); mAccountManager = Tp::AccountManager::create(); connect(mAccountManager->becomeReady(Tp::AccountManager::FeatureCore), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onAccountManagerReady(Tp::PendingOperation*))); } Tp::AccountPtr TplToolApplication::accountPtr(const QString &id) { debugfn(); mAccountPtr = Tpl::Utils::instance()->accountPtr(id.toAscii()); if (!mAccountPtr->isValid()) { return mAccountPtr; } connect(mAccountPtr->becomeReady(Tp::Features() << Tp::Account::FeatureCore << Tp::Account::FeatureAvatar), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onAccountReady(Tp::PendingOperation*))); return mAccountPtr; } Tpl::EntityPtr TplToolApplication::entityPtr(const QString &id) { debugfn(); return Tpl::Entity::create(id.toAscii(), Tpl::EntityTypeContact, NULL, NULL); } bool TplToolApplication::parseArgs1() { debugfn(); QStringList args = arguments(); Tpl::LogManagerPtr logManager = Tpl::LogManager::instance(); if (logManager.isNull()) { qWarning() << "LogManager not found"; return false; } if (args.size() == 2 && args.at(1) == "accounts") { Tp::AccountSetPtr accountSet = Tpl::Utils::instance()->accountManagerPtr()->validAccounts(); QList<Tp::AccountPtr> accounts = accountSet->accounts(); Tp::AccountPtr account; int i = 0; Q_FOREACH(account, accounts) { qDebug() << "account " << i++ << account->objectPath(); } this->exit(); return true; } else if ((args.size() == 3 && args.at(1) == "contacts") || (args.size() == 4 && args.at(1) == "exists") || (args.size() == 3 && args.at(1) == "entities") || (args.size() == 4 && args.at(1) == "dates") || (args.size() == 5 && args.at(1) == "events") || (args.size() == 5 && args.at(1) == "filteredEvents")) { Tp::AccountPtr account = accountPtr(args.at(2).toAscii()); if (account.isNull()) { qWarning() << "Account not found " << args.at(2); } return true; } else if (args.size() == 3 && args.at(1) == "search") { Tpl::PendingSearch *ps = logManager->search(args.at(2), Tpl::EventTypeMaskAny); debugfn() << "PendingSearch=" << ps; if (!ps) { qWarning() << "Error in search"; this->exit(-1); return false; } connect(ps, SIGNAL(finished(Tpl::PendingOperation*)), this, SLOT(onPendingSearch(Tpl::PendingOperation*))); ps->start(); return true; } qDebug() << "Telepathy logger command line tool (qt4)"; qDebug() << ""; qDebug() << "General usage: tpl-tool <command> <parameters>"; qDebug() << ""; qDebug() << "tpl-tool accounts"; qDebug() << "tpl-tool contacts <account>"; qDebug() << "tpl-tool exists <account> <entity>"; qDebug() << "tpl-tool entities <account>"; qDebug() << "tpl-tool dates <account> <entity>"; qDebug() << "tpl-tool events <account> <entity> <date>"; qDebug() << "tpl-tool filteredEvents <account> <entity> <numEvents>"; qDebug() << "tpl-tool search <text>"; this->exit(-1); return false; } bool TplToolApplication::parseArgs2() { debugfn(); QStringList args = arguments(); Tpl::LogManagerPtr logManager = Tpl::LogManager::instance(); if (logManager.isNull()) { qWarning() << "LogManager not found"; return false; } if (args.size() == 3 && args.at(1) == "contacts") { Tp::Contacts contacts = mAccountPtr->connection()->contactManager()->allKnownContacts(); debugfn() << "number of contacts = " << contacts.size(); Tp::ContactPtr contact; int i = 0; Q_FOREACH(contact, contacts) { qDebug() << "contact " << i++ << contact->id(); } this->exit(); return true; } else if (args.size() == 4 && args.at(1) == "exists") { Tpl::EntityPtr entity = entityPtr(args.at(3)); if (entity.isNull()) { qWarning() << "Entity not found " << args.at(3); } bool ret = logManager->exists(mAccountPtr, entity, Tpl::EventTypeMaskAny); qDebug() << "tpl-tool exists " << args.at(2) << args.at(3) << " -> " << ret; this->exit(); return true; } else if (args.at(1) == "entities") { Tpl::PendingEntities *pe = logManager->queryEntities(mAccountPtr); debugfn() << "PendingEntities=" << pe; if (!pe) { qWarning() << "Error in PendingEntities"; this->exit(-1); return false; } connect(pe, SIGNAL(finished(Tpl::PendingOperation*)), this, SLOT(onPendingEntities(Tpl::PendingOperation*))); pe->start(); return true; } else if (args.at(1) == "dates") { Tpl::EntityPtr entity = entityPtr(args.at(3)); if (entity.isNull()) { qWarning() << "Entity not found " << args.at(3); } Tpl::PendingDates *pd = logManager->queryDates(mAccountPtr, entity, Tpl::EventTypeMaskAny); debugfn() << "PendingDates=" << pd; if (!pd) { qWarning() << "Error in PendingDates"; this->exit(-1); return false; } connect(pd, SIGNAL(finished(Tpl::PendingOperation*)), this, SLOT(onPendingDates(Tpl::PendingOperation*))); pd->start(); return true; } else if (args.at(1) == "events") { Tpl::EntityPtr entity = entityPtr(args.at(3)); if (entity.isNull()) { qWarning() << "Entity not found " << args.at(3); } QDate date = QDate::fromString(args.at(4), "yyyyMMdd"); Tpl::PendingEvents *pe = logManager->queryEvents(mAccountPtr, entity, Tpl::EventTypeMaskAny, date); debugfn() << "PendingEvents=" << pe << "date=" << date; if (!pe) { qWarning() << "Error in PendingDates"; this->exit(-1); return false; } connect(pe, SIGNAL(finished(Tpl::PendingOperation*)), this, SLOT(onPendingEvents(Tpl::PendingOperation*))); pe->start(); return true; } else if (args.at(1) == "filteredEvents") { } this->exit(-1); return false; } void TplToolApplication::onAccountManagerReady(Tp::PendingOperation *po) { debugfn() << "po=" << po << "isError=" << po->isError(); if (po->isError()) { qWarning() << "error getting account mananger ready"; exit(-1); return; } Tpl::LogManagerPtr logManager = Tpl::LogManager::instance(); if (logManager.isNull()) { qWarning() << "LogManager not found"; exit(-1); return; } logManager->setAccountManagerPtr(mAccountManager); parseArgs1(); } void TplToolApplication::onAccountReady(Tp::PendingOperation *po) { debugfn() << "po=" << po << "isError=" << po->isError(); if (po->isError()) { qWarning() << "error getting account ready"; exit(-1); return; } Tp::ConnectionPtr connection = mAccountPtr->connection(); if (connection.isNull()) { qWarning() << "error null connection"; exit(-1); return; } connect(mAccountPtr->connection()->becomeReady(Tp::Features() << Tp::Connection::FeatureCore << Tp::Connection::FeatureSelfContact << Tp::Connection::FeatureRoster), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onConnectionReady(Tp::PendingOperation*))); } void TplToolApplication::onConnectionReady(Tp::PendingOperation *po) { debugfn() << "po=" << po << "isError=" << po->isError(); if (po->isError()) { qWarning() << "error getting connection ready"; exit(-1); return; } parseArgs2(); } void TplToolApplication::onPendingSearch(Tpl::PendingOperation *po) { Tpl::PendingSearch *ps = (Tpl::PendingSearch*) po; if (ps->isError()) { qWarning() << "error in search"; exit(-1); return; } Tpl::SearchHitList *hits = ps->hits(); debugfn() << " search hits " << hits->size(); int count = 0; Tpl::SearchHit *hit; Q_FOREACH(hit, *hits) { debugfn() << count++ << "account=" << hit->account.data() << "date=" << hit->date << "target=" << (hit->target ? hit->target->identifier() : "null"); } this->exit(); } void TplToolApplication::onPendingEntities(Tpl::PendingOperation *po) { Tpl::PendingEntities *pe = (Tpl::PendingEntities*) po; if (pe->isError()) { qWarning() << "error in search"; exit(-1); return; } Tpl::EntityPtrList entities= pe->entities(); debugfn() << " Pending entities " << entities.size(); int count = 0; Tpl::EntityPtr entity; Q_FOREACH(entity, entities) { debugfn() << count++ << "entity id=" << entity->identifier() << "alias=" << entity->alias() << "type=" << entity->entityType() << "avatarToken=" << entity->avatarToken(); } this->exit(); } void TplToolApplication::onPendingDates(Tpl::PendingOperation *po) { Tpl::PendingDates *pd = (Tpl::PendingDates*) po; if (pd->isError()) { qWarning() << "error in search"; exit(-1); return; } Tpl::QDateList dates = pd->dates(); debugfn() << " Pending dates " << dates.size(); int count = 0; QDate date; Q_FOREACH(date, dates) { debugfn() << count++ << "date " << date.toString("yyyyMMdd"); } this->exit(); } void TplToolApplication::onPendingEvents(Tpl::PendingOperation *po) { Tpl::PendingEvents *pe = (Tpl::PendingEvents*) po; if (pe->isError()) { qWarning() << "error in PendingEvents"; exit(-1); return; } Tpl::EventPtrList events = pe->events(); debugfn() << " Pending events " << events.size(); int count = 0; QObject a; Tpl::EventPtr event; Q_FOREACH(event, events) { Tpl::TextEventPtr textEvent = event.dynamicCast<Tpl::TextEvent>(); if (!textEvent.isNull()) { debugfn() << count++ << "textEvent" << "timestamp=" << textEvent->timestamp().toString() << "sender=" << textEvent->sender()->identifier() << "receiver=" << textEvent->receiver()->identifier() << "message=" << textEvent->message() << "messageType=" << textEvent->messageType() << "account=" << (textEvent->account() ? textEvent->account()->objectPath() : "null") << "accountPath=" << textEvent->accountPath(); } else { debugfn() << count++ << "event" << "timestamp=" << event->timestamp().toString() << "sender=" << event->sender()->identifier() << "receiver=" << event->receiver()->identifier() << "account=" << (event->account() ? event->account()->objectPath() : "null") << "accountPath=" << event->accountPath(); } } this->exit(); } int main(int argc, char **argv) { g_type_init(); Tp::registerTypes(); TplToolApplication app(argc, argv); Tpl::init(); return app.exec(); } <commit_msg>Fix debug output Fix search query hits interface change Moved date format to #define so it's easier to change now<commit_after>/* * This file is part of TelepathyQt4Logger * * Copyright (C) 2011 Collabora Ltd. <http://www.collabora.co.uk/> * * 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 program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include "tpl-tool.h" #include <tools/_gen/tpl-tool.moc.hpp> #include <TelepathyQt4Logger/utils.h> #include <QApplication> #include <TelepathyQt4/Account> #include <TelepathyQt4/AccountSet> #include <TelepathyQt4/AccountManager> #include <TelepathyQt4/ContactManager> #include <TelepathyQt4/Connection> #include <TelepathyQt4/PendingReady> #include <TelepathyQt4Logger/Entity> #include <TelepathyQt4Logger/Event> #include <TelepathyQt4Logger/TextEvent> #include <TelepathyQt4Logger/LogManager> #include <TelepathyQt4Logger/PendingDates> #include <TelepathyQt4Logger/PendingEntities> #include <TelepathyQt4Logger/PendingEvents> #include <TelepathyQt4Logger/PendingSearch> #include <TelepathyQt4Logger/Init> #include <glib-object.h> #include <QGst/Init> #include <QDebug> #define TPL_TOOL_DATE_FORMAT "yyyyMMdd" TplToolApplication::TplToolApplication(int &argc, char **argv) : QCoreApplication(argc, argv) { debugfn(); mAccountManager = Tp::AccountManager::create(); connect(mAccountManager->becomeReady(Tp::AccountManager::FeatureCore), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onAccountManagerReady(Tp::PendingOperation*))); } Tp::AccountPtr TplToolApplication::accountPtr(const QString &id) { debugfn(); mAccountPtr = Tpl::Utils::instance()->accountPtr(id.toAscii()); if (!mAccountPtr->isValid()) { return mAccountPtr; } connect(mAccountPtr->becomeReady(Tp::Features() << Tp::Account::FeatureCore << Tp::Account::FeatureAvatar), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onAccountReady(Tp::PendingOperation*))); return mAccountPtr; } Tpl::EntityPtr TplToolApplication::entityPtr(const QString &id) { debugfn(); return Tpl::Entity::create(id.toAscii(), Tpl::EntityTypeContact, NULL, NULL); } bool TplToolApplication::parseArgs1() { debugfn(); QStringList args = arguments(); Tpl::LogManagerPtr logManager = Tpl::LogManager::instance(); if (logManager.isNull()) { qWarning() << "LogManager not found"; return false; } if (args.size() == 2 && args.at(1) == "accounts") { Tp::AccountSetPtr accountSet = Tpl::Utils::instance()->accountManagerPtr()->validAccounts(); QList<Tp::AccountPtr> accounts = accountSet->accounts(); Tp::AccountPtr account; int i = 0; Q_FOREACH(account, accounts) { qDebug() << "account " << i++ << account->objectPath(); } this->exit(); return true; } else if ((args.size() == 3 && args.at(1) == "contacts") || (args.size() == 4 && args.at(1) == "exists") || (args.size() == 3 && args.at(1) == "entities") || (args.size() == 4 && args.at(1) == "dates") || (args.size() == 5 && args.at(1) == "events") || (args.size() == 5 && args.at(1) == "filteredEvents")) { Tp::AccountPtr account = accountPtr(args.at(2).toAscii()); if (account.isNull()) { qWarning() << "Account not found " << args.at(2); } return true; } else if (args.size() == 3 && args.at(1) == "search") { Tpl::PendingSearch *ps = logManager->search(args.at(2), Tpl::EventTypeMaskAny); debugfn() << "PendingSearch=" << ps; if (!ps) { qWarning() << "Error in search"; this->exit(-1); return false; } connect(ps, SIGNAL(finished(Tpl::PendingOperation*)), this, SLOT(onPendingSearch(Tpl::PendingOperation*))); ps->start(); return true; } qDebug() << "Telepathy logger command line tool (qt4)"; qDebug() << ""; qDebug() << "General usage: tpl-tool <command> <parameters>"; qDebug() << ""; qDebug() << "tpl-tool accounts"; qDebug() << "tpl-tool contacts <account>"; qDebug() << "tpl-tool exists <account> <entity>"; qDebug() << "tpl-tool entities <account>"; qDebug() << "tpl-tool dates <account> <entity>"; qDebug() << "tpl-tool events <account> <entity> <date>"; qDebug() << "tpl-tool filteredEvents <account> <entity> <numEvents>"; qDebug() << "tpl-tool search <text>"; this->exit(-1); return false; } bool TplToolApplication::parseArgs2() { debugfn(); QStringList args = arguments(); Tpl::LogManagerPtr logManager = Tpl::LogManager::instance(); if (logManager.isNull()) { qWarning() << "LogManager not found"; return false; } if (args.size() == 3 && args.at(1) == "contacts") { Tp::Contacts contacts = mAccountPtr->connection()->contactManager()->allKnownContacts(); debugfn() << "number of contacts = " << contacts.size(); Tp::ContactPtr contact; int i = 0; Q_FOREACH(contact, contacts) { qDebug() << "contact " << i++ << contact->id(); } this->exit(); return true; } else if (args.size() == 4 && args.at(1) == "exists") { Tpl::EntityPtr entity = entityPtr(args.at(3)); if (entity.isNull()) { qWarning() << "Entity not found " << args.at(3); } bool ret = logManager->exists(mAccountPtr, entity, Tpl::EventTypeMaskAny); qDebug() << "tpl-tool exists " << args.at(2) << args.at(3) << " -> " << ret; this->exit(); return true; } else if (args.at(1) == "entities") { Tpl::PendingEntities *pe = logManager->queryEntities(mAccountPtr); debugfn() << "PendingEntities=" << pe; if (!pe) { qWarning() << "Error in PendingEntities"; this->exit(-1); return false; } connect(pe, SIGNAL(finished(Tpl::PendingOperation*)), this, SLOT(onPendingEntities(Tpl::PendingOperation*))); pe->start(); return true; } else if (args.at(1) == "dates") { Tpl::EntityPtr entity = entityPtr(args.at(3)); if (entity.isNull()) { qWarning() << "Entity not found " << args.at(3); } Tpl::PendingDates *pd = logManager->queryDates(mAccountPtr, entity, Tpl::EventTypeMaskAny); debugfn() << "PendingDates=" << pd; if (!pd) { qWarning() << "Error in PendingDates"; this->exit(-1); return false; } connect(pd, SIGNAL(finished(Tpl::PendingOperation*)), this, SLOT(onPendingDates(Tpl::PendingOperation*))); pd->start(); return true; } else if (args.at(1) == "events") { Tpl::EntityPtr entity = entityPtr(args.at(3)); if (entity.isNull()) { qWarning() << "Entity not found " << args.at(3); } QDate date = QDate::fromString(args.at(4), TPL_TOOL_DATE_FORMAT); Tpl::PendingEvents *pe = logManager->queryEvents(mAccountPtr, entity, Tpl::EventTypeMaskAny, date); debugfn() << "PendingEvents=" << pe << "date=" << date; if (!pe) { qWarning() << "Error in PendingDates"; this->exit(-1); return false; } connect(pe, SIGNAL(finished(Tpl::PendingOperation*)), this, SLOT(onPendingEvents(Tpl::PendingOperation*))); pe->start(); return true; } else if (args.at(1) == "filteredEvents") { } this->exit(-1); return false; } void TplToolApplication::onAccountManagerReady(Tp::PendingOperation *po) { debugfn() << "po=" << po << "isError=" << po->isError(); if (po->isError()) { qWarning() << "error getting account mananger ready"; exit(-1); return; } Tpl::LogManagerPtr logManager = Tpl::LogManager::instance(); if (logManager.isNull()) { qWarning() << "LogManager not found"; exit(-1); return; } logManager->setAccountManagerPtr(mAccountManager); parseArgs1(); } void TplToolApplication::onAccountReady(Tp::PendingOperation *po) { debugfn() << "po=" << po << "isError=" << po->isError(); if (po->isError()) { qWarning() << "error getting account ready"; exit(-1); return; } Tp::ConnectionPtr connection = mAccountPtr->connection(); if (connection.isNull()) { qWarning() << "error null connection"; exit(-1); return; } connect(mAccountPtr->connection()->becomeReady(Tp::Features() << Tp::Connection::FeatureCore << Tp::Connection::FeatureSelfContact << Tp::Connection::FeatureRoster), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onConnectionReady(Tp::PendingOperation*))); } void TplToolApplication::onConnectionReady(Tp::PendingOperation *po) { debugfn() << "po=" << po << "isError=" << po->isError(); if (po->isError()) { qWarning() << "error getting connection ready"; exit(-1); return; } parseArgs2(); } void TplToolApplication::onPendingSearch(Tpl::PendingOperation *po) { Tpl::PendingSearch *ps = (Tpl::PendingSearch*) po; if (ps->isError()) { qWarning() << "error in search"; exit(-1); return; } Tpl::SearchHitList hits = ps->hits(); debugfn() << " search hits " << hits.size(); int count = 0; Tpl::SearchHit *hit; Q_FOREACH(hit, hits) { qDebug() << count++ << "account=" << hit->account.data() << (hit->account.isNull() ? "null" : hit->account->objectPath()) << "date=" << hit->date.toString(TPL_TOOL_DATE_FORMAT) << "target=" << (hit->target ? hit->target->identifier() + "/" + hit->target->alias() + "/" + QString::number(hit->target->entityType()) + "/" + hit->target->avatarToken() : "null"); } this->exit(); } void TplToolApplication::onPendingEntities(Tpl::PendingOperation *po) { Tpl::PendingEntities *pe = (Tpl::PendingEntities*) po; if (pe->isError()) { qWarning() << "error in search"; exit(-1); return; } Tpl::EntityPtrList entities= pe->entities(); debugfn() << " Pending entities " << entities.size(); int count = 0; Tpl::EntityPtr entity; Q_FOREACH(entity, entities) { debugfn() << count++ << "entity id=" << entity->identifier() << "alias=" << entity->alias() << "type=" << entity->entityType() << "avatarToken=" << entity->avatarToken(); } this->exit(); } void TplToolApplication::onPendingDates(Tpl::PendingOperation *po) { Tpl::PendingDates *pd = (Tpl::PendingDates*) po; if (pd->isError()) { qWarning() << "error in search"; exit(-1); return; } Tpl::QDateList dates = pd->dates(); debugfn() << " Pending dates " << dates.size(); int count = 0; QDate date; Q_FOREACH(date, dates) { debugfn() << count++ << "date " << date.toString(TPL_TOOL_DATE_FORMAT); } this->exit(); } void TplToolApplication::onPendingEvents(Tpl::PendingOperation *po) { Tpl::PendingEvents *pe = (Tpl::PendingEvents*) po; if (pe->isError()) { qWarning() << "error in PendingEvents"; exit(-1); return; } Tpl::EventPtrList events = pe->events(); debugfn() << " Pending events " << events.size(); int count = 0; QObject a; Tpl::EventPtr event; Q_FOREACH(event, events) { Tpl::TextEventPtr textEvent = event.dynamicCast<Tpl::TextEvent>(); if (!textEvent.isNull()) { qDebug() << count++ << "textEvent" << "timestamp=" << textEvent->timestamp().toString() << "sender=" << textEvent->sender()->identifier() << "receiver=" << textEvent->receiver()->identifier() << "message=" << textEvent->message() << "messageType=" << textEvent->messageType() << "account=" << (textEvent->account() ? textEvent->account()->objectPath() : "null") << "accountPath=" << textEvent->accountPath(); } else { qDebug() << count++ << "event" << "timestamp=" << event->timestamp().toString() << "sender=" << event->sender()->identifier() << "receiver=" << event->receiver()->identifier() << "account=" << (event->account() ? event->account()->objectPath() : "null") << "accountPath=" << event->accountPath(); } } this->exit(); } int main(int argc, char **argv) { g_type_init(); Tp::registerTypes(); TplToolApplication app(argc, argv); Tpl::init(); return app.exec(); } <|endoftext|>
<commit_before>//===-- Communication.cpp ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/lldb-private-log.h" #include "lldb/Core/Communication.h" #include "lldb/Core/Connection.h" #include "lldb/Core/Log.h" #include "lldb/Core/Timer.h" #include "lldb/Core/Event.h" #include <string.h> using namespace lldb; using namespace lldb_private; //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- Communication::Communication(const char *name) : Broadcaster (name), m_connection_ap (), m_read_thread (LLDB_INVALID_HOST_THREAD), m_read_thread_enabled (false), m_bytes(), m_bytes_mutex (Mutex::eMutexTypeRecursive), m_callback (NULL), m_callback_baton (NULL), m_close_on_eof (true) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION, "%p Communication::Communication (name = %s)", this, name); } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- Communication::~Communication() { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION, "%p Communication::~Communication (name = %s)", this, m_broadcaster_name.AsCString("")); Clear(); } void Communication::Clear() { StopReadThread (NULL); Disconnect (NULL); } ConnectionStatus Communication::BytesAvailable (uint32_t timeout_usec, Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::BytesAvailable (timeout_usec = %u)", this, timeout_usec); if (m_connection_ap.get()) return m_connection_ap->BytesAvailable (timeout_usec, error_ptr); if (error_ptr) error_ptr->SetErrorString("Invalid connection."); return eConnectionStatusNoConnection; } ConnectionStatus Communication::Connect (const char *url, Error *error_ptr) { Clear(); lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Connect (url = %s)", this, url); if (m_connection_ap.get()) return m_connection_ap->Connect (url, error_ptr); if (error_ptr) error_ptr->SetErrorString("Invalid connection."); return eConnectionStatusNoConnection; } ConnectionStatus Communication::Disconnect (Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Disconnect ()", this); if (m_connection_ap.get()) { ConnectionStatus status = m_connection_ap->Disconnect (error_ptr); m_connection_ap.reset(); return status; } return eConnectionStatusNoConnection; } bool Communication::IsConnected () const { if (m_connection_ap.get()) return m_connection_ap->IsConnected (); return false; } bool Communication::HasConnection () const { return m_connection_ap.get() != NULL; } size_t Communication::Read (void *dst, size_t dst_len, uint32_t timeout_usec, ConnectionStatus &status, Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Write (dst = %p, dst_len = %zu, timeout_usec = %u) connection = %p", this, dst, dst_len, timeout_usec, m_connection_ap.get()); if (m_read_thread != LLDB_INVALID_HOST_THREAD) { // We have a dedicated read thread that is getting data for us size_t cached_bytes = GetCachedBytes (dst, dst_len); if (cached_bytes > 0 || timeout_usec == 0) { status = eConnectionStatusSuccess; return cached_bytes; } if (m_connection_ap.get() == NULL) { if (error_ptr) error_ptr->SetErrorString("Invalid connection."); status = eConnectionStatusNoConnection; return 0; } // Set the timeout appropriately TimeValue timeout_time; if (timeout_usec != UINT32_MAX) { timeout_time = TimeValue::Now(); timeout_time.OffsetWithMicroSeconds (timeout_usec); } Listener listener ("Communication::Read"); listener.StartListeningForEvents (this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit); EventSP event_sp; while (listener.WaitForEvent (timeout_time.IsValid() ? &timeout_time : NULL, event_sp)) { const uint32_t event_type = event_sp->GetType(); if (event_type & eBroadcastBitReadThreadGotBytes) { return GetCachedBytes (dst, dst_len); } if (event_type & eBroadcastBitReadThreadDidExit) { Disconnect (NULL); break; } } return 0; } // We aren't using a read thread, just read the data synchronously in this // thread. if (m_connection_ap.get()) { status = m_connection_ap->BytesAvailable (timeout_usec, error_ptr); if (status == eConnectionStatusSuccess) return m_connection_ap->Read (dst, dst_len, status, error_ptr); } if (error_ptr) error_ptr->SetErrorString("Invalid connection."); status = eConnectionStatusNoConnection; return 0; } size_t Communication::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Write (src = %p, src_len = %zu) connection = %p", this, src, src_len, m_connection_ap.get()); if (m_connection_ap.get()) return m_connection_ap->Write (src, src_len, status, error_ptr); if (error_ptr) error_ptr->SetErrorString("Invalid connection."); status = eConnectionStatusNoConnection; return 0; } bool Communication::StartReadThread (Error *error_ptr) { if (m_read_thread != LLDB_INVALID_HOST_THREAD) return true; lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::StartReadThread ()", this); char thread_name[1024]; snprintf(thread_name, sizeof(thread_name), "<lldb.comm.%s>", m_broadcaster_name.AsCString()); m_read_thread_enabled = true; m_read_thread = Host::ThreadCreate (thread_name, Communication::ReadThread, this, error_ptr); if (m_read_thread == LLDB_INVALID_HOST_THREAD) m_read_thread_enabled = false; return m_read_thread_enabled; } bool Communication::StopReadThread (Error *error_ptr) { if (m_read_thread == LLDB_INVALID_HOST_THREAD) return true; lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::StopReadThread ()", this); m_read_thread_enabled = false; BroadcastEvent (eBroadcastBitReadThreadShouldExit, NULL); Host::ThreadCancel (m_read_thread, error_ptr); return Host::ThreadJoin (m_read_thread, NULL, error_ptr); m_read_thread = LLDB_INVALID_HOST_THREAD; } size_t Communication::GetCachedBytes (void *dst, size_t dst_len) { Mutex::Locker locker(m_bytes_mutex); if (m_bytes.size() > 0) { // If DST is NULL and we have a thread, then return the number // of bytes that are available so the caller can call again if (dst == NULL) return m_bytes.size(); const size_t len = std::min<size_t>(dst_len, m_bytes.size()); ::memcpy (dst, m_bytes.c_str(), len); m_bytes.erase(m_bytes.begin(), m_bytes.begin() + len); return len; } return 0; } void Communication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool broadcast, ConnectionStatus status) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::AppendBytesToCache (src = %p, src_len = %zu, broadcast = %i)", this, bytes, len, broadcast); if (bytes == NULL || len == 0) return; if (m_callback) { // If the user registered a callback, then call it and do not broadcast m_callback (m_callback_baton, bytes, len); } else { Mutex::Locker locker(m_bytes_mutex); m_bytes.append ((const char *)bytes, len); if (broadcast) BroadcastEventIfUnique (eBroadcastBitReadThreadGotBytes); } } size_t Communication::ReadFromConnection (void *dst, size_t dst_len, ConnectionStatus &status, Error *error_ptr) { if (m_connection_ap.get()) return m_connection_ap->Read (dst, dst_len, status, error_ptr); return 0; } bool Communication::ReadThreadIsRunning () { return m_read_thread != LLDB_INVALID_HOST_THREAD; } void * Communication::ReadThread (void *p) { Communication *comm = (Communication *)p; LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMUNICATION)); if (log) log->Printf ("%p Communication::ReadThread () thread starting...", p); uint8_t buf[1024]; Error error; ConnectionStatus status = eConnectionStatusSuccess; bool done = false; while (!done && comm->m_read_thread_enabled) { status = comm->BytesAvailable (UINT32_MAX, &error); if (status == eConnectionStatusSuccess) { size_t bytes_read = comm->ReadFromConnection (buf, sizeof(buf), status, &error); if (bytes_read > 0) comm->AppendBytesToCache (buf, bytes_read, true, status); } switch (status) { case eConnectionStatusSuccess: break; case eConnectionStatusEndOfFile: case eConnectionStatusNoConnection: // No connection case eConnectionStatusLostConnection: // Lost connection while connected to a valid connection done = true; // Fall through... default: case eConnectionStatusError: // Check GetError() for details case eConnectionStatusTimedOut: // Request timed out if (log) error.LogIfError(log.get(), "%p Communication::BytesAvailable () => status = %i", p, status); break; } } log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMUNICATION); if (log) log->Printf ("%p Communication::ReadThread () thread exiting...", p); // Let clients know that this thread is exiting comm->BroadcastEvent (eBroadcastBitReadThreadDidExit); comm->m_read_thread = LLDB_INVALID_HOST_THREAD; return NULL; } void Communication::SetReadThreadBytesReceivedCallback ( ReadThreadBytesReceived callback, void *callback_baton ) { m_callback = callback; m_callback_baton = callback_baton; } void Communication::SetConnection (Connection *connection) { StopReadThread(NULL); Disconnect (NULL); m_connection_ap.reset(connection); } const char * Communication::ConnectionStatusAsCString (lldb::ConnectionStatus status) { switch (status) { case eConnectionStatusSuccess: return "success"; case eConnectionStatusError: return "error"; case eConnectionStatusTimedOut: return "timed out"; case eConnectionStatusNoConnection: return "no connection"; case eConnectionStatusLostConnection: return "lost connection"; } static char unknown_state_string[64]; snprintf(unknown_state_string, sizeof (unknown_state_string), "ConnectionStatus = %i", status); return unknown_state_string; } <commit_msg>Fixed a multi-threaded race condition that could happen when communication classes are shutting down. We currently don't protect communication connection classes against multi-threaded access. The connection is stored in the lldb_private::Communication.m_connection_ap auto_ptr member. We either need to add protections when accessing this class or not let anything racy occur. With this fix, we are doing the latter.<commit_after>//===-- Communication.cpp ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/lldb-private-log.h" #include "lldb/Core/Communication.h" #include "lldb/Core/Connection.h" #include "lldb/Core/Log.h" #include "lldb/Core/Timer.h" #include "lldb/Core/Event.h" #include <string.h> using namespace lldb; using namespace lldb_private; //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- Communication::Communication(const char *name) : Broadcaster (name), m_connection_ap (), m_read_thread (LLDB_INVALID_HOST_THREAD), m_read_thread_enabled (false), m_bytes(), m_bytes_mutex (Mutex::eMutexTypeRecursive), m_callback (NULL), m_callback_baton (NULL), m_close_on_eof (true) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION, "%p Communication::Communication (name = %s)", this, name); } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- Communication::~Communication() { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION, "%p Communication::~Communication (name = %s)", this, m_broadcaster_name.AsCString("")); Clear(); } void Communication::Clear() { StopReadThread (NULL); Disconnect (NULL); } ConnectionStatus Communication::BytesAvailable (uint32_t timeout_usec, Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::BytesAvailable (timeout_usec = %u)", this, timeout_usec); if (m_connection_ap.get()) return m_connection_ap->BytesAvailable (timeout_usec, error_ptr); if (error_ptr) error_ptr->SetErrorString("Invalid connection."); return eConnectionStatusNoConnection; } ConnectionStatus Communication::Connect (const char *url, Error *error_ptr) { Clear(); lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Connect (url = %s)", this, url); if (m_connection_ap.get()) return m_connection_ap->Connect (url, error_ptr); if (error_ptr) error_ptr->SetErrorString("Invalid connection."); return eConnectionStatusNoConnection; } ConnectionStatus Communication::Disconnect (Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Disconnect ()", this); if (m_connection_ap.get()) { ConnectionStatus status = m_connection_ap->Disconnect (error_ptr); // We currently don't protect m_connection_ap with any mutex for // multi-threaded environments. So lets not nuke our connection class // without putting some multi-threaded protections in. We also probably // don't want to pay for the overhead it might cause if every time we // access the connection we have to take a lock. // // This auto_ptr will cleanup after itself when this object goes away, // so there is no need to currently have it destroy itself immediately // upon disconnnect. //m_connection_ap.reset(); return status; } return eConnectionStatusNoConnection; } bool Communication::IsConnected () const { if (m_connection_ap.get()) return m_connection_ap->IsConnected (); return false; } bool Communication::HasConnection () const { return m_connection_ap.get() != NULL; } size_t Communication::Read (void *dst, size_t dst_len, uint32_t timeout_usec, ConnectionStatus &status, Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Write (dst = %p, dst_len = %zu, timeout_usec = %u) connection = %p", this, dst, dst_len, timeout_usec, m_connection_ap.get()); if (m_read_thread != LLDB_INVALID_HOST_THREAD) { // We have a dedicated read thread that is getting data for us size_t cached_bytes = GetCachedBytes (dst, dst_len); if (cached_bytes > 0 || timeout_usec == 0) { status = eConnectionStatusSuccess; return cached_bytes; } if (m_connection_ap.get() == NULL) { if (error_ptr) error_ptr->SetErrorString("Invalid connection."); status = eConnectionStatusNoConnection; return 0; } // Set the timeout appropriately TimeValue timeout_time; if (timeout_usec != UINT32_MAX) { timeout_time = TimeValue::Now(); timeout_time.OffsetWithMicroSeconds (timeout_usec); } Listener listener ("Communication::Read"); listener.StartListeningForEvents (this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit); EventSP event_sp; while (listener.WaitForEvent (timeout_time.IsValid() ? &timeout_time : NULL, event_sp)) { const uint32_t event_type = event_sp->GetType(); if (event_type & eBroadcastBitReadThreadGotBytes) { return GetCachedBytes (dst, dst_len); } if (event_type & eBroadcastBitReadThreadDidExit) { Disconnect (NULL); break; } } return 0; } // We aren't using a read thread, just read the data synchronously in this // thread. if (m_connection_ap.get()) { status = m_connection_ap->BytesAvailable (timeout_usec, error_ptr); if (status == eConnectionStatusSuccess) return m_connection_ap->Read (dst, dst_len, status, error_ptr); } if (error_ptr) error_ptr->SetErrorString("Invalid connection."); status = eConnectionStatusNoConnection; return 0; } size_t Communication::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Write (src = %p, src_len = %zu) connection = %p", this, src, src_len, m_connection_ap.get()); if (m_connection_ap.get()) return m_connection_ap->Write (src, src_len, status, error_ptr); if (error_ptr) error_ptr->SetErrorString("Invalid connection."); status = eConnectionStatusNoConnection; return 0; } bool Communication::StartReadThread (Error *error_ptr) { if (m_read_thread != LLDB_INVALID_HOST_THREAD) return true; lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::StartReadThread ()", this); char thread_name[1024]; snprintf(thread_name, sizeof(thread_name), "<lldb.comm.%s>", m_broadcaster_name.AsCString()); m_read_thread_enabled = true; m_read_thread = Host::ThreadCreate (thread_name, Communication::ReadThread, this, error_ptr); if (m_read_thread == LLDB_INVALID_HOST_THREAD) m_read_thread_enabled = false; return m_read_thread_enabled; } bool Communication::StopReadThread (Error *error_ptr) { if (m_read_thread == LLDB_INVALID_HOST_THREAD) return true; lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::StopReadThread ()", this); m_read_thread_enabled = false; BroadcastEvent (eBroadcastBitReadThreadShouldExit, NULL); Host::ThreadCancel (m_read_thread, error_ptr); return Host::ThreadJoin (m_read_thread, NULL, error_ptr); m_read_thread = LLDB_INVALID_HOST_THREAD; } size_t Communication::GetCachedBytes (void *dst, size_t dst_len) { Mutex::Locker locker(m_bytes_mutex); if (m_bytes.size() > 0) { // If DST is NULL and we have a thread, then return the number // of bytes that are available so the caller can call again if (dst == NULL) return m_bytes.size(); const size_t len = std::min<size_t>(dst_len, m_bytes.size()); ::memcpy (dst, m_bytes.c_str(), len); m_bytes.erase(m_bytes.begin(), m_bytes.begin() + len); return len; } return 0; } void Communication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool broadcast, ConnectionStatus status) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::AppendBytesToCache (src = %p, src_len = %zu, broadcast = %i)", this, bytes, len, broadcast); if (bytes == NULL || len == 0) return; if (m_callback) { // If the user registered a callback, then call it and do not broadcast m_callback (m_callback_baton, bytes, len); } else { Mutex::Locker locker(m_bytes_mutex); m_bytes.append ((const char *)bytes, len); if (broadcast) BroadcastEventIfUnique (eBroadcastBitReadThreadGotBytes); } } size_t Communication::ReadFromConnection (void *dst, size_t dst_len, ConnectionStatus &status, Error *error_ptr) { if (m_connection_ap.get()) return m_connection_ap->Read (dst, dst_len, status, error_ptr); return 0; } bool Communication::ReadThreadIsRunning () { return m_read_thread != LLDB_INVALID_HOST_THREAD; } void * Communication::ReadThread (void *p) { Communication *comm = (Communication *)p; LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMUNICATION)); if (log) log->Printf ("%p Communication::ReadThread () thread starting...", p); uint8_t buf[1024]; Error error; ConnectionStatus status = eConnectionStatusSuccess; bool done = false; while (!done && comm->m_read_thread_enabled) { status = comm->BytesAvailable (UINT32_MAX, &error); if (status == eConnectionStatusSuccess) { size_t bytes_read = comm->ReadFromConnection (buf, sizeof(buf), status, &error); if (bytes_read > 0) comm->AppendBytesToCache (buf, bytes_read, true, status); } switch (status) { case eConnectionStatusSuccess: break; case eConnectionStatusEndOfFile: case eConnectionStatusNoConnection: // No connection case eConnectionStatusLostConnection: // Lost connection while connected to a valid connection done = true; // Fall through... default: case eConnectionStatusError: // Check GetError() for details case eConnectionStatusTimedOut: // Request timed out if (log) error.LogIfError(log.get(), "%p Communication::BytesAvailable () => status = %i", p, status); break; } } log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMUNICATION); if (log) log->Printf ("%p Communication::ReadThread () thread exiting...", p); // Let clients know that this thread is exiting comm->BroadcastEvent (eBroadcastBitReadThreadDidExit); comm->m_read_thread = LLDB_INVALID_HOST_THREAD; comm->Disconnect(); return NULL; } void Communication::SetReadThreadBytesReceivedCallback ( ReadThreadBytesReceived callback, void *callback_baton ) { m_callback = callback; m_callback_baton = callback_baton; } void Communication::SetConnection (Connection *connection) { StopReadThread(NULL); Disconnect (NULL); m_connection_ap.reset(connection); } const char * Communication::ConnectionStatusAsCString (lldb::ConnectionStatus status) { switch (status) { case eConnectionStatusSuccess: return "success"; case eConnectionStatusError: return "error"; case eConnectionStatusTimedOut: return "timed out"; case eConnectionStatusNoConnection: return "no connection"; case eConnectionStatusLostConnection: return "lost connection"; } static char unknown_state_string[64]; snprintf(unknown_state_string, sizeof (unknown_state_string), "ConnectionStatus = %i", status); return unknown_state_string; } <|endoftext|>
<commit_before>//===-- Communication.cpp ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/lldb-private-log.h" #include "lldb/Core/Communication.h" #include "lldb/Core/Connection.h" #include "lldb/Core/Log.h" #include "lldb/Core/Timer.h" #include "lldb/Core/Event.h" #include <string.h> using namespace lldb; using namespace lldb_private; //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- Communication::Communication(const char *name) : Broadcaster (name), m_connection_sp (), m_read_thread (LLDB_INVALID_HOST_THREAD), m_read_thread_enabled (false), m_bytes(), m_bytes_mutex (Mutex::eMutexTypeRecursive), m_callback (NULL), m_callback_baton (NULL), m_close_on_eof (true) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION, "%p Communication::Communication (name = %s)", this, name); } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- Communication::~Communication() { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION, "%p Communication::~Communication (name = %s)", this, m_broadcaster_name.AsCString("")); Clear(); } void Communication::Clear() { StopReadThread (NULL); Disconnect (NULL); } ConnectionStatus Communication::BytesAvailable (uint32_t timeout_usec, Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::BytesAvailable (timeout_usec = %u)", this, timeout_usec); lldb::ConnectionSP connection_sp (m_connection_sp); if (connection_sp.get()) return connection_sp->BytesAvailable (timeout_usec, error_ptr); if (error_ptr) error_ptr->SetErrorString("Invalid connection."); return eConnectionStatusNoConnection; } ConnectionStatus Communication::Connect (const char *url, Error *error_ptr) { Clear(); lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Connect (url = %s)", this, url); lldb::ConnectionSP connection_sp (m_connection_sp); if (connection_sp.get()) return connection_sp->Connect (url, error_ptr); if (error_ptr) error_ptr->SetErrorString("Invalid connection."); return eConnectionStatusNoConnection; } ConnectionStatus Communication::Disconnect (Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Disconnect ()", this); lldb::ConnectionSP connection_sp (m_connection_sp); if (connection_sp.get()) { ConnectionStatus status = connection_sp->Disconnect (error_ptr); // We currently don't protect connection_sp with any mutex for // multi-threaded environments. So lets not nuke our connection class // without putting some multi-threaded protections in. We also probably // don't want to pay for the overhead it might cause if every time we // access the connection we have to take a lock. // // This auto_ptr will cleanup after itself when this object goes away, // so there is no need to currently have it destroy itself immediately // upon disconnnect. //connection_sp.reset(); return status; } return eConnectionStatusNoConnection; } bool Communication::IsConnected () const { lldb::ConnectionSP connection_sp (m_connection_sp); if (connection_sp.get()) return connection_sp->IsConnected (); return false; } bool Communication::HasConnection () const { return m_connection_sp.get() != NULL; } size_t Communication::Read (void *dst, size_t dst_len, uint32_t timeout_usec, ConnectionStatus &status, Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Read (dst = %p, dst_len = %zu, timeout_usec = %u) connection = %p", this, dst, dst_len, timeout_usec, m_connection_sp.get()); if (m_read_thread != LLDB_INVALID_HOST_THREAD) { // We have a dedicated read thread that is getting data for us size_t cached_bytes = GetCachedBytes (dst, dst_len); if (cached_bytes > 0 || timeout_usec == 0) { status = eConnectionStatusSuccess; return cached_bytes; } if (m_connection_sp.get() == NULL) { if (error_ptr) error_ptr->SetErrorString("Invalid connection."); status = eConnectionStatusNoConnection; return 0; } // Set the timeout appropriately TimeValue timeout_time; if (timeout_usec != UINT32_MAX) { timeout_time = TimeValue::Now(); timeout_time.OffsetWithMicroSeconds (timeout_usec); } Listener listener ("Communication::Read"); listener.StartListeningForEvents (this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit); EventSP event_sp; while (listener.WaitForEvent (timeout_time.IsValid() ? &timeout_time : NULL, event_sp)) { const uint32_t event_type = event_sp->GetType(); if (event_type & eBroadcastBitReadThreadGotBytes) { return GetCachedBytes (dst, dst_len); } if (event_type & eBroadcastBitReadThreadDidExit) { Disconnect (NULL); break; } } return 0; } // We aren't using a read thread, just read the data synchronously in this // thread. lldb::ConnectionSP connection_sp (m_connection_sp); if (connection_sp.get()) { status = connection_sp->BytesAvailable (timeout_usec, error_ptr); if (status == eConnectionStatusSuccess) return connection_sp->Read (dst, dst_len, status, error_ptr); } if (error_ptr) error_ptr->SetErrorString("Invalid connection."); status = eConnectionStatusNoConnection; return 0; } size_t Communication::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr) { lldb::ConnectionSP connection_sp (m_connection_sp); lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Write (src = %p, src_len = %zu) connection = %p", this, src, src_len, connection_sp.get()); if (connection_sp.get()) return connection_sp->Write (src, src_len, status, error_ptr); if (error_ptr) error_ptr->SetErrorString("Invalid connection."); status = eConnectionStatusNoConnection; return 0; } bool Communication::StartReadThread (Error *error_ptr) { if (m_read_thread != LLDB_INVALID_HOST_THREAD) return true; lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::StartReadThread ()", this); char thread_name[1024]; snprintf(thread_name, sizeof(thread_name), "<lldb.comm.%s>", m_broadcaster_name.AsCString()); m_read_thread_enabled = true; m_read_thread = Host::ThreadCreate (thread_name, Communication::ReadThread, this, error_ptr); if (m_read_thread == LLDB_INVALID_HOST_THREAD) m_read_thread_enabled = false; return m_read_thread_enabled; } bool Communication::StopReadThread (Error *error_ptr) { if (m_read_thread == LLDB_INVALID_HOST_THREAD) return true; lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::StopReadThread ()", this); m_read_thread_enabled = false; BroadcastEvent (eBroadcastBitReadThreadShouldExit, NULL); Host::ThreadCancel (m_read_thread, error_ptr); return Host::ThreadJoin (m_read_thread, NULL, error_ptr); m_read_thread = LLDB_INVALID_HOST_THREAD; } size_t Communication::GetCachedBytes (void *dst, size_t dst_len) { Mutex::Locker locker(m_bytes_mutex); if (m_bytes.size() > 0) { // If DST is NULL and we have a thread, then return the number // of bytes that are available so the caller can call again if (dst == NULL) return m_bytes.size(); const size_t len = std::min<size_t>(dst_len, m_bytes.size()); ::memcpy (dst, m_bytes.c_str(), len); m_bytes.erase(m_bytes.begin(), m_bytes.begin() + len); return len; } return 0; } void Communication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool broadcast, ConnectionStatus status) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::AppendBytesToCache (src = %p, src_len = %zu, broadcast = %i)", this, bytes, len, broadcast); if (bytes == NULL || len == 0) return; if (m_callback) { // If the user registered a callback, then call it and do not broadcast m_callback (m_callback_baton, bytes, len); } else { Mutex::Locker locker(m_bytes_mutex); m_bytes.append ((const char *)bytes, len); if (broadcast) BroadcastEventIfUnique (eBroadcastBitReadThreadGotBytes); } } size_t Communication::ReadFromConnection (void *dst, size_t dst_len, ConnectionStatus &status, Error *error_ptr) { lldb::ConnectionSP connection_sp (m_connection_sp); if (connection_sp.get()) return connection_sp->Read (dst, dst_len, status, error_ptr); return 0; } bool Communication::ReadThreadIsRunning () { return m_read_thread != LLDB_INVALID_HOST_THREAD; } void * Communication::ReadThread (void *p) { Communication *comm = (Communication *)p; LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMUNICATION)); if (log) log->Printf ("%p Communication::ReadThread () thread starting...", p); uint8_t buf[1024]; Error error; ConnectionStatus status = eConnectionStatusSuccess; bool done = false; while (!done && comm->m_read_thread_enabled) { status = comm->BytesAvailable (UINT32_MAX, &error); if (status == eConnectionStatusSuccess) { size_t bytes_read = comm->ReadFromConnection (buf, sizeof(buf), status, &error); if (bytes_read > 0) comm->AppendBytesToCache (buf, bytes_read, true, status); } switch (status) { case eConnectionStatusSuccess: break; case eConnectionStatusEndOfFile: case eConnectionStatusNoConnection: // No connection case eConnectionStatusLostConnection: // Lost connection while connected to a valid connection done = true; // Fall through... default: case eConnectionStatusError: // Check GetError() for details case eConnectionStatusTimedOut: // Request timed out if (log) error.LogIfError(log.get(), "%p Communication::BytesAvailable () => status = %i", p, status); break; } } log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMUNICATION); if (log) log->Printf ("%p Communication::ReadThread () thread exiting...", p); // Let clients know that this thread is exiting comm->BroadcastEvent (eBroadcastBitReadThreadDidExit); comm->m_read_thread = LLDB_INVALID_HOST_THREAD; comm->Disconnect(); return NULL; } void Communication::SetReadThreadBytesReceivedCallback ( ReadThreadBytesReceived callback, void *callback_baton ) { m_callback = callback; m_callback_baton = callback_baton; } void Communication::SetConnection (Connection *connection) { StopReadThread(NULL); Disconnect (NULL); m_connection_sp.reset(connection); } const char * Communication::ConnectionStatusAsCString (lldb::ConnectionStatus status) { switch (status) { case eConnectionStatusSuccess: return "success"; case eConnectionStatusError: return "error"; case eConnectionStatusTimedOut: return "timed out"; case eConnectionStatusNoConnection: return "no connection"; case eConnectionStatusLostConnection: return "lost connection"; } static char unknown_state_string[64]; snprintf(unknown_state_string, sizeof (unknown_state_string), "ConnectionStatus = %i", status); return unknown_state_string; } <commit_msg>Do not pass an invalid thread to Thread{Cancel,Join}.<commit_after>//===-- Communication.cpp ---------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // C Includes // C++ Includes // Other libraries and framework includes // Project includes #include "lldb/lldb-private-log.h" #include "lldb/Core/Communication.h" #include "lldb/Core/Connection.h" #include "lldb/Core/Log.h" #include "lldb/Core/Timer.h" #include "lldb/Core/Event.h" #include <string.h> using namespace lldb; using namespace lldb_private; //---------------------------------------------------------------------- // Constructor //---------------------------------------------------------------------- Communication::Communication(const char *name) : Broadcaster (name), m_connection_sp (), m_read_thread (LLDB_INVALID_HOST_THREAD), m_read_thread_enabled (false), m_bytes(), m_bytes_mutex (Mutex::eMutexTypeRecursive), m_callback (NULL), m_callback_baton (NULL), m_close_on_eof (true) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION, "%p Communication::Communication (name = %s)", this, name); } //---------------------------------------------------------------------- // Destructor //---------------------------------------------------------------------- Communication::~Communication() { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_OBJECT | LIBLLDB_LOG_COMMUNICATION, "%p Communication::~Communication (name = %s)", this, m_broadcaster_name.AsCString("")); Clear(); } void Communication::Clear() { StopReadThread (NULL); Disconnect (NULL); } ConnectionStatus Communication::BytesAvailable (uint32_t timeout_usec, Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::BytesAvailable (timeout_usec = %u)", this, timeout_usec); lldb::ConnectionSP connection_sp (m_connection_sp); if (connection_sp.get()) return connection_sp->BytesAvailable (timeout_usec, error_ptr); if (error_ptr) error_ptr->SetErrorString("Invalid connection."); return eConnectionStatusNoConnection; } ConnectionStatus Communication::Connect (const char *url, Error *error_ptr) { Clear(); lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Connect (url = %s)", this, url); lldb::ConnectionSP connection_sp (m_connection_sp); if (connection_sp.get()) return connection_sp->Connect (url, error_ptr); if (error_ptr) error_ptr->SetErrorString("Invalid connection."); return eConnectionStatusNoConnection; } ConnectionStatus Communication::Disconnect (Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Disconnect ()", this); lldb::ConnectionSP connection_sp (m_connection_sp); if (connection_sp.get()) { ConnectionStatus status = connection_sp->Disconnect (error_ptr); // We currently don't protect connection_sp with any mutex for // multi-threaded environments. So lets not nuke our connection class // without putting some multi-threaded protections in. We also probably // don't want to pay for the overhead it might cause if every time we // access the connection we have to take a lock. // // This auto_ptr will cleanup after itself when this object goes away, // so there is no need to currently have it destroy itself immediately // upon disconnnect. //connection_sp.reset(); return status; } return eConnectionStatusNoConnection; } bool Communication::IsConnected () const { lldb::ConnectionSP connection_sp (m_connection_sp); if (connection_sp.get()) return connection_sp->IsConnected (); return false; } bool Communication::HasConnection () const { return m_connection_sp.get() != NULL; } size_t Communication::Read (void *dst, size_t dst_len, uint32_t timeout_usec, ConnectionStatus &status, Error *error_ptr) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Read (dst = %p, dst_len = %zu, timeout_usec = %u) connection = %p", this, dst, dst_len, timeout_usec, m_connection_sp.get()); if (m_read_thread_enabled) { // We have a dedicated read thread that is getting data for us size_t cached_bytes = GetCachedBytes (dst, dst_len); if (cached_bytes > 0 || timeout_usec == 0) { status = eConnectionStatusSuccess; return cached_bytes; } if (m_connection_sp.get() == NULL) { if (error_ptr) error_ptr->SetErrorString("Invalid connection."); status = eConnectionStatusNoConnection; return 0; } // Set the timeout appropriately TimeValue timeout_time; if (timeout_usec != UINT32_MAX) { timeout_time = TimeValue::Now(); timeout_time.OffsetWithMicroSeconds (timeout_usec); } Listener listener ("Communication::Read"); listener.StartListeningForEvents (this, eBroadcastBitReadThreadGotBytes | eBroadcastBitReadThreadDidExit); EventSP event_sp; while (listener.WaitForEvent (timeout_time.IsValid() ? &timeout_time : NULL, event_sp)) { const uint32_t event_type = event_sp->GetType(); if (event_type & eBroadcastBitReadThreadGotBytes) { return GetCachedBytes (dst, dst_len); } if (event_type & eBroadcastBitReadThreadDidExit) { Disconnect (NULL); break; } } return 0; } // We aren't using a read thread, just read the data synchronously in this // thread. lldb::ConnectionSP connection_sp (m_connection_sp); if (connection_sp.get()) { status = connection_sp->BytesAvailable (timeout_usec, error_ptr); if (status == eConnectionStatusSuccess) return connection_sp->Read (dst, dst_len, status, error_ptr); } if (error_ptr) error_ptr->SetErrorString("Invalid connection."); status = eConnectionStatusNoConnection; return 0; } size_t Communication::Write (const void *src, size_t src_len, ConnectionStatus &status, Error *error_ptr) { lldb::ConnectionSP connection_sp (m_connection_sp); lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::Write (src = %p, src_len = %zu) connection = %p", this, src, src_len, connection_sp.get()); if (connection_sp.get()) return connection_sp->Write (src, src_len, status, error_ptr); if (error_ptr) error_ptr->SetErrorString("Invalid connection."); status = eConnectionStatusNoConnection; return 0; } bool Communication::StartReadThread (Error *error_ptr) { if (m_read_thread != LLDB_INVALID_HOST_THREAD) return true; lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::StartReadThread ()", this); char thread_name[1024]; snprintf(thread_name, sizeof(thread_name), "<lldb.comm.%s>", m_broadcaster_name.AsCString()); m_read_thread_enabled = true; m_read_thread = Host::ThreadCreate (thread_name, Communication::ReadThread, this, error_ptr); if (m_read_thread == LLDB_INVALID_HOST_THREAD) m_read_thread_enabled = false; return m_read_thread_enabled; } bool Communication::StopReadThread (Error *error_ptr) { if (m_read_thread == LLDB_INVALID_HOST_THREAD) return true; lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::StopReadThread ()", this); m_read_thread_enabled = false; BroadcastEvent (eBroadcastBitReadThreadShouldExit, NULL); Host::ThreadCancel (m_read_thread, error_ptr); bool status = Host::ThreadJoin (m_read_thread, NULL, error_ptr); m_read_thread = LLDB_INVALID_HOST_THREAD; return status; } size_t Communication::GetCachedBytes (void *dst, size_t dst_len) { Mutex::Locker locker(m_bytes_mutex); if (m_bytes.size() > 0) { // If DST is NULL and we have a thread, then return the number // of bytes that are available so the caller can call again if (dst == NULL) return m_bytes.size(); const size_t len = std::min<size_t>(dst_len, m_bytes.size()); ::memcpy (dst, m_bytes.c_str(), len); m_bytes.erase(m_bytes.begin(), m_bytes.begin() + len); return len; } return 0; } void Communication::AppendBytesToCache (const uint8_t * bytes, size_t len, bool broadcast, ConnectionStatus status) { lldb_private::LogIfAnyCategoriesSet (LIBLLDB_LOG_COMMUNICATION, "%p Communication::AppendBytesToCache (src = %p, src_len = %zu, broadcast = %i)", this, bytes, len, broadcast); if (bytes == NULL || len == 0) return; if (m_callback) { // If the user registered a callback, then call it and do not broadcast m_callback (m_callback_baton, bytes, len); } else { Mutex::Locker locker(m_bytes_mutex); m_bytes.append ((const char *)bytes, len); if (broadcast) BroadcastEventIfUnique (eBroadcastBitReadThreadGotBytes); } } size_t Communication::ReadFromConnection (void *dst, size_t dst_len, ConnectionStatus &status, Error *error_ptr) { lldb::ConnectionSP connection_sp (m_connection_sp); if (connection_sp.get()) return connection_sp->Read (dst, dst_len, status, error_ptr); return 0; } bool Communication::ReadThreadIsRunning () { return m_read_thread_enabled; } void * Communication::ReadThread (void *p) { Communication *comm = (Communication *)p; LogSP log(lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMUNICATION)); if (log) log->Printf ("%p Communication::ReadThread () thread starting...", p); uint8_t buf[1024]; Error error; ConnectionStatus status = eConnectionStatusSuccess; bool done = false; while (!done && comm->m_read_thread_enabled) { status = comm->BytesAvailable (UINT32_MAX, &error); if (status == eConnectionStatusSuccess) { size_t bytes_read = comm->ReadFromConnection (buf, sizeof(buf), status, &error); if (bytes_read > 0) comm->AppendBytesToCache (buf, bytes_read, true, status); } switch (status) { case eConnectionStatusSuccess: break; case eConnectionStatusEndOfFile: case eConnectionStatusNoConnection: // No connection case eConnectionStatusLostConnection: // Lost connection while connected to a valid connection done = true; // Fall through... default: case eConnectionStatusError: // Check GetError() for details case eConnectionStatusTimedOut: // Request timed out if (log) error.LogIfError(log.get(), "%p Communication::BytesAvailable () => status = %i", p, status); break; } } log = lldb_private::GetLogIfAllCategoriesSet (LIBLLDB_LOG_COMMUNICATION); if (log) log->Printf ("%p Communication::ReadThread () thread exiting...", p); // Let clients know that this thread is exiting comm->BroadcastEvent (eBroadcastBitReadThreadDidExit); comm->m_read_thread_enabled = false; comm->Disconnect(); return NULL; } void Communication::SetReadThreadBytesReceivedCallback ( ReadThreadBytesReceived callback, void *callback_baton ) { m_callback = callback; m_callback_baton = callback_baton; } void Communication::SetConnection (Connection *connection) { StopReadThread(NULL); Disconnect (NULL); m_connection_sp.reset(connection); } const char * Communication::ConnectionStatusAsCString (lldb::ConnectionStatus status) { switch (status) { case eConnectionStatusSuccess: return "success"; case eConnectionStatusError: return "error"; case eConnectionStatusTimedOut: return "timed out"; case eConnectionStatusNoConnection: return "no connection"; case eConnectionStatusLostConnection: return "lost connection"; } static char unknown_state_string[64]; snprintf(unknown_state_string, sizeof (unknown_state_string), "ConnectionStatus = %i", status); return unknown_state_string; } <|endoftext|>
<commit_before>#include <DuplicateConnector.h> #include <DuplicateSessionPool.h> DuplicateConnector::DuplicateConnector( uptr<MessageDuplicateBlock> msg ) : Connector( msg->address() , DUPLICATE_PORT ) { this->message_ = move_ptr( msg ); } DuplicateConnector::~DuplicateConnector() { } Session * DuplicateConnector::CreateSession() { return new DuplicateSession( move_ptr( this->message_ ) ); } void DuplicateConnector::OnSessionOpen( Session * session ) { auto s = scast<DuplicateSession*>( session ); DuplicateSessionPool::Instance()->Push( s ); s->SendRequest(); } void DuplicateConnector::OnSessionClose( Session * session ) { DuplicateSessionPool::Instance()->Pop( scast<DuplicateSession*>( session ) ); SAFE_DELETE( session ); } <commit_msg>fix bugs<commit_after>#include <DuplicateConnector.h> #include <DuplicateSessionPool.h> DuplicateConnector::DuplicateConnector( uptr<MessageDuplicateBlock> msg ) : Connector( msg->address() , msg->port() ) { this->message_ = move_ptr( msg ); } DuplicateConnector::~DuplicateConnector() { } Session * DuplicateConnector::CreateSession() { return new DuplicateSession( move_ptr( this->message_ ) ); } void DuplicateConnector::OnSessionOpen( Session * session ) { auto s = scast<DuplicateSession*>( session ); DuplicateSessionPool::Instance()->Push( s ); s->SendRequest(); } void DuplicateConnector::OnSessionClose( Session * session ) { DuplicateSessionPool::Instance()->Pop( scast<DuplicateSession*>( session ) ); SAFE_DELETE( session ); } <|endoftext|>
<commit_before>/* Copyright (C) 2013 Martin Klapetek <mklapetek@kde.org> Copyright (C) 2014 David Edmundson <davidedmundson@kde.org> 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "im-persons-data-source.h" #include <TelepathyQt/AccountManager> #include <TelepathyQt/AccountFactory> #include <TelepathyQt/ContactManager> #include <TelepathyQt/PendingOperation> #include <TelepathyQt/PendingReady> #include <TelepathyQt/Presence> #include "KTp/contact-factory.h" #include "KTp/global-contact-manager.h" #include "KTp/types.h" #include "debug.h" #include <KPeopleBackend/AllContactsMonitor> #include <KPluginFactory> #include <KPluginLoader> #include <QSqlDatabase> #include <QSqlQuery> #include <QPixmap> using namespace KPeople; class KTpAllContacts : public AllContactsMonitor { Q_OBJECT public: KTpAllContacts(); ~KTpAllContacts(); virtual QMap<QString, AbstractContact::Ptr> contacts() Q_DECL_OVERRIDE; private Q_SLOTS: void loadCache(); void onAccountManagerReady(Tp::PendingOperation *op); void onContactChanged(); void onContactInvalidated(); void onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved); private: QString createUri(const KTp::ContactPtr &contact) const; //presence names indexed by ConnectionPresenceType QHash<QString, KTp::ContactPtr> m_contacts; QMap<QString, AbstractContact::Ptr> m_contactVCards; }; static const QString S_KPEOPLE_PROPERTY_ACCOUNT_PATH = QString::fromLatin1("telepathy-accountPath"); static const QString S_KPEOPLE_PROPERTY_CONTACT_ID = QString::fromLatin1("telepathy-contactId"); static const QString S_KPEOPLE_PROPERTY_PRESENCE = QString::fromLatin1("telepathy-presence"); const QHash<Tp::ConnectionPresenceType, QString> s_presenceStrings = { { Tp::ConnectionPresenceTypeUnset, QString() }, { Tp::ConnectionPresenceTypeOffline, QString::fromLatin1("offline") }, { Tp::ConnectionPresenceTypeAvailable, QString::fromLatin1("available") }, { Tp::ConnectionPresenceTypeAway, QString::fromLatin1("away") }, { Tp::ConnectionPresenceTypeExtendedAway, QString::fromLatin1("xa") }, { Tp::ConnectionPresenceTypeHidden, QString::fromLatin1("hidden") }, //of 'offline' ? { Tp::ConnectionPresenceTypeBusy, QString::fromLatin1("busy") }, { Tp::ConnectionPresenceTypeUnknown, QString() }, { Tp::ConnectionPresenceTypeError, QString() } }; class TelepathyContact : public KPeople::AbstractContact { public: virtual QVariant customProperty(const QString &key) const Q_DECL_OVERRIDE { // Check if the contact is valid first if (m_contact && m_contact->manager() && m_contact->manager()->connection() && m_account) { if (key == AbstractContact::NameProperty) return m_contact->alias(); else if(key == AbstractContact::GroupsProperty) return m_contact->groups(); else if(key == S_KPEOPLE_PROPERTY_CONTACT_ID) return m_contact->id(); else if(key == S_KPEOPLE_PROPERTY_ACCOUNT_PATH) return m_account->objectPath(); else if(key == S_KPEOPLE_PROPERTY_PRESENCE) return s_presenceStrings.value(m_contact->presence().type()); else if (key == AbstractContact::PictureProperty) return m_contact->avatarPixmap(); } return m_properties[key]; } void insertProperty(const QString &key, const QVariant &value) { m_properties[key] = value; } void setContact(const KTp::ContactPtr &contact) { m_contact = contact; } void setAccount(const Tp::AccountPtr &account) { m_account = account; } private: KTp::ContactPtr m_contact; Tp::AccountPtr m_account; QVariantMap m_properties; }; KTpAllContacts::KTpAllContacts() { Tp::registerTypes(); loadCache(); } KTpAllContacts::~KTpAllContacts() { } void KTpAllContacts::loadCache() { QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), QLatin1String("ktpCache")); QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/ktp"); QDir().mkpath(path); db.setDatabaseName(path+QStringLiteral("/cache.db")); if (!db.open()) { qWarning() << "couldn't open database" << db.databaseName(); } QSqlQuery query(db); query.exec(QLatin1String("SELECT groupName FROM groups ORDER BY groupId;")); QStringList groupsList; while (query.next()) { groupsList.append(query.value(0).toString()); } if (!groupsList.isEmpty()) { query.exec(QLatin1String("SELECT accountId, contactId, alias, avatarFileName, groupsIds FROM contacts;")); } else { query.exec(QLatin1String("SELECT accountId, contactId, alias, avatarFileName FROM contacts;")); } while (query.next()) { QExplicitlySharedDataPointer<TelepathyContact> addressee(new TelepathyContact); const QString accountId = query.value(0).toString(); const QString contactId = query.value(1).toString(); addressee->insertProperty(AbstractContact::NameProperty, query.value(2).toString()); addressee->insertProperty(AbstractContact::PictureProperty, QUrl::fromLocalFile(query.value(3).toString())); if (!groupsList.isEmpty()) { QVariantList contactGroups; Q_FOREACH (const QString &groupIdStr, query.value(4).toString().split(QLatin1String(","))) { bool convSuccess; int groupId = groupIdStr.toInt(&convSuccess); if ((!convSuccess) || (groupId >= groupsList.count())) continue; contactGroups.append(groupsList.at(groupId)); } addressee->insertProperty(QStringLiteral("groups"), contactGroups); } addressee->insertProperty(S_KPEOPLE_PROPERTY_CONTACT_ID, contactId); addressee->insertProperty(S_KPEOPLE_PROPERTY_ACCOUNT_PATH, TP_QT_ACCOUNT_OBJECT_PATH_BASE + QLatin1Char('/') + accountId); addressee->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, s_presenceStrings[Tp::ConnectionPresenceTypeOffline]); const QString uri = QLatin1String("ktp://") + accountId + QLatin1Char('?') + contactId; m_contactVCards[uri] = addressee; Q_EMIT contactAdded(uri, addressee); } //now start fetching the up-to-date information connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onAccountManagerReady(Tp::PendingOperation*))); emitInitialFetchComplete(true); } QString KTpAllContacts::createUri(const KTp::ContactPtr &contact) const { // so real ID will look like // ktp://gabble/jabber/blah/asdfjwer?foo@bar.com // ? is used as it is not a valid character in the dbus path that makes up the account UID return QLatin1String("ktp://") + contact->accountUniqueIdentifier() + QLatin1Char('?') + contact->id(); } void KTpAllContacts::onAccountManagerReady(Tp::PendingOperation *op) { if (op->isError()) { qCWarning(KTP_KPEOPLE) << "Failed to initialize AccountManager:" << op->errorName(); qCWarning(KTP_KPEOPLE) << op->errorMessage(); return; } qCDebug(KTP_KPEOPLE) << "Account manager ready"; connect(KTp::contactManager(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)), this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts))); onAllKnownContactsChanged(KTp::contactManager()->allKnownContacts(), Tp::Contacts()); } void KTpAllContacts::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved) { if (!m_contacts.isEmpty()) { Q_FOREACH (const Tp::ContactPtr &c, contactsRemoved) { const KTp::ContactPtr &contact = KTp::ContactPtr::qObjectCast(c); const QString uri = createUri(contact); m_contacts.remove(uri); m_contactVCards.remove(uri); Q_EMIT contactRemoved(uri); } } Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) { KTp::ContactPtr ktpContact = KTp::ContactPtr::qObjectCast(contact); const QString uri = createUri(ktpContact); AbstractContact::Ptr vcard = m_contactVCards.value(uri); bool added = false; if (!vcard) { vcard = AbstractContact::Ptr(new TelepathyContact); m_contactVCards[uri] = vcard; added = true; } static_cast<TelepathyContact*>(vcard.data())->setContact(ktpContact); static_cast<TelepathyContact*>(vcard.data())->setAccount(KTp::contactManager()->accountForContact(ktpContact)); m_contacts.insert(uri, ktpContact); if (added) { Q_EMIT contactAdded(uri, vcard); } else { Q_EMIT contactChanged(uri, vcard); } connect(ktpContact.data(), SIGNAL(presenceChanged(Tp::Presence)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(invalidated()), this, SLOT(onContactInvalidated())); connect(ktpContact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(addedToGroup(QString)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(removedFromGroup(QString)), this, SLOT(onContactChanged())); } } void KTpAllContacts::onContactChanged() { const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender())); const QString uri = createUri(contact); Q_EMIT contactChanged(uri, m_contactVCards.value(uri)); } void KTpAllContacts::onContactInvalidated() { const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender())); const QString uri = createUri(contact); m_contacts.remove(uri); //set to offline and emit changed AbstractContact::Ptr vcard = m_contactVCards[uri]; TelepathyContact *tpContact = static_cast<TelepathyContact*>(vcard.data()); tpContact->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, QStringLiteral("offline")); Q_EMIT contactChanged(uri, vcard); } QMap<QString, AbstractContact::Ptr> KTpAllContacts::contacts() { return m_contactVCards; } IMPersonsDataSource::IMPersonsDataSource(QObject *parent, const QVariantList &args) : BasePersonsDataSource(parent) { Q_UNUSED(args); } IMPersonsDataSource::~IMPersonsDataSource() { } QString IMPersonsDataSource::sourcePluginId() const { return QStringLiteral("ktp"); } AllContactsMonitor* IMPersonsDataSource::createAllContactsMonitor() { return new KTpAllContacts(); } K_PLUGIN_FACTORY( IMPersonsDataSourceFactory, registerPlugin<IMPersonsDataSource>(); ) K_EXPORT_PLUGIN( IMPersonsDataSourceFactory("im_persons_data_source_plugin") ) #include "im-persons-data-source.moc" <commit_msg>Set the Unknown and Error presences to something<commit_after>/* Copyright (C) 2013 Martin Klapetek <mklapetek@kde.org> Copyright (C) 2014 David Edmundson <davidedmundson@kde.org> 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 Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include "im-persons-data-source.h" #include <TelepathyQt/AccountManager> #include <TelepathyQt/AccountFactory> #include <TelepathyQt/ContactManager> #include <TelepathyQt/PendingOperation> #include <TelepathyQt/PendingReady> #include <TelepathyQt/Presence> #include "KTp/contact-factory.h" #include "KTp/global-contact-manager.h" #include "KTp/types.h" #include "debug.h" #include <KPeopleBackend/AllContactsMonitor> #include <KPluginFactory> #include <KPluginLoader> #include <QSqlDatabase> #include <QSqlQuery> #include <QPixmap> using namespace KPeople; class KTpAllContacts : public AllContactsMonitor { Q_OBJECT public: KTpAllContacts(); ~KTpAllContacts(); virtual QMap<QString, AbstractContact::Ptr> contacts() Q_DECL_OVERRIDE; private Q_SLOTS: void loadCache(); void onAccountManagerReady(Tp::PendingOperation *op); void onContactChanged(); void onContactInvalidated(); void onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved); private: QString createUri(const KTp::ContactPtr &contact) const; //presence names indexed by ConnectionPresenceType QHash<QString, KTp::ContactPtr> m_contacts; QMap<QString, AbstractContact::Ptr> m_contactVCards; }; static const QString S_KPEOPLE_PROPERTY_ACCOUNT_PATH = QString::fromLatin1("telepathy-accountPath"); static const QString S_KPEOPLE_PROPERTY_CONTACT_ID = QString::fromLatin1("telepathy-contactId"); static const QString S_KPEOPLE_PROPERTY_PRESENCE = QString::fromLatin1("telepathy-presence"); const QHash<Tp::ConnectionPresenceType, QString> s_presenceStrings = { { Tp::ConnectionPresenceTypeUnset, QString() }, { Tp::ConnectionPresenceTypeOffline, QString::fromLatin1("offline") }, { Tp::ConnectionPresenceTypeAvailable, QString::fromLatin1("available") }, { Tp::ConnectionPresenceTypeAway, QString::fromLatin1("away") }, { Tp::ConnectionPresenceTypeExtendedAway, QString::fromLatin1("xa") }, { Tp::ConnectionPresenceTypeHidden, QString::fromLatin1("hidden") }, //of 'offline' ? { Tp::ConnectionPresenceTypeBusy, QString::fromLatin1("busy") }, { Tp::ConnectionPresenceTypeUnknown, QString::fromLatin1("unknown") }, { Tp::ConnectionPresenceTypeError, QString::fromLatin1("error") } }; class TelepathyContact : public KPeople::AbstractContact { public: virtual QVariant customProperty(const QString &key) const Q_DECL_OVERRIDE { // Check if the contact is valid first if (m_contact && m_contact->manager() && m_contact->manager()->connection() && m_account) { if (key == AbstractContact::NameProperty) return m_contact->alias(); else if(key == AbstractContact::GroupsProperty) return m_contact->groups(); else if(key == S_KPEOPLE_PROPERTY_CONTACT_ID) return m_contact->id(); else if(key == S_KPEOPLE_PROPERTY_ACCOUNT_PATH) return m_account->objectPath(); else if(key == S_KPEOPLE_PROPERTY_PRESENCE) return s_presenceStrings.value(m_contact->presence().type()); else if (key == AbstractContact::PictureProperty) return m_contact->avatarPixmap(); } return m_properties[key]; } void insertProperty(const QString &key, const QVariant &value) { m_properties[key] = value; } void setContact(const KTp::ContactPtr &contact) { m_contact = contact; } void setAccount(const Tp::AccountPtr &account) { m_account = account; } private: KTp::ContactPtr m_contact; Tp::AccountPtr m_account; QVariantMap m_properties; }; KTpAllContacts::KTpAllContacts() { Tp::registerTypes(); loadCache(); } KTpAllContacts::~KTpAllContacts() { } void KTpAllContacts::loadCache() { QSqlDatabase db = QSqlDatabase::addDatabase(QLatin1String("QSQLITE"), QLatin1String("ktpCache")); QString path = QStandardPaths::writableLocation(QStandardPaths::GenericDataLocation) + QLatin1String("/ktp"); QDir().mkpath(path); db.setDatabaseName(path+QStringLiteral("/cache.db")); if (!db.open()) { qWarning() << "couldn't open database" << db.databaseName(); } QSqlQuery query(db); query.exec(QLatin1String("SELECT groupName FROM groups ORDER BY groupId;")); QStringList groupsList; while (query.next()) { groupsList.append(query.value(0).toString()); } if (!groupsList.isEmpty()) { query.exec(QLatin1String("SELECT accountId, contactId, alias, avatarFileName, groupsIds FROM contacts;")); } else { query.exec(QLatin1String("SELECT accountId, contactId, alias, avatarFileName FROM contacts;")); } while (query.next()) { QExplicitlySharedDataPointer<TelepathyContact> addressee(new TelepathyContact); const QString accountId = query.value(0).toString(); const QString contactId = query.value(1).toString(); addressee->insertProperty(AbstractContact::NameProperty, query.value(2).toString()); addressee->insertProperty(AbstractContact::PictureProperty, QUrl::fromLocalFile(query.value(3).toString())); if (!groupsList.isEmpty()) { QVariantList contactGroups; Q_FOREACH (const QString &groupIdStr, query.value(4).toString().split(QLatin1String(","))) { bool convSuccess; int groupId = groupIdStr.toInt(&convSuccess); if ((!convSuccess) || (groupId >= groupsList.count())) continue; contactGroups.append(groupsList.at(groupId)); } addressee->insertProperty(QStringLiteral("groups"), contactGroups); } addressee->insertProperty(S_KPEOPLE_PROPERTY_CONTACT_ID, contactId); addressee->insertProperty(S_KPEOPLE_PROPERTY_ACCOUNT_PATH, TP_QT_ACCOUNT_OBJECT_PATH_BASE + QLatin1Char('/') + accountId); addressee->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, s_presenceStrings[Tp::ConnectionPresenceTypeOffline]); const QString uri = QLatin1String("ktp://") + accountId + QLatin1Char('?') + contactId; m_contactVCards[uri] = addressee; Q_EMIT contactAdded(uri, addressee); } //now start fetching the up-to-date information connect(KTp::accountManager()->becomeReady(), SIGNAL(finished(Tp::PendingOperation*)), this, SLOT(onAccountManagerReady(Tp::PendingOperation*))); emitInitialFetchComplete(true); } QString KTpAllContacts::createUri(const KTp::ContactPtr &contact) const { // so real ID will look like // ktp://gabble/jabber/blah/asdfjwer?foo@bar.com // ? is used as it is not a valid character in the dbus path that makes up the account UID return QLatin1String("ktp://") + contact->accountUniqueIdentifier() + QLatin1Char('?') + contact->id(); } void KTpAllContacts::onAccountManagerReady(Tp::PendingOperation *op) { if (op->isError()) { qCWarning(KTP_KPEOPLE) << "Failed to initialize AccountManager:" << op->errorName(); qCWarning(KTP_KPEOPLE) << op->errorMessage(); return; } qCDebug(KTP_KPEOPLE) << "Account manager ready"; connect(KTp::contactManager(), SIGNAL(allKnownContactsChanged(Tp::Contacts,Tp::Contacts)), this, SLOT(onAllKnownContactsChanged(Tp::Contacts,Tp::Contacts))); onAllKnownContactsChanged(KTp::contactManager()->allKnownContacts(), Tp::Contacts()); } void KTpAllContacts::onAllKnownContactsChanged(const Tp::Contacts &contactsAdded, const Tp::Contacts &contactsRemoved) { if (!m_contacts.isEmpty()) { Q_FOREACH (const Tp::ContactPtr &c, contactsRemoved) { const KTp::ContactPtr &contact = KTp::ContactPtr::qObjectCast(c); const QString uri = createUri(contact); m_contacts.remove(uri); m_contactVCards.remove(uri); Q_EMIT contactRemoved(uri); } } Q_FOREACH (const Tp::ContactPtr &contact, contactsAdded) { KTp::ContactPtr ktpContact = KTp::ContactPtr::qObjectCast(contact); const QString uri = createUri(ktpContact); AbstractContact::Ptr vcard = m_contactVCards.value(uri); bool added = false; if (!vcard) { vcard = AbstractContact::Ptr(new TelepathyContact); m_contactVCards[uri] = vcard; added = true; } static_cast<TelepathyContact*>(vcard.data())->setContact(ktpContact); static_cast<TelepathyContact*>(vcard.data())->setAccount(KTp::contactManager()->accountForContact(ktpContact)); m_contacts.insert(uri, ktpContact); if (added) { Q_EMIT contactAdded(uri, vcard); } else { Q_EMIT contactChanged(uri, vcard); } connect(ktpContact.data(), SIGNAL(presenceChanged(Tp::Presence)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(capabilitiesChanged(Tp::ContactCapabilities)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(invalidated()), this, SLOT(onContactInvalidated())); connect(ktpContact.data(), SIGNAL(avatarDataChanged(Tp::AvatarData)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(addedToGroup(QString)), this, SLOT(onContactChanged())); connect(ktpContact.data(), SIGNAL(removedFromGroup(QString)), this, SLOT(onContactChanged())); } } void KTpAllContacts::onContactChanged() { const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender())); const QString uri = createUri(contact); Q_EMIT contactChanged(uri, m_contactVCards.value(uri)); } void KTpAllContacts::onContactInvalidated() { const KTp::ContactPtr contact(qobject_cast<KTp::Contact*>(sender())); const QString uri = createUri(contact); m_contacts.remove(uri); //set to offline and emit changed AbstractContact::Ptr vcard = m_contactVCards[uri]; TelepathyContact *tpContact = static_cast<TelepathyContact*>(vcard.data()); tpContact->insertProperty(S_KPEOPLE_PROPERTY_PRESENCE, QStringLiteral("offline")); Q_EMIT contactChanged(uri, vcard); } QMap<QString, AbstractContact::Ptr> KTpAllContacts::contacts() { return m_contactVCards; } IMPersonsDataSource::IMPersonsDataSource(QObject *parent, const QVariantList &args) : BasePersonsDataSource(parent) { Q_UNUSED(args); } IMPersonsDataSource::~IMPersonsDataSource() { } QString IMPersonsDataSource::sourcePluginId() const { return QStringLiteral("ktp"); } AllContactsMonitor* IMPersonsDataSource::createAllContactsMonitor() { return new KTpAllContacts(); } K_PLUGIN_FACTORY( IMPersonsDataSourceFactory, registerPlugin<IMPersonsDataSource>(); ) K_EXPORT_PLUGIN( IMPersonsDataSourceFactory("im_persons_data_source_plugin") ) #include "im-persons-data-source.moc" <|endoftext|>
<commit_before>#include <iostream> #include <set> #include <algorithm> #include <functional> #include <ode/ode.h> #include <drawstuff/drawstuff.h> #include "texturepath.h" #ifdef dDOUBLE #define dsDrawBox dsDrawBoxD #define dsDrawCylinder dsDrawCylinderD #endif using namespace std; dWorld *world; dSpace *space; dPlane *ground; dBody *kbody; dBox *kbox; dJointGroup joints; dCylinder *kpole; dBody *matraca; dBox *matraca_geom; dHingeJoint *hinge; struct Box { dBody body; dBox geom; Box() : body(*world), geom(*space, 0.2, 0.2, 0.2) { dMass mass; mass.setBox(1, 0.2, 0.2, 0.2); body.setMass(mass); geom.setData(this); geom.setBody(body); } void draw() const { dVector3 lengths; geom.getLengths(lengths); dsSetTexture(DS_WOOD); dsSetColor(0,1,0); dsDrawBox(geom.getPosition(), geom.getRotation(), lengths); } }; set<Box*> boxes; set<Box*> to_remove; void dropBox() { Box *box = new Box(); dReal px = (rand() / float(RAND_MAX)) * 2 - 1; dReal py = (rand() / float(RAND_MAX)) * 2 - 1; dReal pz = 3; box->body.setPosition(px, py, pz); boxes.insert(box); } void queueRemoval(dGeomID g) { Box *b = (Box*)dGeomGetData(g); to_remove.insert(b); } void removeQueued() { while (!to_remove.empty()) { Box *b = *to_remove.begin(); to_remove.erase(b); boxes.erase(b); delete b; } } void nearCallback(void *data, dGeomID g1, dGeomID g2) { if (g1 == ground->id()) { queueRemoval(g2); return; } if (g2 == ground->id()) { queueRemoval(g1); return; } dBodyID b1 = dGeomGetBody(g1); dBodyID b2 = dGeomGetBody(g2); if (b1 and b2 and dAreConnectedExcluding(b1, b2, dJointTypeContact)) return; const int MAX_CONTACTS = 10; dContact contact[MAX_CONTACTS]; int n = dCollide(g1, g2, MAX_CONTACTS, &contact[0].geom, sizeof(dContact)); for (int i=0; i<n; ++i) { contact[i].surface.mode = 0; contact[i].surface.mu = 1; dJointID j = dJointCreateContact (*world, joints.id(), contact+i); dJointAttach(j, b1, b2); } } void simLoop(int pause) { if (!pause) { const dReal timestep = 0.005; // this does a hard-coded circular motion animation static float t=0; t += timestep/4; if (t > 2*M_PI) t = 0; dReal px = cos(t); dReal py = sin(t); dReal vx = -sin(t)/4; dReal vy = cos(t)/4; kbody->setPosition(px, py, .5); kbody->setLinearVel(vx, vy, 0); // end of hard-coded animation space->collide(0, nearCallback); removeQueued(); world->quickStep(timestep); joints.clear(); } dVector3 lengths; // the moving platform kbox->getLengths(lengths); dsSetTexture(DS_WOOD); dsSetColor(.3, .3, 1); dsDrawBox(kbox->getPosition(), kbox->getRotation(), lengths); dReal length, radius; kpole->getParams(&radius, &length); dsSetTexture(DS_CHECKERED); dsSetColor(1, 1, 0); dsDrawCylinder(kpole->getPosition(), kpole->getRotation(), length, radius); // the matraca matraca_geom->getLengths(lengths); dsSetColor(1,0,0); dsSetTexture(DS_WOOD); dsDrawBox(matraca_geom->getPosition(), matraca_geom->getRotation(), lengths); // and the boxes for_each(boxes.begin(), boxes.end(), mem_fun(&Box::draw)); } void command(int c) { switch (c) { case ' ': dropBox(); break; } } int main(int argc, char **argv) { dInitODE(); // setup pointers to drawstuff callback functions dsFunctions fn; fn.version = DS_VERSION; fn.start = 0; fn.step = &simLoop; fn.command = &command; fn.stop = 0; fn.path_to_textures = DRAWSTUFF_TEXTURE_PATH; cout << endl << "*** Press SPACE to drop boxes **" << endl; space = new dSimpleSpace(); ground = new dPlane(*space, 0, 0, 1, 0); world = new dWorld; world->setGravity(0, 0, -.5); kbody = new dBody(*world); kbody->setKinematic(); const dReal kx = 1, ky = 0, kz = .5; kbody->setPosition(kx, ky, kz); kbox = new dBox(*space, 3, 3, .5); kbox->setBody(*kbody); kpole = new dCylinder(*space, .125, 1.5); kpole->setBody(*kbody); dGeomSetOffsetPosition(kpole->id(), 0, 0, 0.8); matraca = new dBody(*world); matraca->setPosition(kx+0, ky+1, kz+1); matraca_geom = new dBox(*space, 0.5, 2, 0.75); matraca_geom->setBody(*matraca); dMass mass; mass.setBox(1, 0.5, 2, 0.75); matraca->setMass(mass); hinge = new dHingeJoint(*world); hinge->attach(*kbody, *matraca); hinge->setAnchor(kx, ky, kz+1); hinge->setAxis(0, 0, 1); dsSimulationLoop (argc, argv, 640, 480, &fn); dCloseODE(); } <commit_msg>Fixed: Compilation error in Visual Studio fixed <commit_after>#include <iostream> #include <set> #include <algorithm> #include <functional> #include <ode/ode.h> #include <drawstuff/drawstuff.h> #include "texturepath.h" #ifdef dDOUBLE #define dsDrawBox dsDrawBoxD #define dsDrawCylinder dsDrawCylinderD #endif using namespace std; dWorld *world; dSpace *space; dPlane *ground; dBody *kbody; dBox *kbox; dJointGroup joints; dCylinder *kpole; dBody *matraca; dBox *matraca_geom; dHingeJoint *hinge; struct Box { dBody body; dBox geom; Box() : body(*world), geom(*space, 0.2, 0.2, 0.2) { dMass mass; mass.setBox(1, 0.2, 0.2, 0.2); body.setMass(mass); geom.setData(this); geom.setBody(body); } void draw() const { dVector3 lengths; geom.getLengths(lengths); dsSetTexture(DS_WOOD); dsSetColor(0,1,0); dsDrawBox(geom.getPosition(), geom.getRotation(), lengths); } }; set<Box*> boxes; set<Box*> to_remove; void dropBox() { Box *box = new Box(); dReal px = (rand() / float(RAND_MAX)) * 2 - 1; dReal py = (rand() / float(RAND_MAX)) * 2 - 1; dReal pz = 3; box->body.setPosition(px, py, pz); boxes.insert(box); } void queueRemoval(dGeomID g) { Box *b = (Box*)dGeomGetData(g); to_remove.insert(b); } void removeQueued() { while (!to_remove.empty()) { Box *b = *to_remove.begin(); to_remove.erase(b); boxes.erase(b); delete b; } } void nearCallback(void *data, dGeomID g1, dGeomID g2) { if (g1 == ground->id()) { queueRemoval(g2); return; } if (g2 == ground->id()) { queueRemoval(g1); return; } dBodyID b1 = dGeomGetBody(g1); dBodyID b2 = dGeomGetBody(g2); if (b1 && b2 && dAreConnectedExcluding(b1, b2, dJointTypeContact)) return; const int MAX_CONTACTS = 10; dContact contact[MAX_CONTACTS]; int n = dCollide(g1, g2, MAX_CONTACTS, &contact[0].geom, sizeof(dContact)); for (int i=0; i<n; ++i) { contact[i].surface.mode = 0; contact[i].surface.mu = 1; dJointID j = dJointCreateContact (*world, joints.id(), contact+i); dJointAttach(j, b1, b2); } } void simLoop(int pause) { if (!pause) { const dReal timestep = 0.005; // this does a hard-coded circular motion animation static float t=0; t += timestep/4; if (t > 2*M_PI) t = 0; dReal px = cos(t); dReal py = sin(t); dReal vx = -sin(t)/4; dReal vy = cos(t)/4; kbody->setPosition(px, py, .5); kbody->setLinearVel(vx, vy, 0); // end of hard-coded animation space->collide(0, nearCallback); removeQueued(); world->quickStep(timestep); joints.clear(); } dVector3 lengths; // the moving platform kbox->getLengths(lengths); dsSetTexture(DS_WOOD); dsSetColor(.3, .3, 1); dsDrawBox(kbox->getPosition(), kbox->getRotation(), lengths); dReal length, radius; kpole->getParams(&radius, &length); dsSetTexture(DS_CHECKERED); dsSetColor(1, 1, 0); dsDrawCylinder(kpole->getPosition(), kpole->getRotation(), length, radius); // the matraca matraca_geom->getLengths(lengths); dsSetColor(1,0,0); dsSetTexture(DS_WOOD); dsDrawBox(matraca_geom->getPosition(), matraca_geom->getRotation(), lengths); // and the boxes for_each(boxes.begin(), boxes.end(), mem_fun(&Box::draw)); } void command(int c) { switch (c) { case ' ': dropBox(); break; } } int main(int argc, char **argv) { dInitODE(); // setup pointers to drawstuff callback functions dsFunctions fn; fn.version = DS_VERSION; fn.start = 0; fn.step = &simLoop; fn.command = &command; fn.stop = 0; fn.path_to_textures = DRAWSTUFF_TEXTURE_PATH; cout << endl << "*** Press SPACE to drop boxes **" << endl; space = new dSimpleSpace(); ground = new dPlane(*space, 0, 0, 1, 0); world = new dWorld; world->setGravity(0, 0, -.5); kbody = new dBody(*world); kbody->setKinematic(); const dReal kx = 1, ky = 0, kz = .5; kbody->setPosition(kx, ky, kz); kbox = new dBox(*space, 3, 3, .5); kbox->setBody(*kbody); kpole = new dCylinder(*space, .125, 1.5); kpole->setBody(*kbody); dGeomSetOffsetPosition(kpole->id(), 0, 0, 0.8); matraca = new dBody(*world); matraca->setPosition(kx+0, ky+1, kz+1); matraca_geom = new dBox(*space, 0.5, 2, 0.75); matraca_geom->setBody(*matraca); dMass mass; mass.setBox(1, 0.5, 2, 0.75); matraca->setMass(mass); hinge = new dHingeJoint(*world); hinge->attach(*kbody, *matraca); hinge->setAnchor(kx, ky, kz+1); hinge->setAxis(0, 0, 1); dsSimulationLoop (argc, argv, 640, 480, &fn); dCloseODE(); } <|endoftext|>
<commit_before>/* The MIT License Copyright (c) 2013 Adrian Tan <atks@umich.edu> 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 "merge_candidate_variants.h" namespace { class Evidence { public: uint32_t i, m; uint32_t* e; uint32_t* n; kstring_t samples; int32_t esum, nsum; double af; double lr; bcf1_t *v; Evidence(uint32_t m) { this->m = m; i = 0; e = (uint32_t*) malloc(m*sizeof(uint32_t)); n = (uint32_t*) malloc(m*sizeof(uint32_t)); samples = {0,0,0}; esum = 0; nsum = 0; af = 0; lr = 0; v = NULL; }; ~Evidence() { i = 0; free(e); free(n); if (samples.m) free(samples.s); v = NULL; }; void clear() { i = 0; samples.l = 0; esum = 0; nsum = 0; af = 0; lr = 0; v = NULL; }; }; class Igor : Program { public: std::string version; /////////// //options// /////////// std::string build; std::vector<std::string> input_vcf_files; std::string input_vcf_file_list; std::string output_vcf_file; std::vector<GenomeInterval> intervals; std::string interval_list; /////// //i/o// /////// BCFSyncedReader *sr; BCFOrderedWriter *odw; bcf1_t *v; /////////////// //general use// /////////////// kstring_t variant; ///////// //stats// ///////// uint32_t no_candidate_snps; uint32_t no_candidate_indels; Igor(int argc, char ** argv) { ////////////////////////// //options initialization// ////////////////////////// try { std::string desc = "Merge candidate variants across samples.\n\ Each VCF file is required to have the FORMAT flags E and N and should have exactly one sample."; version = "0.5"; TCLAP::CmdLine cmd(desc, ' ', version); VTOutput my; cmd.setOutput(&my); TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals", false, "", "str", cmd); TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "str", cmd); TCLAP::ValueArg<std::string> arg_output_vcf_file("o", "o", "output VCF file [-]", false, "-", "", cmd); TCLAP::ValueArg<std::string> arg_input_vcf_file_list("L", "L", "file containing list of input VCF files", true, "", "str", cmd); cmd.parse(argc, argv); input_vcf_file_list = arg_input_vcf_file_list.getValue(); output_vcf_file = arg_output_vcf_file.getValue(); parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue()); /////////////////////// //parse input VCF files /////////////////////// htsFile *file = hts_open(input_vcf_file_list.c_str(), "r"); if (file==NULL) { std::cerr << "cannot open " << input_vcf_file_list.c_str() << "\n"; exit(1); } kstring_t *s = &file->line; while (hts_getline(file, KS_SEP_LINE, s) >= 0) { if (s->s[0]!='#') { input_vcf_files.push_back(std::string(s->s)); } } hts_close(file); } catch (TCLAP::ArgException &e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n"; abort(); } }; void initialize() { ////////////////////// //i/o initialization// ////////////////////// sr = new BCFSyncedReader(input_vcf_files, intervals); odw = new BCFOrderedWriter(output_vcf_file, 0); bcf_hdr_append(odw->hdr, "##fileformat=VCFv4.1"); bcf_hdr_transfer_contigs(sr->hdrs[0], odw->hdr); bcf_hdr_append(odw->hdr, "##INFO=<ID=SAMPLES,Number=.,Type=String,Description=\"Samples with evidence.\">"); bcf_hdr_append(odw->hdr, "##INFO=<ID=E,Number=.,Type=Integer,Description=\"Evidence read counts for each sample\">"); bcf_hdr_append(odw->hdr, "##INFO=<ID=N,Number=.,Type=Integer,Description=\"Read counts for each sample\">"); bcf_hdr_append(odw->hdr, "##INFO=<ID=ESUM,Number=1,Type=Integer,Description=\"Total evidence read count\">"); bcf_hdr_append(odw->hdr, "##INFO=<ID=NSUM,Number=1,Type=Integer,Description=\"Total read count\">"); bcf_hdr_append(odw->hdr, "##INFO=<ID=LR,Number=1,Type=String,Description=\"Likelihood Ratio Statistic\">"); odw->write_hdr(); /////////////// //general use// /////////////// variant = {0,0,0}; //////////////////////// //stats initialization// //////////////////////// no_candidate_snps = 0; no_candidate_indels = 0; } KHASH_MAP_INIT_STR(xdict, Evidence*); void merge_candidate_variants() { khash_t(xdict) *m = kh_init(xdict); int32_t *E = (int32_t*) malloc(1*sizeof(int32_t)); int32_t *N = (int32_t*) malloc(1*sizeof(int32_t)); int32_t n = 1; int32_t nE, nN; int32_t ret; khiter_t k; int32_t nfiles = sr->get_nfiles(); double log10e = -2; //for combining the alleles std::vector<bcfptr> current_recs; while(sr->read_next_position(current_recs)) { // //for each file that contains the next record // for (uint32_t i=0; i<current_recs.size(); ++i) // { // bcf1_t *v = current_recs[i].v; // std::cerr << "\t[" << current_recs[i].file_index << "]" << v->rid << ":" << (v->pos+1) << ":" << v->d.allele[0] << ":" << v->d.allele[1]; // } // std::cerr << "\n"; //for each file that contains the next record for (uint32_t i=0; i<current_recs.size(); ++i) { int32_t file_index = current_recs[i].file_index; bcf1_t *v = current_recs[i].v; bcf_hdr_t *h = current_recs[i].h; nE = bcf_get_format_int(h, v, "E", &E, &n); nN = bcf_get_format_int(h, v, "N", &N, &n); if (nE==1 && nN==1) { //populate hash bcf_variant2string(h, v, &variant); std::cerr << variant.s << "\n"; if ((k=kh_get(xdict, m, variant.s))==kh_end(m)) { k = kh_put(xdict, m, variant.s, &ret); if (ret) //does not exist { variant = {0,0,0}; //disown allocated char* kh_value(m, k) = new Evidence(nfiles); } else { kh_value(m, k)->clear(); } bcf1_t* nv = odw->get_bcf1_from_pool(); bcf_set_chrom(odw->hdr, nv, bcf_get_chrom(h, v)); bcf_update_alleles(odw->hdr, nv, const_cast<const char**>(bcf_get_allele(v)), bcf_get_n_allele(v)); bcf_set_pos1(nv, bcf_get_pos1(v)); kh_value(m, k)->v = nv; uint32_t i = kh_value(m, k)->i; if (i) kputc(',', &kh_value(m, k)->samples); kputs(bcf_hdr_get_sample_name(h, 0), &kh_value(m, k)->samples); kh_value(m, k)->e[i] = E[0]; kh_value(m, k)->n[i] = N[0]; kh_value(m, k)->esum += E[0]; kh_value(m, k)->nsum += N[0]; kh_value(m, k)->af += ((double)E[0])/((double)N[0]); kh_value(m, k)->n += N[0]; ++kh_value(m, k)->i; // // ++no_candidate_snps; // ++no_candidate_indels; } else { uint32_t i = kh_value(m, k)->i; // if (i) kputc(',', &kh_value(m, k)->samples); // kputs(bcf_hdr_get_sample_name(h, 0), &kh_value(m, k)->samples); // kh_value(m, k)->e[i] = E[0]; // kh_value(m, k)->n[i] = N[0]; // kh_value(m, k)->esum += E[0]; // kh_value(m, k)->nsum += N[0]; // kh_value(m, k)->af += ((double)E[0])/((double)N[0]); // kh_value(m, k)->n += N[0]; // ++kh_value(m, k)->i; // // ++no_candidate_snps; // ++no_candidate_indels; } } } std::cerr << "here?\n"; //clear hash, print out aggregated records for (k = kh_begin(m); k != kh_end(m); ++k) { if (kh_exist(m, k)) { std::cerr << "VALUE OF I: " << kh_value(m, k)->i << "\n"; bcf1_t *nv = kh_value(m, k)->v; // bcf_update_info_string(odw->hdr, nv, "SAMPLES", kh_value(m, k)->samples.s); // bcf_update_info_int32(odw->hdr, nv, "E", kh_value(m, k)->e, kh_value(m, k)->i); // bcf_update_info_int32(odw->hdr, nv, "N", kh_value(m, k)->n, kh_value(m, k)->i); // bcf_update_info_int32(odw->hdr, nv, "ESUM", kh_value(m, k)->e, 1); // bcf_update_info_int32(odw->hdr, nv, "NSUM", kh_value(m, k)->e, 1); // odw->write(nv); delete kh_value(m, k); free((char*)kh_key(m, k)); } } kh_clear(xdict, m); } sr->close(); odw->close(); }; void print_options() { std::clog << "merge_candidate_variants v" << version << "\n\n"; std::clog << "options: input VCF file " << input_vcf_files.size() << " files\n"; std::clog << " [o] output VCF file " << output_vcf_file << "\n"; print_int_op(" [i] intervals ", intervals); std::clog << "\n"; } void print_stats() { std::clog << "\n"; std::cerr << "stats: Total Number of Candidate SNPs " << no_candidate_snps << "\n"; std::cerr << " Total Number of Candidate Indels " << no_candidate_indels << "\n\n"; }; ~Igor() { }; private: }; } void merge_candidate_variants(int argc, char ** argv) { Igor igor(argc, argv); igor.print_options(); igor.initialize(); igor.merge_candidate_variants(); igor.print_stats(); } <commit_msg>Included modified LRT for merge_candidate_variants.*<commit_after>/* The MIT License Copyright (c) 2013 Adrian Tan <atks@umich.edu> 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 "merge_candidate_variants.h" namespace { class Evidence { public: uint32_t i, m; uint32_t* e; uint32_t* n; kstring_t samples; int32_t esum, nsum; double af; double lr; bcf1_t *v; Evidence(uint32_t m) { this->m = m; i = 0; e = (uint32_t*) malloc(m*sizeof(uint32_t)); n = (uint32_t*) malloc(m*sizeof(uint32_t)); samples = {0,0,0}; esum = 0; nsum = 0; af = 0; lr = 0; v = NULL; }; ~Evidence() { i = 0; free(e); free(n); if (samples.m) free(samples.s); v = NULL; }; void clear() { i = 0; samples.l = 0; esum = 0; nsum = 0; af = 0; lr = 0; v = NULL; }; }; class Igor : Program { public: std::string version; /////////// //options// /////////// std::string build; std::vector<std::string> input_vcf_files; std::string input_vcf_file_list; std::string output_vcf_file; std::vector<GenomeInterval> intervals; std::string interval_list; /////// //i/o// /////// BCFSyncedReader *sr; BCFOrderedWriter *odw; bcf1_t *v; /////////////// //general use// /////////////// kstring_t variant; ///////// //stats// ///////// uint32_t no_samples; uint32_t no_candidate_snps; uint32_t no_candidate_indels; Igor(int argc, char ** argv) { ////////////////////////// //options initialization// ////////////////////////// try { std::string desc = "Merge candidate variants across samples.\n\ Each VCF file is required to have the FORMAT flags E and N and should have exactly one sample."; version = "0.5"; TCLAP::CmdLine cmd(desc, ' ', version); VTOutput my; cmd.setOutput(&my); TCLAP::ValueArg<std::string> arg_intervals("i", "i", "intervals", false, "", "str", cmd); TCLAP::ValueArg<std::string> arg_interval_list("I", "I", "file containing list of intervals []", false, "", "str", cmd); TCLAP::ValueArg<std::string> arg_output_vcf_file("o", "o", "output VCF file [-]", false, "-", "", cmd); TCLAP::ValueArg<std::string> arg_input_vcf_file_list("L", "L", "file containing list of input VCF files", true, "", "str", cmd); cmd.parse(argc, argv); input_vcf_file_list = arg_input_vcf_file_list.getValue(); output_vcf_file = arg_output_vcf_file.getValue(); parse_intervals(intervals, arg_interval_list.getValue(), arg_intervals.getValue()); /////////////////////// //parse input VCF files /////////////////////// htsFile *file = hts_open(input_vcf_file_list.c_str(), "r"); if (file==NULL) { std::cerr << "cannot open " << input_vcf_file_list.c_str() << "\n"; exit(1); } kstring_t *s = &file->line; while (hts_getline(file, KS_SEP_LINE, s) >= 0) { if (s->s[0]!='#') { input_vcf_files.push_back(std::string(s->s)); } } hts_close(file); } catch (TCLAP::ArgException &e) { std::cerr << "error: " << e.error() << " for arg " << e.argId() << "\n"; abort(); } }; void initialize() { ////////////////////// //i/o initialization// ////////////////////// sr = new BCFSyncedReader(input_vcf_files, intervals); odw = new BCFOrderedWriter(output_vcf_file, 0); bcf_hdr_append(odw->hdr, "##fileformat=VCFv4.1"); bcf_hdr_transfer_contigs(sr->hdrs[0], odw->hdr); bcf_hdr_append(odw->hdr, "##INFO=<ID=SAMPLES,Number=.,Type=String,Description=\"Samples with evidence.\">"); bcf_hdr_append(odw->hdr, "##INFO=<ID=NSAMPLES,Number=.,Type=Integer,Description=\"Number of samples.\">"); bcf_hdr_append(odw->hdr, "##INFO=<ID=E,Number=.,Type=Integer,Description=\"Evidence read counts for each sample\">"); bcf_hdr_append(odw->hdr, "##INFO=<ID=N,Number=.,Type=Integer,Description=\"Read counts for each sample\">"); bcf_hdr_append(odw->hdr, "##INFO=<ID=ESUM,Number=1,Type=Integer,Description=\"Total evidence read count\">"); bcf_hdr_append(odw->hdr, "##INFO=<ID=NSUM,Number=1,Type=Integer,Description=\"Total read count\">"); bcf_hdr_append(odw->hdr, "##INFO=<ID=AF,Number=A,Type=Float,Description=\"Allele Frequency\">"); bcf_hdr_append(odw->hdr, "##INFO=<ID=LR,Number=1,Type=String,Description=\"Likelihood Ratio Statistic\">"); odw->write_hdr(); /////////////// //general use// /////////////// variant = {0,0,0}; no_samples = sr->nfiles; //////////////////////// //stats initialization// //////////////////////// no_candidate_snps = 0; no_candidate_indels = 0; } KHASH_MAP_INIT_STR(xdict, Evidence*); void merge_candidate_variants() { khash_t(xdict) *m = kh_init(xdict); int32_t *E = (int32_t*) malloc(1*sizeof(int32_t)); int32_t *N = (int32_t*) malloc(1*sizeof(int32_t)); int32_t n = 1; int32_t nE, nN; int32_t ret; khiter_t k; int32_t nfiles = sr->get_nfiles(); double log10e = -2; //for combining the alleles std::vector<bcfptr> current_recs; while(sr->read_next_position(current_recs)) { // //for each file that contains the next record // for (uint32_t i=0; i<current_recs.size(); ++i) // { // bcf1_t *v = current_recs[i].v; // std::cerr << "\t[" << current_recs[i].file_index << "]" << v->rid << ":" << (v->pos+1) << ":" << v->d.allele[0] << ":" << v->d.allele[1]; // } // std::cerr << "\n"; //for each file that contains the next record for (uint32_t i=0; i<current_recs.size(); ++i) { int32_t file_index = current_recs[i].file_index; bcf1_t *v = current_recs[i].v; bcf_hdr_t *h = current_recs[i].h; nE = bcf_get_format_int(h, v, "E", &E, &n); nN = bcf_get_format_int(h, v, "N", &N, &n); if (nE==1 && nN==1) { //populate hash bcf_variant2string(h, v, &variant); //std::cerr << variant.s << "\n"; if ((k=kh_get(xdict, m, variant.s))==kh_end(m)) { k = kh_put(xdict, m, variant.s, &ret); if (ret) //does not exist { variant = {0,0,0}; //disown allocated char* kh_value(m, k) = new Evidence(nfiles); } else { kh_value(m, k)->clear(); } //update variant information bcf1_t* nv = odw->get_bcf1_from_pool(); bcf_clear(nv); bcf_set_chrom(odw->hdr, nv, bcf_get_chrom(h, v)); bcf_update_alleles(odw->hdr, nv, const_cast<const char**>(bcf_get_allele(v)), bcf_get_n_allele(v)); bcf_set_pos1(nv, bcf_get_pos1(v)); kh_value(m, k)->v = nv; } uint32_t i = kh_value(m, k)->i; if (i) kputc(',', &kh_value(m, k)->samples); kputs(bcf_hdr_get_sample_name(h, 0), &kh_value(m, k)->samples); kh_value(m, k)->e[i] = E[0]; kh_value(m, k)->n[i] = N[0]; kh_value(m, k)->esum += E[0]; kh_value(m, k)->nsum += N[0]; kh_value(m, k)->af += ((double)E[0])/((double)N[0]); ++kh_value(m, k)->i; // ++no_candidate_snps; // ++no_candidate_indels; } } //clear hash, print out aggregated records for (k = kh_begin(m); k != kh_end(m); ++k) { if (kh_exist(m, k)) { bcf1_t *nv = kh_value(m, k)->v; bcf_update_info_string(odw->hdr, nv, "SAMPLES", kh_value(m, k)->samples.s); bcf_update_info_int32(odw->hdr, nv, "NSAMPLES", &kh_value(m, k)->i, 1); bcf_update_info_int32(odw->hdr, nv, "E", kh_value(m, k)->e, kh_value(m, k)->i); bcf_update_info_int32(odw->hdr, nv, "N", kh_value(m, k)->n, kh_value(m, k)->i); bcf_update_info_int32(odw->hdr, nv, "ESUM", &kh_value(m, k)->esum, 1); bcf_update_info_int32(odw->hdr, nv, "NSUM", &kh_value(m, k)->nsum, 1); float af = kh_value(m, k)->af/no_samples; bcf_update_info_float(odw->hdr, nv, "AF", &af, 1); odw->write(nv); delete kh_value(m, k); free((char*)kh_key(m, k)); } } kh_clear(xdict, m); } sr->close(); odw->close(); }; void print_options() { std::clog << "merge_candidate_variants v" << version << "\n\n"; std::clog << "options: input VCF file " << input_vcf_files.size() << " files\n"; std::clog << " [o] output VCF file " << output_vcf_file << "\n"; print_int_op(" [i] intervals ", intervals); std::clog << "\n"; } void print_stats() { std::clog << "\n"; std::cerr << "stats: Total Number of Candidate SNPs " << no_candidate_snps << "\n"; std::cerr << " Total Number of Candidate Indels " << no_candidate_indels << "\n\n"; }; ~Igor() { }; private: }; } void merge_candidate_variants(int argc, char ** argv) { Igor igor(argc, argv); igor.print_options(); igor.initialize(); igor.merge_candidate_variants(); igor.print_stats(); } <|endoftext|>
<commit_before>//===--- ClosureLifetimeFixup.cpp - Fixup the lifetime of closures --------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "closure-lifetime-fixup" #include "swift/SIL/DebugUtils.h" #include "swift/SIL/InstructionUtils.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILInstruction.h" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "swift/SILOptimizer/Utils/CFG.h" #include "swift/SILOptimizer/Utils/Local.h" #include "llvm/Support/CommandLine.h" llvm::cl::opt<bool> DisableConvertEscapeToNoEscapeSwitchEnumPeephole( "sil-disable-convert-escape-to-noescape-switch-peephole", llvm::cl::init(false), llvm::cl::desc( "Disable the convert_escape_to_noescape switch enum peephole. "), llvm::cl::Hidden); using namespace swift; static SILBasicBlock *getOptionalDiamondSuccessor(SwitchEnumInst *SEI) { auto numSuccs = SEI->getNumSuccessors(); if (numSuccs != 2) return nullptr; auto *SuccSome = SEI->getCase(0).second; auto *SuccNone = SEI->getCase(1).second; if (SuccSome->args_size() != 1) std::swap(SuccSome, SuccNone); if (SuccSome->args_size() != 1 || SuccNone->args_size() != 0) return nullptr; auto *Succ = SuccSome->getSingleSuccessorBlock(); if (!Succ) return nullptr; if (SuccNone == Succ) return Succ; SuccNone = SuccNone->getSingleSuccessorBlock(); if (SuccNone == Succ) return Succ; SuccNone = SuccNone->getSingleSuccessorBlock(); if (SuccNone == Succ) return Succ; return nullptr; } /// Extend the lifetime of the convert_escape_to_noescape's operand to the end /// of the function. static void extendLifetimeToEndOfFunction(SILFunction &Fn, ConvertEscapeToNoEscapeInst *Cvt) { auto EscapingClosure = Cvt->getOperand(); auto EscapingClosureTy = EscapingClosure->getType(); auto OptionalEscapingClosureTy = SILType::getOptionalType(EscapingClosureTy); auto loc = RegularLocation::getAutoGeneratedLocation(); SILBuilderWithScope B(Cvt); auto NewCvt = B.createConvertEscapeToNoEscape( Cvt->getLoc(), Cvt->getOperand(), Cvt->getType(), false, true); Cvt->replaceAllUsesWith(NewCvt); Cvt->eraseFromParent(); Cvt = NewCvt; // Create an alloc_stack Optional<() -> ()> at the beginning of the function. AllocStackInst *Slot; auto &Context = Cvt->getModule().getASTContext(); { SILBuilderWithScope B(Fn.getEntryBlock()->begin()); Slot = B.createAllocStack(loc, OptionalEscapingClosureTy); auto *NoneDecl = Context.getOptionalNoneDecl(); // Store None to it. B.createStore( loc, B.createEnum(loc, SILValue(), NoneDecl, OptionalEscapingClosureTy), Slot, StoreOwnershipQualifier::Init); } // Insert a copy before the convert_escape_to_noescape and store it to the // alloc_stack location. { SILBuilderWithScope B(Cvt); auto *SomeDecl = Context.getOptionalSomeDecl(); B.createDestroyAddr(loc, Slot); auto ClosureCopy = B.createCopyValue(loc, EscapingClosure); B.createStore( loc, B.createEnum(loc, ClosureCopy, SomeDecl, OptionalEscapingClosureTy), Slot, StoreOwnershipQualifier::Init); } // Insert destroys at the function exits. SmallVector<SILBasicBlock *, 4> ExitingBlocks; Fn.findExitingBlocks(ExitingBlocks); for (auto *Exit : ExitingBlocks) { auto *Term = Exit->getTerminator(); SILBuilderWithScope B(Term); B.setInsertionPoint(Term); B.createDestroyAddr(loc, Slot); B.createDeallocStack(loc, Slot); } } static SILInstruction *lookThroughRebastractionUsers( SILInstruction *Inst, llvm::DenseMap<SILInstruction *, SILInstruction *> &Memoized) { // Try a cached lookup. auto Res = Memoized.find(Inst); if (Res != Memoized.end()) return Res->second; // Cache recursive results. auto memoizeResult = [&] (SILInstruction *from, SILInstruction *toResult) { Memoized[from] = toResult; return toResult; }; // If we have a convert_function, just look at its user. if (auto *Cvt = dyn_cast<ConvertFunctionInst>(Inst)) return memoizeResult(Inst, lookThroughRebastractionUsers( getSingleNonDebugUser(Cvt), Memoized)); if (auto *Cvt = dyn_cast<ConvertEscapeToNoEscapeInst>(Inst)) return memoizeResult(Inst, lookThroughRebastractionUsers( getSingleNonDebugUser(Cvt), Memoized)); // If we have a partial_apply user look at its single (non release) user. auto *PA = dyn_cast<PartialApplyInst>(Inst); if (!PA) return Inst; SILInstruction *SingleNonDebugNonRefCountUser = nullptr; for (auto *Usr : getNonDebugUses(PA)) { auto *I = Usr->getUser(); if (onlyAffectsRefCount(I)) continue; if (SingleNonDebugNonRefCountUser) { SingleNonDebugNonRefCountUser = nullptr; break; } SingleNonDebugNonRefCountUser = I; } return memoizeResult(Inst, lookThroughRebastractionUsers( SingleNonDebugNonRefCountUser, Memoized)); } static bool tryExtendLifetimeToLastUse( ConvertEscapeToNoEscapeInst *Cvt, llvm::DenseMap<SILInstruction *, SILInstruction *> &Memoized) { // Don't optimize converts that might have been escaped by the function call // (materializeForSet 'escapes' its arguments into the writeback buffer). if (Cvt->isEscapedByUser()) return false; // If there is a single user that is an apply this is simple: extend the // lifetime of the operand until after the apply. auto SingleUser = lookThroughRebastractionUsers(Cvt, Memoized); if (!SingleUser) return false; // Handle an apply. if (auto SingleApplyUser = FullApplySite::isa(SingleUser)) { // FIXME: Don't know how-to handle begin_apply/end_apply yet. if (auto *Begin = dyn_cast<BeginApplyInst>(SingleApplyUser.getInstruction())) { return false; } auto loc = RegularLocation::getAutoGeneratedLocation(); // Insert a copy at the convert_escape_to_noescape [not_guaranteed] and // change the instruction to the guaranteed form. auto EscapingClosure = Cvt->getOperand(); { SILBuilderWithScope B(Cvt); auto NewCvt = B.createConvertEscapeToNoEscape( Cvt->getLoc(), Cvt->getOperand(), Cvt->getType(), false, true); Cvt->replaceAllUsesWith(NewCvt); Cvt->eraseFromParent(); Cvt = NewCvt; } SILBuilderWithScope B2(Cvt); auto ClosureCopy = B2.createCopyValue(loc, EscapingClosure); // Insert a destroy after the apply. if (auto *Apply = dyn_cast<ApplyInst>(SingleApplyUser.getInstruction())) { auto InsertPt = std::next(SILBasicBlock::iterator(Apply)); SILBuilderWithScope B3(InsertPt); B3.createDestroyValue(loc, ClosureCopy); } else if (auto *Try = dyn_cast<TryApplyInst>(SingleApplyUser.getInstruction())) { for (auto *SuccBB : Try->getSuccessorBlocks()) { SILBuilderWithScope B3(SuccBB->begin()); B3.createDestroyValue(loc, ClosureCopy); } } else { llvm_unreachable("Unknown FullApplySite instruction kind"); } return true; } return false; } /// Ensure the lifetime of the closure accross an /// /// optional<@escaping () -> ()> to /// optional<@noescape @convention(block) () -> ()> /// /// conversion and its use. /// /// The pattern this is looking for /// switch_enum %closure /// / \ /// convert_escape_to_noescape nil /// switch_enum /// / \ /// convertToBlock nil /// \ / /// (%convertOptionalBlock :) /// We will insert a copy_value of the original %closure before the two /// diamonds. And a destroy of %closure at the last destroy of /// %convertOptionalBlock. static bool trySwitchEnumPeephole(ConvertEscapeToNoEscapeInst *Cvt) { // Don't optimize converts that might have been escaped by the function call // (materializeForSet 'escapes' its arguments into the writeback buffer). if (Cvt->isEscapedByUser()) return false; auto *blockArg = dyn_cast<SILArgument>(Cvt->getOperand()); if (!blockArg) return false; auto *PredBB = Cvt->getParent()->getSinglePredecessorBlock(); if (!PredBB) return false; auto *ConvertSuccessorBlock = Cvt->getParent()->getSingleSuccessorBlock(); if (!ConvertSuccessorBlock) return false; auto *SwitchEnum1 = dyn_cast<SwitchEnumInst>(PredBB->getTerminator()); if (!SwitchEnum1) return false; auto *DiamondSucc = getOptionalDiamondSuccessor(SwitchEnum1); if (!DiamondSucc) return false; auto *SwitchEnum2 = dyn_cast<SwitchEnumInst>(DiamondSucc->getTerminator()); if (!SwitchEnum2) return false; auto *DiamondSucc2 = getOptionalDiamondSuccessor(SwitchEnum2); if (!DiamondSucc2) return false; if (DiamondSucc2->getNumArguments() != 1) return false; // Look for the last and only destroy. SILInstruction *onlyDestroy = [&]() -> SILInstruction * { SILInstruction *lastDestroy = nullptr; for (auto *Use : DiamondSucc2->getArgument(0)->getUses()) { SILInstruction *Usr = Use->getUser(); if (isa<ReleaseValueInst>(Usr) || isa<StrongReleaseInst>(Usr) || isa<DestroyValueInst>(Usr)) { if (lastDestroy) return nullptr; lastDestroy = Usr; } } return lastDestroy; }(); if (!onlyDestroy) return false; // Replace the convert_escape_to_noescape instruction. { SILBuilderWithScope B(Cvt); auto NewCvt = B.createConvertEscapeToNoEscape( Cvt->getLoc(), Cvt->getOperand(), Cvt->getType(), false, true); Cvt->replaceAllUsesWith(NewCvt); Cvt->eraseFromParent(); Cvt = NewCvt; } // Extend the lifetime. SILBuilderWithScope B(SwitchEnum1); auto loc = RegularLocation::getAutoGeneratedLocation(); auto copy = B.createCopyValue(loc, SwitchEnum1->getOperand()); B.setInsertionPoint(onlyDestroy); B.createDestroyValue(loc, copy); return true; } static bool fixupConvertEscapeToNoEscapeLifetime(SILFunction &Fn) { bool Changed = false; // tryExtendLifetimeToLastUse uses a cache of recursive instruction use // queries. llvm::DenseMap<SILInstruction *, SILInstruction *> MemoizedQueries; for (auto &BB : Fn) { auto I = BB.begin(); while (I != BB.end()) { SILInstruction *Inst = &*I; ++I; auto *Cvt = dyn_cast<ConvertEscapeToNoEscapeInst>(Inst); if (!Cvt || Cvt->isLifetimeGuaranteed()) continue; // First try to peephole a known pattern. if (!DisableConvertEscapeToNoEscapeSwitchEnumPeephole && trySwitchEnumPeephole(Cvt)) { Changed |= true; continue; } if (tryExtendLifetimeToLastUse(Cvt, MemoizedQueries)) { Changed |= true; continue; } // Otherwise, extend the lifetime of the operand to the end of the // function. extendLifetimeToEndOfFunction(Fn, Cvt); Changed |= true; } } return Changed; } /// Fix-up the lifetime of the escaping closure argument of /// convert_escape_to_noescape [not_guaranteed] instructions. /// /// convert_escape_to_noescape [not_guaranteed] assume that someone guarantees /// the lifetime of the operand for the duration of the trivial closure result. /// SILGen does not guarantee this for '[not_guaranteed]' instructions so we /// ensure it here. namespace { class ClosureLifetimeFixup : public SILFunctionTransform { /// The entry point to the transformation. void run() override { // Don't rerun diagnostics on deserialized functions. if (getFunction()->wasDeserializedCanonical()) return; // Fixup lifetimes of optional convertEscapeToNoEscape. if (fixupConvertEscapeToNoEscapeLifetime(*getFunction())) invalidateAnalysis(SILAnalysis::InvalidationKind::FunctionBody); DEBUG(getFunction()->verify()); } }; } // end anonymous namespace SILTransform *swift::createClosureLifetimeFixup() { return new ClosureLifetimeFixup(); } <commit_msg>Add missing null check<commit_after>//===--- ClosureLifetimeFixup.cpp - Fixup the lifetime of closures --------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "closure-lifetime-fixup" #include "swift/SIL/DebugUtils.h" #include "swift/SIL/InstructionUtils.h" #include "swift/SIL/SILArgument.h" #include "swift/SIL/SILBuilder.h" #include "swift/SIL/SILInstruction.h" #include "swift/SILOptimizer/PassManager/Passes.h" #include "swift/SILOptimizer/PassManager/Transforms.h" #include "swift/SILOptimizer/Utils/CFG.h" #include "swift/SILOptimizer/Utils/Local.h" #include "llvm/Support/CommandLine.h" llvm::cl::opt<bool> DisableConvertEscapeToNoEscapeSwitchEnumPeephole( "sil-disable-convert-escape-to-noescape-switch-peephole", llvm::cl::init(false), llvm::cl::desc( "Disable the convert_escape_to_noescape switch enum peephole. "), llvm::cl::Hidden); using namespace swift; static SILBasicBlock *getOptionalDiamondSuccessor(SwitchEnumInst *SEI) { auto numSuccs = SEI->getNumSuccessors(); if (numSuccs != 2) return nullptr; auto *SuccSome = SEI->getCase(0).second; auto *SuccNone = SEI->getCase(1).second; if (SuccSome->args_size() != 1) std::swap(SuccSome, SuccNone); if (SuccSome->args_size() != 1 || SuccNone->args_size() != 0) return nullptr; auto *Succ = SuccSome->getSingleSuccessorBlock(); if (!Succ) return nullptr; if (SuccNone == Succ) return Succ; SuccNone = SuccNone->getSingleSuccessorBlock(); if (SuccNone == Succ) return Succ; SuccNone = SuccNone->getSingleSuccessorBlock(); if (SuccNone == Succ) return Succ; return nullptr; } /// Extend the lifetime of the convert_escape_to_noescape's operand to the end /// of the function. static void extendLifetimeToEndOfFunction(SILFunction &Fn, ConvertEscapeToNoEscapeInst *Cvt) { auto EscapingClosure = Cvt->getOperand(); auto EscapingClosureTy = EscapingClosure->getType(); auto OptionalEscapingClosureTy = SILType::getOptionalType(EscapingClosureTy); auto loc = RegularLocation::getAutoGeneratedLocation(); SILBuilderWithScope B(Cvt); auto NewCvt = B.createConvertEscapeToNoEscape( Cvt->getLoc(), Cvt->getOperand(), Cvt->getType(), false, true); Cvt->replaceAllUsesWith(NewCvt); Cvt->eraseFromParent(); Cvt = NewCvt; // Create an alloc_stack Optional<() -> ()> at the beginning of the function. AllocStackInst *Slot; auto &Context = Cvt->getModule().getASTContext(); { SILBuilderWithScope B(Fn.getEntryBlock()->begin()); Slot = B.createAllocStack(loc, OptionalEscapingClosureTy); auto *NoneDecl = Context.getOptionalNoneDecl(); // Store None to it. B.createStore( loc, B.createEnum(loc, SILValue(), NoneDecl, OptionalEscapingClosureTy), Slot, StoreOwnershipQualifier::Init); } // Insert a copy before the convert_escape_to_noescape and store it to the // alloc_stack location. { SILBuilderWithScope B(Cvt); auto *SomeDecl = Context.getOptionalSomeDecl(); B.createDestroyAddr(loc, Slot); auto ClosureCopy = B.createCopyValue(loc, EscapingClosure); B.createStore( loc, B.createEnum(loc, ClosureCopy, SomeDecl, OptionalEscapingClosureTy), Slot, StoreOwnershipQualifier::Init); } // Insert destroys at the function exits. SmallVector<SILBasicBlock *, 4> ExitingBlocks; Fn.findExitingBlocks(ExitingBlocks); for (auto *Exit : ExitingBlocks) { auto *Term = Exit->getTerminator(); SILBuilderWithScope B(Term); B.setInsertionPoint(Term); B.createDestroyAddr(loc, Slot); B.createDeallocStack(loc, Slot); } } static SILInstruction *lookThroughRebastractionUsers( SILInstruction *Inst, llvm::DenseMap<SILInstruction *, SILInstruction *> &Memoized) { if (Inst == nullptr) return nullptr; // Try a cached lookup. auto Res = Memoized.find(Inst); if (Res != Memoized.end()) return Res->second; // Cache recursive results. auto memoizeResult = [&] (SILInstruction *from, SILInstruction *toResult) { Memoized[from] = toResult; return toResult; }; // If we have a convert_function, just look at its user. if (auto *Cvt = dyn_cast<ConvertFunctionInst>(Inst)) return memoizeResult(Inst, lookThroughRebastractionUsers( getSingleNonDebugUser(Cvt), Memoized)); if (auto *Cvt = dyn_cast<ConvertEscapeToNoEscapeInst>(Inst)) return memoizeResult(Inst, lookThroughRebastractionUsers( getSingleNonDebugUser(Cvt), Memoized)); // If we have a partial_apply user look at its single (non release) user. auto *PA = dyn_cast<PartialApplyInst>(Inst); if (!PA) return Inst; SILInstruction *SingleNonDebugNonRefCountUser = nullptr; for (auto *Usr : getNonDebugUses(PA)) { auto *I = Usr->getUser(); if (onlyAffectsRefCount(I)) continue; if (SingleNonDebugNonRefCountUser) { SingleNonDebugNonRefCountUser = nullptr; break; } SingleNonDebugNonRefCountUser = I; } return memoizeResult(Inst, lookThroughRebastractionUsers( SingleNonDebugNonRefCountUser, Memoized)); } static bool tryExtendLifetimeToLastUse( ConvertEscapeToNoEscapeInst *Cvt, llvm::DenseMap<SILInstruction *, SILInstruction *> &Memoized) { // Don't optimize converts that might have been escaped by the function call // (materializeForSet 'escapes' its arguments into the writeback buffer). if (Cvt->isEscapedByUser()) return false; // If there is a single user that is an apply this is simple: extend the // lifetime of the operand until after the apply. auto SingleUser = lookThroughRebastractionUsers(Cvt, Memoized); if (!SingleUser) return false; // Handle an apply. if (auto SingleApplyUser = FullApplySite::isa(SingleUser)) { // FIXME: Don't know how-to handle begin_apply/end_apply yet. if (auto *Begin = dyn_cast<BeginApplyInst>(SingleApplyUser.getInstruction())) { return false; } auto loc = RegularLocation::getAutoGeneratedLocation(); // Insert a copy at the convert_escape_to_noescape [not_guaranteed] and // change the instruction to the guaranteed form. auto EscapingClosure = Cvt->getOperand(); { SILBuilderWithScope B(Cvt); auto NewCvt = B.createConvertEscapeToNoEscape( Cvt->getLoc(), Cvt->getOperand(), Cvt->getType(), false, true); Cvt->replaceAllUsesWith(NewCvt); Cvt->eraseFromParent(); Cvt = NewCvt; } SILBuilderWithScope B2(Cvt); auto ClosureCopy = B2.createCopyValue(loc, EscapingClosure); // Insert a destroy after the apply. if (auto *Apply = dyn_cast<ApplyInst>(SingleApplyUser.getInstruction())) { auto InsertPt = std::next(SILBasicBlock::iterator(Apply)); SILBuilderWithScope B3(InsertPt); B3.createDestroyValue(loc, ClosureCopy); } else if (auto *Try = dyn_cast<TryApplyInst>(SingleApplyUser.getInstruction())) { for (auto *SuccBB : Try->getSuccessorBlocks()) { SILBuilderWithScope B3(SuccBB->begin()); B3.createDestroyValue(loc, ClosureCopy); } } else { llvm_unreachable("Unknown FullApplySite instruction kind"); } return true; } return false; } /// Ensure the lifetime of the closure accross an /// /// optional<@escaping () -> ()> to /// optional<@noescape @convention(block) () -> ()> /// /// conversion and its use. /// /// The pattern this is looking for /// switch_enum %closure /// / \ /// convert_escape_to_noescape nil /// switch_enum /// / \ /// convertToBlock nil /// \ / /// (%convertOptionalBlock :) /// We will insert a copy_value of the original %closure before the two /// diamonds. And a destroy of %closure at the last destroy of /// %convertOptionalBlock. static bool trySwitchEnumPeephole(ConvertEscapeToNoEscapeInst *Cvt) { // Don't optimize converts that might have been escaped by the function call // (materializeForSet 'escapes' its arguments into the writeback buffer). if (Cvt->isEscapedByUser()) return false; auto *blockArg = dyn_cast<SILArgument>(Cvt->getOperand()); if (!blockArg) return false; auto *PredBB = Cvt->getParent()->getSinglePredecessorBlock(); if (!PredBB) return false; auto *ConvertSuccessorBlock = Cvt->getParent()->getSingleSuccessorBlock(); if (!ConvertSuccessorBlock) return false; auto *SwitchEnum1 = dyn_cast<SwitchEnumInst>(PredBB->getTerminator()); if (!SwitchEnum1) return false; auto *DiamondSucc = getOptionalDiamondSuccessor(SwitchEnum1); if (!DiamondSucc) return false; auto *SwitchEnum2 = dyn_cast<SwitchEnumInst>(DiamondSucc->getTerminator()); if (!SwitchEnum2) return false; auto *DiamondSucc2 = getOptionalDiamondSuccessor(SwitchEnum2); if (!DiamondSucc2) return false; if (DiamondSucc2->getNumArguments() != 1) return false; // Look for the last and only destroy. SILInstruction *onlyDestroy = [&]() -> SILInstruction * { SILInstruction *lastDestroy = nullptr; for (auto *Use : DiamondSucc2->getArgument(0)->getUses()) { SILInstruction *Usr = Use->getUser(); if (isa<ReleaseValueInst>(Usr) || isa<StrongReleaseInst>(Usr) || isa<DestroyValueInst>(Usr)) { if (lastDestroy) return nullptr; lastDestroy = Usr; } } return lastDestroy; }(); if (!onlyDestroy) return false; // Replace the convert_escape_to_noescape instruction. { SILBuilderWithScope B(Cvt); auto NewCvt = B.createConvertEscapeToNoEscape( Cvt->getLoc(), Cvt->getOperand(), Cvt->getType(), false, true); Cvt->replaceAllUsesWith(NewCvt); Cvt->eraseFromParent(); Cvt = NewCvt; } // Extend the lifetime. SILBuilderWithScope B(SwitchEnum1); auto loc = RegularLocation::getAutoGeneratedLocation(); auto copy = B.createCopyValue(loc, SwitchEnum1->getOperand()); B.setInsertionPoint(onlyDestroy); B.createDestroyValue(loc, copy); return true; } static bool fixupConvertEscapeToNoEscapeLifetime(SILFunction &Fn) { bool Changed = false; // tryExtendLifetimeToLastUse uses a cache of recursive instruction use // queries. llvm::DenseMap<SILInstruction *, SILInstruction *> MemoizedQueries; for (auto &BB : Fn) { auto I = BB.begin(); while (I != BB.end()) { SILInstruction *Inst = &*I; ++I; auto *Cvt = dyn_cast<ConvertEscapeToNoEscapeInst>(Inst); if (!Cvt || Cvt->isLifetimeGuaranteed()) continue; // First try to peephole a known pattern. if (!DisableConvertEscapeToNoEscapeSwitchEnumPeephole && trySwitchEnumPeephole(Cvt)) { Changed |= true; continue; } if (tryExtendLifetimeToLastUse(Cvt, MemoizedQueries)) { Changed |= true; continue; } // Otherwise, extend the lifetime of the operand to the end of the // function. extendLifetimeToEndOfFunction(Fn, Cvt); Changed |= true; } } return Changed; } /// Fix-up the lifetime of the escaping closure argument of /// convert_escape_to_noescape [not_guaranteed] instructions. /// /// convert_escape_to_noescape [not_guaranteed] assume that someone guarantees /// the lifetime of the operand for the duration of the trivial closure result. /// SILGen does not guarantee this for '[not_guaranteed]' instructions so we /// ensure it here. namespace { class ClosureLifetimeFixup : public SILFunctionTransform { /// The entry point to the transformation. void run() override { // Don't rerun diagnostics on deserialized functions. if (getFunction()->wasDeserializedCanonical()) return; // Fixup lifetimes of optional convertEscapeToNoEscape. if (fixupConvertEscapeToNoEscapeLifetime(*getFunction())) invalidateAnalysis(SILAnalysis::InvalidationKind::FunctionBody); DEBUG(getFunction()->verify()); } }; } // end anonymous namespace SILTransform *swift::createClosureLifetimeFixup() { return new ClosureLifetimeFixup(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: drwtrans.hxx,v $ * * $Revision: 1.11 $ * * last change: $Author: kz $ $Date: 2004-10-04 20:17:27 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifndef SC_DRWTRANS_HXX #define SC_DRWTRANS_HXX #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_ #include <com/sun/star/embed/XEmbeddedObject.hxx> #endif #ifndef _TRANSFER_HXX #include <svtools/transfer.hxx> #endif //REMOVE #ifndef _IPOBJ_HXX //REMOVE #include <so3/ipobj.hxx> //REMOVE #endif #include <sfx2/objsh.hxx> #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif class SdrModel; class ScDocShell; class INetBookmark; class SdrObject; class SdrView; class ScDrawView; class ScDrawTransferObj : public TransferableHelper { private: SdrModel* pModel; TransferableDataHelper aOleData; TransferableObjectDescriptor aObjDesc; //REMOVE SvEmbeddedObjectRef aDocShellRef; //REMOVE SvEmbeddedObjectRef aDrawPersistRef; SfxObjectShellRef aDocShellRef; SfxObjectShellRef aDrawPersistRef; // extracted from model in ctor: Size aSrcSize; INetBookmark* pBookmark; BOOL bGraphic; BOOL bGrIsBit; BOOL bOleObj; // source information for drag&drop: // (view is needed to handle drawing obejcts) SdrView* pDragSourceView; USHORT nDragSourceFlags; BOOL bDragWasInternal; sal_uInt32 nSourceDocID; void InitDocShell(); //REMOVE SvInPlaceObjectRef GetSingleObject(); ::com::sun::star::uno::Reference< ::com::sun::star::embed::XEmbeddedObject > GetSingleObject(); public: ScDrawTransferObj( SdrModel* pClipModel, ScDocShell* pContainerShell, const TransferableObjectDescriptor& rDesc ); virtual ~ScDrawTransferObj(); virtual void AddSupportedFormats(); virtual sal_Bool GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual sal_Bool WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual void ObjectReleased(); virtual void DragFinished( sal_Int8 nDropAction ); SdrModel* GetModel() { return pModel; } void SetDrawPersist( const SfxObjectShellRef& rRef ); void SetDragSource( ScDrawView* pView ); void SetDragSourceObj( SdrObject* pObj, SCTAB nTab ); void SetDragSourceFlags( USHORT nFlags ); void SetDragWasInternal(); SdrView* GetDragSourceView() { return pDragSourceView; } USHORT GetDragSourceFlags() const { return nDragSourceFlags; } void SetSourceDocID( sal_uInt32 nVal ) { nSourceDocID = nVal; } sal_uInt32 GetSourceDocID() const { return nSourceDocID; } static ScDrawTransferObj* GetOwnClipboard( Window* pUIWin ); }; #endif <commit_msg>INTEGRATION: CWS ooo19126 (1.11.326); FILE MERGED 2005/09/05 15:05:19 rt 1.11.326.1: #i54170# Change license header: remove SISSL<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: drwtrans.hxx,v $ * * $Revision: 1.12 $ * * last change: $Author: rt $ $Date: 2005-09-08 21:23:08 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SC_DRWTRANS_HXX #define SC_DRWTRANS_HXX #ifndef _COM_SUN_STAR_UNO_REFERENCE_HXX_ #include <com/sun/star/uno/Reference.hxx> #endif #ifndef _COM_SUN_STAR_EMBED_XEMBEDDEDOBJECT_HPP_ #include <com/sun/star/embed/XEmbeddedObject.hxx> #endif #ifndef _TRANSFER_HXX #include <svtools/transfer.hxx> #endif //REMOVE #ifndef _IPOBJ_HXX //REMOVE #include <so3/ipobj.hxx> //REMOVE #endif #include <sfx2/objsh.hxx> #ifndef SC_SCGLOB_HXX #include "global.hxx" #endif class SdrModel; class ScDocShell; class INetBookmark; class SdrObject; class SdrView; class ScDrawView; class ScDrawTransferObj : public TransferableHelper { private: SdrModel* pModel; TransferableDataHelper aOleData; TransferableObjectDescriptor aObjDesc; //REMOVE SvEmbeddedObjectRef aDocShellRef; //REMOVE SvEmbeddedObjectRef aDrawPersistRef; SfxObjectShellRef aDocShellRef; SfxObjectShellRef aDrawPersistRef; // extracted from model in ctor: Size aSrcSize; INetBookmark* pBookmark; BOOL bGraphic; BOOL bGrIsBit; BOOL bOleObj; // source information for drag&drop: // (view is needed to handle drawing obejcts) SdrView* pDragSourceView; USHORT nDragSourceFlags; BOOL bDragWasInternal; sal_uInt32 nSourceDocID; void InitDocShell(); //REMOVE SvInPlaceObjectRef GetSingleObject(); ::com::sun::star::uno::Reference< ::com::sun::star::embed::XEmbeddedObject > GetSingleObject(); public: ScDrawTransferObj( SdrModel* pClipModel, ScDocShell* pContainerShell, const TransferableObjectDescriptor& rDesc ); virtual ~ScDrawTransferObj(); virtual void AddSupportedFormats(); virtual sal_Bool GetData( const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual sal_Bool WriteObject( SotStorageStreamRef& rxOStm, void* pUserObject, sal_uInt32 nUserObjectId, const ::com::sun::star::datatransfer::DataFlavor& rFlavor ); virtual void ObjectReleased(); virtual void DragFinished( sal_Int8 nDropAction ); SdrModel* GetModel() { return pModel; } void SetDrawPersist( const SfxObjectShellRef& rRef ); void SetDragSource( ScDrawView* pView ); void SetDragSourceObj( SdrObject* pObj, SCTAB nTab ); void SetDragSourceFlags( USHORT nFlags ); void SetDragWasInternal(); SdrView* GetDragSourceView() { return pDragSourceView; } USHORT GetDragSourceFlags() const { return nDragSourceFlags; } void SetSourceDocID( sal_uInt32 nVal ) { nSourceDocID = nVal; } sal_uInt32 GetSourceDocID() const { return nSourceDocID; } static ScDrawTransferObj* GetOwnClipboard( Window* pUIWin ); }; #endif <|endoftext|>
<commit_before><commit_msg>fdo#75032: Skip notes when copying values from undo document.<commit_after><|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/io/vtk_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/surface/mls.h> #include <pcl/surface/gp3.h> #include <pcl/surface/grid_projection.h> using namespace pcl; using namespace pcl::io; using namespace std; typedef KdTree<PointXYZ>::Ptr KdTreePtr; PointCloud<PointXYZ>::Ptr cloud (new PointCloud<PointXYZ> ()); boost::shared_ptr<vector<int> > indices (new vector<int>); KdTreePtr tree; /* ---[ */ int main (int argc, char** argv) { // Input assert(argc > 1); char* file_name = argv[1]; sensor_msgs::PointCloud2 cloud_blob; loadPCDFile (file_name, cloud_blob); fromROSMsg (cloud_blob, *cloud); // Indices indices->resize (cloud->points.size ()); for (size_t i = 0; i < indices->size (); ++i) { (*indices)[i] = i; } // KD-Tree tree.reset (new KdTreeFLANN<PointXYZ>); tree->setInputCloud (cloud); // Init objects PointCloud<PointXYZ> mls_points; PointCloud<Normal>::Ptr mls_normals (new PointCloud<Normal> ()); MovingLeastSquares<PointXYZ, Normal> mls; // Set parameters mls.setInputCloud (cloud); mls.setIndices (indices); mls.setPolynomialFit (true); mls.setSearchMethod (tree); mls.setSearchRadius (0.03); // Reconstruct mls.setOutputNormals (mls_normals); mls.reconstruct (mls_points); PointCloud<PointNormal> mls_cloud; pcl::concatenateFields (mls_points, *mls_normals, mls_cloud); // Save output savePCDFile ("./test/bun0-mls.pcd", mls_cloud); // Test triangulation std::cerr << "TESTING TRIANGULATION" << std::endl; KdTree<PointNormal>::Ptr tree2 (new KdTreeFLANN<PointNormal>); tree2->setInputCloud (mls_cloud.makeShared ()); PolygonMesh triangles; // Initialize object GridProjection<PointNormal> gp3; gp3.setResolution (0.005); gp3.setPaddingSize (3); // GreedyProjectionTriangulation<PointNormal> gp3; // gp3.setSearchRadius (0.025); // gp3.setMu (2.5); // gp3.setMaximumNearestNeighbors (100); // gp3.setMaximumSurfaceAgle(M_PI/4); // 45 degrees // gp3.setMinimumAngle(M_PI/18); // 10 degrees // gp3.setMaximumAngle(2*M_PI/3); // 120 degrees // gp3.setNormalConsistency(false); // Get result gp3.setInputCloud (mls_cloud.makeShared ()); gp3.setSearchMethod (tree2); gp3.reconstruct (triangles); saveVTKFile ("./test/bun0-mls.vtk", triangles); //std::cerr << "INPUT: ./test/bun0-mls.pcd" << std::endl; std::cerr << "OUTPUT: ./test/bun0-mls.vtk" << std::endl; // Finish return (0); } /* ]--- */ <commit_msg>nicer example code for reconstruction methods<commit_after>/* * Software License Agreement (BSD License) * * Copyright (c) 2010, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #include <pcl/point_types.h> #include <pcl/io/pcd_io.h> #include <pcl/io/vtk_io.h> #include <pcl/kdtree/kdtree_flann.h> #include <pcl/surface/mls.h> #include <pcl/surface/gp3.h> #include <pcl/surface/grid_projection.h> using namespace pcl; using namespace pcl::io; using namespace std; typedef KdTree<PointXYZ>::Ptr KdTreePtr; PointCloud<PointXYZ>::Ptr cloud (new PointCloud<PointXYZ> ()); boost::shared_ptr<vector<int> > indices (new vector<int>); KdTreePtr tree; /* ---[ */ int main (int argc, char** argv) { // Input assert(argc > 1); char* file_name = argv[1]; sensor_msgs::PointCloud2 cloud_blob; loadPCDFile (file_name, cloud_blob); fromROSMsg (cloud_blob, *cloud); // Indices indices->resize (cloud->points.size ()); for (size_t i = 0; i < indices->size (); ++i) { (*indices)[i] = i; } // KD-Tree tree.reset (new KdTreeFLANN<PointXYZ>); tree->setInputCloud (cloud); // Init objects PointCloud<PointXYZ> mls_points; PointCloud<Normal>::Ptr mls_normals (new PointCloud<Normal> ()); MovingLeastSquares<PointXYZ, Normal> mls; // Set parameters mls.setInputCloud (cloud); mls.setIndices (indices); mls.setPolynomialFit (true); mls.setSearchMethod (tree); mls.setSearchRadius (0.03); // Reconstruct mls.setOutputNormals (mls_normals); mls.reconstruct (mls_points); // Save output PointCloud<PointNormal>::Ptr mls_cloud (new PointCloud<PointNormal> ()); pcl::concatenateFields (mls_points, *mls_normals, *mls_cloud); savePCDFile ("./test/bun0-mls.pcd", *mls_cloud); // Test triangulation std::cerr << "TESTING TRIANGULATION" << std::endl; KdTree<PointNormal>::Ptr tree2 (new KdTreeFLANN<PointNormal>); tree2->setInputCloud (mls_cloud); PolygonMesh triangles; PolygonMesh grid; // Initialize object GreedyProjectionTriangulation<PointNormal> gp3; gp3.setSearchRadius (0.025); gp3.setMu (2.5); gp3.setMaximumNearestNeighbors (100); gp3.setMaximumSurfaceAgle(M_PI/4); // 45 degrees gp3.setMinimumAngle(M_PI/18); // 10 degrees gp3.setMaximumAngle(2*M_PI/3); // 120 degrees gp3.setNormalConsistency(false); // Get result gp3.setInputCloud (mls_cloud); gp3.setSearchMethod (tree2); gp3.reconstruct (triangles); saveVTKFile ("./test/bun0-mls-triangles.vtk", triangles); //std::cerr << "INPUT: ./test/bun0-mls.pcd" << std::endl; std::cerr << "OUTPUT: ./test/bun0-mls-triangles.vtk" << std::endl; // Initialize object GridProjection<PointNormal> gp; gp.setResolution (0.005); gp.setPaddingSize (3); // Get result gp.setInputCloud (mls_cloud); gp.setSearchMethod (tree2); gp.reconstruct (grid); saveVTKFile ("./test/bun0-mls-grid.vtk", grid); //std::cerr << "INPUT: ./test/bun0-mls.pcd" << std::endl; std::cerr << "OUTPUT: ./test/bun0-mls-grid.vtk" << std::endl; // Finish return (0); } /* ]--- */ <|endoftext|>
<commit_before>#include <memory> #include <Eigen/Sparse> #include <Eigen/Core> #include <SmurffCpp/Utils/counters.h> #include <SmurffCpp/Utils/RootFile.h> #include <SmurffCpp/Utils/MatrixUtils.h> #include <SmurffCpp/result.h> #include <SmurffCpp/ResultItem.h> #include <SmurffCpp/Model.h> #include <SmurffCpp/Predict/PredictSession.h> namespace smurff { PredictSession::PredictSession(std::shared_ptr<RootFile> rf) : m_model_rootfile(rf), m_pred_rootfile(0), m_has_config(false), m_num_latent(-1), m_dims(PVec<>(0)), m_is_init(false) { m_stepfiles = m_model_rootfile->openSampleStepFiles(); } PredictSession::PredictSession(std::shared_ptr<RootFile> rf, const Config &config) : m_model_rootfile(rf), m_pred_rootfile(0), m_config(config), m_has_config(true), m_num_latent(-1), m_dims(PVec<>(0)), m_is_init(false) { m_stepfiles = m_model_rootfile->openSampleStepFiles(); } PredictSession::PredictSession(const Config &config) : m_pred_rootfile(0), m_config(config), m_has_config(true), m_num_latent(-1), m_dims(PVec<>(0)), m_is_init(false) { THROWERROR_ASSERT(config.getRootName().size()) m_model_rootfile = std::make_shared<RootFile>(config.getRootName()); m_stepfiles = m_model_rootfile->openSampleStepFiles(); } void PredictSession::run() { THROWERROR_ASSERT(m_has_config); std::vector<std::shared_ptr<Eigen::MatrixXd>> predictions; std::shared_ptr<MatrixConfig> side_info; int mode; if (m_config.getTest()) { init(); while (step()) ; return; } else if (m_config.getRowFeatures()) { side_info = m_config.getRowFeatures(); mode = 0; } else if (m_config.getColFeatures()) { side_info = m_config.getColFeatures(); mode = 1; } else { THROWERROR("Need either test, row features or col features") } if (side_info->isDense()) { auto dense_matrix = matrix_utils::dense_to_eigen(*side_info); predictions = predict(mode, dense_matrix); } else { auto sparse_matrix = matrix_utils::sparse_to_eigen(*side_info); predictions = predict(mode, sparse_matrix); } } void PredictSession::init() { THROWERROR_ASSERT(m_has_config); THROWERROR_ASSERT(m_config.getTest()); m_result = std::make_shared<Result>(m_config.getTest(), m_config.getNSamples()); m_pos = m_stepfiles.rbegin(); m_iter = 0; m_is_init = true; THROWERROR_ASSERT_MSG(m_config.getSavePrefix() != getModelRoot()->getPrefix(), "Cannot have same prefix for model and predictions - both have " + m_config.getSavePrefix()); if (m_config.getSaveFreq()) { // create root file m_pred_rootfile = std::make_shared<RootFile>(m_config.getSavePrefix(), m_config.getSaveExtension(), true); m_pred_rootfile->createCsvStatusFile(); m_pred_rootfile->flushLast(); } if (m_config.getVerbose()) info(std::cout, ""); } bool PredictSession::step() { THROWERROR_ASSERT(m_has_config); THROWERROR_ASSERT(m_is_init); THROWERROR_ASSERT(m_pos != m_stepfiles.rend()); double start = tick(); auto model = restoreModel(*m_pos); m_result->update(model, false); double stop = tick(); m_iter++; m_secs_per_iter = stop - start; m_secs_total += m_secs_per_iter; if (m_config.getVerbose()) std::cout << getStatus()->asString() << std::endl; if (m_config.getSaveFreq() > 0 && (m_iter % m_config.getSaveFreq()) == 0) save(); auto next_pos = m_pos; next_pos++; bool last_iter = next_pos == m_stepfiles.rend(); //save last iter if (last_iter && m_config.getSaveFreq() == -1) save(); m_pos++; return !last_iter; } void PredictSession::save() { //save this iteration std::shared_ptr<StepFile> stepFile = getRootFile()->createSampleStepFile(m_iter); if (m_config.getVerbose()) { std::cout << "-- Saving predictions into '" << stepFile->getStepFileName() << "'." << std::endl; } stepFile->savePred(m_result); m_pred_rootfile->addCsvStatusLine(*getStatus()); m_pred_rootfile->flushLast(); } std::shared_ptr<StatusItem> PredictSession::getStatus() const { std::shared_ptr<StatusItem> ret = std::make_shared<StatusItem>(); ret->phase = "Predict"; ret->iter = (*m_pos)->getIsample(); ret->phase_iter = m_stepfiles.size(); ret->train_rmse = NAN; ret->rmse_avg = m_result->rmse_avg; ret->rmse_1sample = m_result->rmse_1sample; ret->auc_avg = m_result->auc_avg; ret->auc_1sample = m_result->auc_1sample; ret->elapsed_iter = m_secs_per_iter; ret->elapsed_total = m_secs_total; return ret; } std::shared_ptr<Result> PredictSession::getResult() const { return m_result; } std::ostream &PredictSession::info(std::ostream &os, std::string indent) const { os << indent << "PredictSession {\n"; os << indent << " Model {\n"; os << indent << " model root-file: " << getModelRoot()->getFullPath() << "\n"; os << indent << " num-samples: " << getNumSteps() << "\n"; os << indent << " num-latent: " << getNumLatent() << "\n"; os << indent << " dimensions: " << getModelDims() << "\n"; os << indent << " }\n"; os << indent << " Predictions {\n"; m_result->info(os, indent + " "); if (m_config.getSaveFreq() > 0) { os << indent << " Save predictions: every " << m_config.getSaveFreq() << " iteration\n"; os << indent << " Save extension: " << m_config.getSaveExtension() << "\n"; os << indent << " Output root-file: " << getRootFile()->getFullPath() << "\n"; } else if (m_config.getSaveFreq() < 0) { os << indent << " Save predictions after last iteration\n"; os << indent << " Save extension: " << m_config.getSaveExtension() << "\n"; os << indent << " Output root-file: " << getRootFile()->getFullPath() << "\n"; } else { os << indent << " Don't save predictions\n"; } os << indent << " }" << std::endl; os << indent << "}\n"; return os; } std::shared_ptr<Model> PredictSession::restoreModel(const std::shared_ptr<StepFile> &sf) { auto model = sf->restoreModel(); if (m_num_latent <= 0) { m_num_latent = model->nlatent(); m_dims = model->getDims(); } else { THROWERROR_ASSERT(m_num_latent == model->nlatent()); THROWERROR_ASSERT(m_dims == model->getDims()); } THROWERROR_ASSERT(m_num_latent > 0); return model; } std::shared_ptr<Model> PredictSession::restoreModel(int i) { return restoreModel(m_stepfiles.at(i)); } // predict one element ResultItem PredictSession::predict(PVec<> pos, const StepFile &sf) { ResultItem ret{pos}; predict(ret, sf); return ret; } // predict one element void PredictSession::predict(ResultItem &res, const StepFile &sf) { auto model = sf.restoreModel(); auto pred = model->predict(res.coords); res.update(pred); } // predict one element void PredictSession::predict(ResultItem &res) { auto stepfiles = getModelRoot()->openSampleStepFiles(); for (const auto &sf : stepfiles) predict(res, *sf); } ResultItem PredictSession::predict(PVec<> pos) { ResultItem ret{pos}; predict(ret); return ret; } // predict all elements in Ytest std::shared_ptr<Result> PredictSession::predict(std::shared_ptr<TensorConfig> Y) { auto res = std::make_shared<Result>(Y); for (const auto s : m_stepfiles) { auto model = restoreModel(s); res->update(model, false); } return res; } } // end namespace smurff <commit_msg>Second step to out-of-matrix predictions in smurff command line verison<commit_after>#include <memory> #include <Eigen/Sparse> #include <Eigen/Core> #include <SmurffCpp/Utils/counters.h> #include <SmurffCpp/Utils/RootFile.h> #include <SmurffCpp/Utils/MatrixUtils.h> #include <SmurffCpp/IO/MatrixIO.h> #include <SmurffCpp/result.h> #include <SmurffCpp/ResultItem.h> #include <SmurffCpp/Model.h> #include <SmurffCpp/Predict/PredictSession.h> namespace smurff { PredictSession::PredictSession(std::shared_ptr<RootFile> rf) : m_model_rootfile(rf), m_pred_rootfile(0), m_has_config(false), m_num_latent(-1), m_dims(PVec<>(0)), m_is_init(false) { m_stepfiles = m_model_rootfile->openSampleStepFiles(); } PredictSession::PredictSession(std::shared_ptr<RootFile> rf, const Config &config) : m_model_rootfile(rf), m_pred_rootfile(0), m_config(config), m_has_config(true), m_num_latent(-1), m_dims(PVec<>(0)), m_is_init(false) { m_stepfiles = m_model_rootfile->openSampleStepFiles(); } PredictSession::PredictSession(const Config &config) : m_pred_rootfile(0), m_config(config), m_has_config(true), m_num_latent(-1), m_dims(PVec<>(0)), m_is_init(false) { THROWERROR_ASSERT(config.getRootName().size()) m_model_rootfile = std::make_shared<RootFile>(config.getRootName()); m_stepfiles = m_model_rootfile->openSampleStepFiles(); } void PredictSession::run() { THROWERROR_ASSERT(m_has_config); std::vector<std::shared_ptr<Eigen::MatrixXd>> predictions; std::shared_ptr<MatrixConfig> side_info; int mode; if (m_config.getTest()) { init(); while (step()) ; return; } else if (m_config.getRowFeatures()) { side_info = m_config.getRowFeatures(); mode = 0; } else if (m_config.getColFeatures()) { side_info = m_config.getColFeatures(); mode = 1; } else { THROWERROR("Need either test, row features or col features") } if (side_info->isDense()) { auto dense_matrix = matrix_utils::dense_to_eigen(*side_info); predictions = predict(mode, dense_matrix); } else { auto sparse_matrix = matrix_utils::sparse_to_eigen(*side_info); predictions = predict(mode, sparse_matrix); } int i = 0; for (auto p : predictions) { auto filename = m_config.getSavePrefix() + "/predictions-sample-" + std::to_string(i) + m_config.getSaveExtension(); if (m_config.getVerbose()) { std::cout << "-- Saving sample '" << i << " to " << filename << "." << std::endl; } matrix_io::eigen::write_matrix(filename, *p); ++i; } } void PredictSession::init() { THROWERROR_ASSERT(m_has_config); THROWERROR_ASSERT(m_config.getTest()); m_result = std::make_shared<Result>(m_config.getTest(), m_config.getNSamples()); m_pos = m_stepfiles.rbegin(); m_iter = 0; m_is_init = true; THROWERROR_ASSERT_MSG(m_config.getSavePrefix() != getModelRoot()->getPrefix(), "Cannot have same prefix for model and predictions - both have " + m_config.getSavePrefix()); if (m_config.getSaveFreq()) { // create root file m_pred_rootfile = std::make_shared<RootFile>(m_config.getSavePrefix(), m_config.getSaveExtension(), true); m_pred_rootfile->createCsvStatusFile(); m_pred_rootfile->flushLast(); } if (m_config.getVerbose()) info(std::cout, ""); } bool PredictSession::step() { THROWERROR_ASSERT(m_has_config); THROWERROR_ASSERT(m_is_init); THROWERROR_ASSERT(m_pos != m_stepfiles.rend()); double start = tick(); auto model = restoreModel(*m_pos); m_result->update(model, false); double stop = tick(); m_iter++; m_secs_per_iter = stop - start; m_secs_total += m_secs_per_iter; if (m_config.getVerbose()) std::cout << getStatus()->asString() << std::endl; if (m_config.getSaveFreq() > 0 && (m_iter % m_config.getSaveFreq()) == 0) save(); auto next_pos = m_pos; next_pos++; bool last_iter = next_pos == m_stepfiles.rend(); //save last iter if (last_iter && m_config.getSaveFreq() == -1) save(); m_pos++; return !last_iter; } void PredictSession::save() { //save this iteration std::shared_ptr<StepFile> stepFile = getRootFile()->createSampleStepFile(m_iter); if (m_config.getVerbose()) { std::cout << "-- Saving predictions into '" << stepFile->getStepFileName() << "'." << std::endl; } stepFile->savePred(m_result); m_pred_rootfile->addCsvStatusLine(*getStatus()); m_pred_rootfile->flushLast(); } std::shared_ptr<StatusItem> PredictSession::getStatus() const { std::shared_ptr<StatusItem> ret = std::make_shared<StatusItem>(); ret->phase = "Predict"; ret->iter = (*m_pos)->getIsample(); ret->phase_iter = m_stepfiles.size(); ret->train_rmse = NAN; ret->rmse_avg = m_result->rmse_avg; ret->rmse_1sample = m_result->rmse_1sample; ret->auc_avg = m_result->auc_avg; ret->auc_1sample = m_result->auc_1sample; ret->elapsed_iter = m_secs_per_iter; ret->elapsed_total = m_secs_total; return ret; } std::shared_ptr<Result> PredictSession::getResult() const { return m_result; } std::ostream &PredictSession::info(std::ostream &os, std::string indent) const { os << indent << "PredictSession {\n"; os << indent << " Model {\n"; os << indent << " model root-file: " << getModelRoot()->getFullPath() << "\n"; os << indent << " num-samples: " << getNumSteps() << "\n"; os << indent << " num-latent: " << getNumLatent() << "\n"; os << indent << " dimensions: " << getModelDims() << "\n"; os << indent << " }\n"; os << indent << " Predictions {\n"; m_result->info(os, indent + " "); if (m_config.getSaveFreq() > 0) { os << indent << " Save predictions: every " << m_config.getSaveFreq() << " iteration\n"; os << indent << " Save extension: " << m_config.getSaveExtension() << "\n"; os << indent << " Output root-file: " << getRootFile()->getFullPath() << "\n"; } else if (m_config.getSaveFreq() < 0) { os << indent << " Save predictions after last iteration\n"; os << indent << " Save extension: " << m_config.getSaveExtension() << "\n"; os << indent << " Output root-file: " << getRootFile()->getFullPath() << "\n"; } else { os << indent << " Don't save predictions\n"; } os << indent << " }" << std::endl; os << indent << "}\n"; return os; } std::shared_ptr<Model> PredictSession::restoreModel(const std::shared_ptr<StepFile> &sf) { auto model = sf->restoreModel(); if (m_num_latent <= 0) { m_num_latent = model->nlatent(); m_dims = model->getDims(); } else { THROWERROR_ASSERT(m_num_latent == model->nlatent()); THROWERROR_ASSERT(m_dims == model->getDims()); } THROWERROR_ASSERT(m_num_latent > 0); return model; } std::shared_ptr<Model> PredictSession::restoreModel(int i) { return restoreModel(m_stepfiles.at(i)); } // predict one element ResultItem PredictSession::predict(PVec<> pos, const StepFile &sf) { ResultItem ret{pos}; predict(ret, sf); return ret; } // predict one element void PredictSession::predict(ResultItem &res, const StepFile &sf) { auto model = sf.restoreModel(); auto pred = model->predict(res.coords); res.update(pred); } // predict one element void PredictSession::predict(ResultItem &res) { auto stepfiles = getModelRoot()->openSampleStepFiles(); for (const auto &sf : stepfiles) predict(res, *sf); } ResultItem PredictSession::predict(PVec<> pos) { ResultItem ret{pos}; predict(ret); return ret; } // predict all elements in Ytest std::shared_ptr<Result> PredictSession::predict(std::shared_ptr<TensorConfig> Y) { auto res = std::make_shared<Result>(Y); for (const auto s : m_stepfiles) { auto model = restoreModel(s); res->update(model, false); } return res; } } // end namespace smurff <|endoftext|>
<commit_before>/* ** Author(s): ** - Cedric GESTES <gestes@aldebaran-robotics.com> ** ** Copyright (C) 2010 Aldebaran Robotics */ #include <cstring> #include <cstdlib> #include <iostream> #include <sstream> #include <qimessaging/signature.hpp> #include "src/signature/pretty_print_signature_visitor.hpp" namespace qi { static bool _is_valid(const char *begin, const char *end) { const char *current = begin; while (*current) { current++; }; return true; } static int _find_end(char **pcurrent, const char **psignature, const char *sigend, char copen, char close) { int opencount = 1; int closecount = 0; char *current = *pcurrent; const char *signature = *psignature; *current = *signature; signature++; current++; while ((signature < sigend) && (opencount != closecount)) { if (*signature == copen) opencount++; if (*signature == close) closecount++; *current = *signature; signature++; current++; } *pcurrent = current; *psignature = signature; return 0; } class SignaturePrivate { public: SignaturePrivate() : _signature(0), _end(0), _valid(false) { } bool split(const char *, const char *); void init(const char *signature, size_t len); char *_signature; const char *_end; bool _valid; }; void SignaturePrivate::init(const char *signature, size_t len) { if (!signature) { _valid = false; return; } //worst case: each char is a POD, we need 2x space (for \0) size_t size = len * 2; if (_signature) free(_signature); _signature = (char *)malloc(size); _end = _signature + size; _valid = split(signature, signature + size); } // go forward, add a 0, go forward, add a 0, bouhhh a 1! AHHHHHH scary! bool SignaturePrivate::split(const char *signature, const char *sig_end) { if (!_is_valid(signature, sig_end)) return false; //std::cout << "fullsig:" << signature << std::endl; char *current = _signature; //char *signature = _signature; const char *prev = current; while(*signature) { if (signature >= sig_end || _signature >= _end) break; //verify that the current signature is correct switch(static_cast<qi::Signature::Type>(*signature)) { case qi::Signature::Void: case qi::Signature::Bool: case qi::Signature::Char: case qi::Signature::Int: case qi::Signature::Float: case qi::Signature::Double: case qi::Signature::String: *current = *signature; current++; signature++; break; case qi::Signature::List: _find_end(&current, &signature, sig_end, '[', ']'); break; case qi::Signature::Map: _find_end(&current, &signature, sig_end, '[', ']'); break; default: return false; } if (*signature == '*') { *current = *signature; current++; signature++; } *current = 0; current++; //std::cout << "elt:" << prev << std::endl; prev = current; } _end = current - 1; return true; }; Signature::Signature(const char *fullSignature) : _p(boost::shared_ptr<SignaturePrivate>(new SignaturePrivate())) { if (!fullSignature) return; size_t size = strlen(fullSignature); _p->init(fullSignature, size); } Signature::Signature(const std::string &subsig) : _p(boost::shared_ptr<SignaturePrivate>(new SignaturePrivate())) { _p->init(subsig.c_str(), subsig.size()); } bool Signature::isValid() const { return _p->_valid; } ::qi::Signature::iterator Signature::begin() const { ::qi::Signature::iterator it(_p->_signature, _p->_end); return it; }; ::qi::Signature::iterator Signature::end() const { ::qi::Signature::iterator it; return it; }; ::qi::Signature::iterator &Signature::iterator::operator++() { if (!_current) return *this; //go to next \0 while (*_current && (_current <= _end)) { ++_current; } //eat one more if (!*_current) _current++; if (_current >= _end) _current = 0; return *this; } ::qi::Signature::iterator &Signature::iterator::operator++(int) { this->operator ++(); } Signature::Type Signature::iterator::type()const { if (!_current) return None; return static_cast<Type>(*_current); } std::string Signature::iterator::signature()const { if (!_current) return std::string(); return std::string(_current); } bool Signature::iterator::hasChildren() const { if (!_current) return false; switch (*_current) { case '[': case '{': case '@': return true; default: return false; }; } bool Signature::iterator::isPointer() const { if (!_current) return false; const char *prev = _current; const char *next = _current; while (*next) { prev = next; next++; } return *prev == '*'; } Signature Signature::iterator::children() const { Signature sig; size_t size; size_t toremove = 0; const char *fullSignature = _current; if (!fullSignature) return sig; size = strlen(fullSignature); while (toremove < size) { if (fullSignature[size - 1 - toremove] != '*') break; toremove++; } sig._p->init(fullSignature + 1, size - toremove - 1); return sig; } // std::string Signature::toSTL() { // //PrettyPrintSignatureVisitor ppsv(_signature, PrettyPrintSignatureVisitor::STL); // //return ppsv.fullSignature(); // } // std::string Signature::toQT() { // //PrettyPrintSignatureVisitor ppsv(_signature, PrettyPrintSignatureVisitor::Qt); // //return ppsv.fullSignature(); // } } <commit_msg>signature: fix free/delete<commit_after>/* ** Author(s): ** - Cedric GESTES <gestes@aldebaran-robotics.com> ** ** Copyright (C) 2010 Aldebaran Robotics */ #include <cstring> #include <cstdlib> #include <iostream> #include <sstream> #include <qimessaging/signature.hpp> #include "src/signature/pretty_print_signature_visitor.hpp" namespace qi { static bool _is_valid(const char *begin, const char *end) { const char *current = begin; while (*current) { current++; }; return true; } static int _find_end(char **pcurrent, const char **psignature, const char *sigend, char copen, char close) { int opencount = 1; int closecount = 0; char *current = *pcurrent; const char *signature = *psignature; *current = *signature; signature++; current++; while ((signature < sigend) && (opencount != closecount)) { if (*signature == copen) opencount++; if (*signature == close) closecount++; *current = *signature; signature++; current++; } *pcurrent = current; *psignature = signature; return 0; } class SignaturePrivate { public: SignaturePrivate() : _signature(0), _end(0), _valid(false) { } ~SignaturePrivate() { delete(_signature); } bool split(const char *, const char *); void init(const char *signature, size_t len); char *_signature; const char *_end; bool _valid; }; void SignaturePrivate::init(const char *signature, size_t len) { if (!signature) { _valid = false; return; } //worst case: each char is a POD, we need 2x space (for \0) size_t size = len * 2; if (_signature) free(_signature); _signature = new char[size]; _end = _signature + size; _valid = split(signature, signature + size); } // go forward, add a 0, go forward, add a 0, bouhhh a 1! AHHHHHH scary! bool SignaturePrivate::split(const char *signature, const char *sig_end) { if (!_is_valid(signature, sig_end)) return false; //std::cout << "fullsig:" << signature << std::endl; char *current = _signature; //char *signature = _signature; const char *prev = current; while(*signature) { if (signature >= sig_end || _signature >= _end) break; //verify that the current signature is correct switch(static_cast<qi::Signature::Type>(*signature)) { case qi::Signature::Void: case qi::Signature::Bool: case qi::Signature::Char: case qi::Signature::Int: case qi::Signature::Float: case qi::Signature::Double: case qi::Signature::String: *current = *signature; current++; signature++; break; case qi::Signature::List: _find_end(&current, &signature, sig_end, '[', ']'); break; case qi::Signature::Map: _find_end(&current, &signature, sig_end, '[', ']'); break; default: return false; } if (*signature == '*') { *current = *signature; current++; signature++; } *current = 0; current++; //std::cout << "elt:" << prev << std::endl; prev = current; } _end = current - 1; return true; }; Signature::Signature(const char *fullSignature) : _p(boost::shared_ptr<SignaturePrivate>(new SignaturePrivate())) { if (!fullSignature) return; size_t size = strlen(fullSignature); _p->init(fullSignature, size); } Signature::Signature(const std::string &subsig) : _p(boost::shared_ptr<SignaturePrivate>(new SignaturePrivate())) { _p->init(subsig.c_str(), subsig.size()); } bool Signature::isValid() const { return _p->_valid; } ::qi::Signature::iterator Signature::begin() const { ::qi::Signature::iterator it(_p->_signature, _p->_end); return it; }; ::qi::Signature::iterator Signature::end() const { ::qi::Signature::iterator it; return it; }; ::qi::Signature::iterator &Signature::iterator::operator++() { if (!_current) return *this; //go to next \0 while (*_current && (_current <= _end)) { ++_current; } //eat one more if (!*_current) _current++; if (_current >= _end) _current = 0; return *this; } ::qi::Signature::iterator &Signature::iterator::operator++(int) { this->operator++(); return *this; } Signature::Type Signature::iterator::type()const { if (!_current) return None; return static_cast<Type>(*_current); } std::string Signature::iterator::signature()const { if (!_current) return std::string(); return std::string(_current); } bool Signature::iterator::hasChildren() const { if (!_current) return false; switch (*_current) { case '[': case '{': case '@': return true; default: return false; }; } bool Signature::iterator::isPointer() const { if (!_current) return false; const char *prev = _current; const char *next = _current; while (*next) { prev = next; next++; } return *prev == '*'; } Signature Signature::iterator::children() const { Signature sig; size_t size; size_t toremove = 0; const char *fullSignature = _current; if (!fullSignature) return sig; size = strlen(fullSignature); while (toremove < size) { if (fullSignature[size - 1 - toremove] != '*') break; toremove++; } sig._p->init(fullSignature + 1, size - toremove - 1); return sig; } // std::string Signature::toSTL() { // //PrettyPrintSignatureVisitor ppsv(_signature, PrettyPrintSignatureVisitor::STL); // //return ppsv.fullSignature(); // } // std::string Signature::toQT() { // //PrettyPrintSignatureVisitor ppsv(_signature, PrettyPrintSignatureVisitor::Qt); // //return ppsv.fullSignature(); // } } <|endoftext|>
<commit_before>/************************************************************************* > File Name: PlayerSetting.cpp > Project Name: Hearthstonepp > Author: Young-Joong Kim > Purpose: Implement PlayerSetting > Created Time: 2018/07/21 > Copyright (c) 2018, Young-Joong Kim *************************************************************************/ #include <Tasks/BasicTasks/PlayerSettingTask.h> namespace Hearthstonepp::BasicTasks { PlayerSettingTask::PlayerSettingTask(TaskAgent& agent) : m_agent(agent) { // Do Nothing } TaskID PlayerSettingTask::GetTaskID() const { return TaskID::PLAYER_SETTING; } MetaData PlayerSettingTask::Impl(Player& player1, Player& player2) { player1.id = 0; player2.id = 0; TaskMeta setting = Serializer::CreatePlayerSetting(player1.email, player2.email); m_agent.Notify(std::move(setting)); return MetaData::PLAYER_SETTING_SUCCESS; } } // namespace Hearthstonepp::BasicTasks<commit_msg>Update PlayerSettingTask - Fix both player get same id<commit_after>/************************************************************************* > File Name: PlayerSetting.cpp > Project Name: Hearthstonepp > Author: Young-Joong Kim > Purpose: Implement PlayerSetting > Created Time: 2018/07/21 > Copyright (c) 2018, Young-Joong Kim *************************************************************************/ #include <Tasks/BasicTasks/PlayerSettingTask.h> namespace Hearthstonepp::BasicTasks { PlayerSettingTask::PlayerSettingTask(TaskAgent& agent) : m_agent(agent) { // Do Nothing } TaskID PlayerSettingTask::GetTaskID() const { return TaskID::PLAYER_SETTING; } MetaData PlayerSettingTask::Impl(Player& player1, Player& player2) { player1.id = 0; player2.id = 1; TaskMeta setting = Serializer::CreatePlayerSetting(player1.email, player2.email); m_agent.Notify(std::move(setting)); return MetaData::PLAYER_SETTING_SUCCESS; } } // namespace Hearthstonepp::BasicTasks<|endoftext|>
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #ifndef NET_SOCKET_HPP #define NET_SOCKET_HPP #include <net/ip4/addr.hpp> namespace net { /** * An IP address and port */ union Socket { using Address = ip4::Addr; using port_t = uint16_t; /** * Constructor * * Intialize an empty socket <0.0.0.0:0> */ constexpr Socket() noexcept : address_{}, port_{} {} /** * Constructor * * Create a socket with an address and port * * @param address * The host's network address * * @param port * The port associated with the process */ constexpr Socket(const Address address, const port_t port) noexcept : address_{address}, port_{port} {} Socket(const Socket& other) noexcept : data_{other.data_} {} Socket& operator=(const Socket& other) noexcept { data_ = other.data_; return *this; } /** * Get the socket's network address * * @return The socket's network address */ constexpr Address address() const noexcept { return address_; } /** * Get the socket's port value * * @return The socket's port value */ constexpr port_t port() const noexcept { return port_; } /** * Get a string representation of this class * * @return A string representation of this class */ std::string to_string() const { return address_.str() + ":" + std::to_string(port_); } /** * Check if this socket is empty <0.0.0.0:0> * * @return true if this socket is empty, false otherwise */ constexpr bool is_empty() const noexcept { return (address_ == 0) and (port_ == 0); } /** * Operator to check for equality relationship * * @param other * The socket to check for equality relationship * * @return true if the specified socket is equal, false otherwise */ constexpr bool operator==(const Socket& other) const noexcept { return data_ == other.data_; } /** * Operator to check for inequality relationship * * @param other * The socket to check for inequality relationship * * @return true if the specified socket is not equal, false otherwise */ constexpr bool operator!=(const Socket& other) const noexcept { return not (*this == other); } /** * Operator to check for less-than relationship * * @param other * The socket to check for less-than relationship * * @return true if this socket is less-than the specified socket, * false otherwise */ constexpr bool operator<(const Socket& other) const noexcept { return (address() < other.address()) or ((address() == other.address()) and (port() < other.port())); } /** * Operator to check for greater-than relationship * * @param other * The socket to check for greater-than relationship * * @return true if this socket is greater-than the specified socket, * false otherwise */ constexpr bool operator>(const Socket& other) const noexcept { return not (*this < other); } private: struct { Address address_; port_t port_; uint16_t padding{0}; }; uint64_t data_; }; //< class Socket static_assert(sizeof(Socket) == 8, "Socket not 8 byte"); /** * @brief A pair of Sockets */ struct Quadruple { Socket src; Socket dst; Quadruple() = default; Quadruple(Socket s, Socket d) : src(std::move(s)), dst(std::move(d)) {} bool operator==(const Quadruple& other) const noexcept { return src == other.src and dst == other.dst; } bool operator!=(const Quadruple& other) const noexcept { return not (*this == other); } bool operator<(const Quadruple& other) const noexcept { return src < other.src or (src == other.src and dst < other.dst); } bool operator>(const Quadruple& other) const noexcept { return src > other.src or (src == other.src and dst > other.dst); } bool is_reverse(const Quadruple& other) const noexcept { return src == other.dst and dst == other.src; } Quadruple& swap() { std::swap(src, dst); return *this; } std::string to_string() const { return src.to_string() + " " + dst.to_string(); } }; //< struct Quadruple } //< namespace net namespace std { template<> struct hash<net::Socket> { public: size_t operator () (const net::Socket& key) const noexcept { const auto h1 = std::hash<net::Socket::Address>{}(key.address()); const auto h2 = std::hash<net::Socket::port_t>{}(key.port()); return h1 ^ h2; } }; template<> struct hash<net::Quadruple> { public: size_t operator () (const net::Quadruple& key) const noexcept { const auto h1 = std::hash<net::Socket>{}(key.src); const auto h2 = std::hash<net::Socket>{}(key.dst); return h1 ^ h2; } }; } // < namespace std #endif //< NET_SOCKET_HPP <commit_msg>net: Fix Socket not building with g++<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org // // Copyright 2015-2017 Oslo and Akershus University College of Applied Sciences // and Alfred Bratterud // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #pragma once #ifndef NET_SOCKET_HPP #define NET_SOCKET_HPP #include <net/ip4/addr.hpp> namespace net { /** * An IP address and port */ union Socket { using Address = ip4::Addr; using port_t = uint16_t; /** * Constructor * * Intialize an empty socket <0.0.0.0:0> */ constexpr Socket() noexcept : sock_(0, 0) {} /** * Constructor * * Create a socket with an address and port * * @param address * The host's network address * * @param port * The port associated with the process */ constexpr Socket(const Address address, const port_t port) noexcept : sock_(address, port) {} Socket(const Socket& other) noexcept : data_{other.data_} {} Socket& operator=(const Socket& other) noexcept { data_ = other.data_; return *this; } /** * Get the socket's network address * * @return The socket's network address */ constexpr Address address() const noexcept { return sock_.address; } /** * Get the socket's port value * * @return The socket's port value */ constexpr port_t port() const noexcept { return sock_.port; } /** * Get a string representation of this class * * @return A string representation of this class */ std::string to_string() const { return address().str() + ":" + std::to_string(port()); } /** * Check if this socket is empty <0.0.0.0:0> * * @return true if this socket is empty, false otherwise */ constexpr bool is_empty() const noexcept { return (address() == 0) and (port() == 0); } /** * Operator to check for equality relationship * * @param other * The socket to check for equality relationship * * @return true if the specified socket is equal, false otherwise */ constexpr bool operator==(const Socket& other) const noexcept { return data_ == other.data_; } /** * Operator to check for inequality relationship * * @param other * The socket to check for inequality relationship * * @return true if the specified socket is not equal, false otherwise */ constexpr bool operator!=(const Socket& other) const noexcept { return not (*this == other); } /** * Operator to check for less-than relationship * * @param other * The socket to check for less-than relationship * * @return true if this socket is less-than the specified socket, * false otherwise */ constexpr bool operator<(const Socket& other) const noexcept { return (address() < other.address()) or ((address() == other.address()) and (port() < other.port())); } /** * Operator to check for greater-than relationship * * @param other * The socket to check for greater-than relationship * * @return true if this socket is greater-than the specified socket, * false otherwise */ constexpr bool operator>(const Socket& other) const noexcept { return not (*this < other); } private: struct Sock { constexpr Sock(Address a, port_t p) : address(a), port(p), padding(0) {} Address address; port_t port; uint16_t padding; } sock_; uint64_t data_; }; //< class Socket static_assert(sizeof(Socket) == 8, "Socket not 8 byte"); /** * @brief A pair of Sockets */ struct Quadruple { Socket src; Socket dst; Quadruple() = default; Quadruple(Socket s, Socket d) : src(std::move(s)), dst(std::move(d)) {} bool operator==(const Quadruple& other) const noexcept { return src == other.src and dst == other.dst; } bool operator!=(const Quadruple& other) const noexcept { return not (*this == other); } bool operator<(const Quadruple& other) const noexcept { return src < other.src or (src == other.src and dst < other.dst); } bool operator>(const Quadruple& other) const noexcept { return src > other.src or (src == other.src and dst > other.dst); } bool is_reverse(const Quadruple& other) const noexcept { return src == other.dst and dst == other.src; } Quadruple& swap() { std::swap(src, dst); return *this; } std::string to_string() const { return src.to_string() + " " + dst.to_string(); } }; //< struct Quadruple } //< namespace net namespace std { template<> struct hash<net::Socket> { public: size_t operator () (const net::Socket& key) const noexcept { const auto h1 = std::hash<net::Socket::Address>{}(key.address()); const auto h2 = std::hash<net::Socket::port_t>{}(key.port()); return h1 ^ h2; } }; template<> struct hash<net::Quadruple> { public: size_t operator () (const net::Quadruple& key) const noexcept { const auto h1 = std::hash<net::Socket>{}(key.src); const auto h2 = std::hash<net::Socket>{}(key.dst); return h1 ^ h2; } }; } // < namespace std #endif //< NET_SOCKET_HPP <|endoftext|>
<commit_before>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. // Implementation of class LinearForm #include "fem.hpp" namespace mfem { LinearForm::LinearForm(FiniteElementSpace *f, LinearForm *lf) : Vector(f->GetVSize()) { // Linear forms are stored on the device UseDevice(true); fes = f; ext = nullptr; extern_lfs = 1; // Copy the pointers to the integrators domain_integs = lf->domain_integs; domain_delta_integs = lf->domain_delta_integs; boundary_integs = lf->boundary_integs; boundary_face_integs = lf->boundary_face_integs; boundary_face_integs_marker = lf->boundary_face_integs_marker; } void LinearForm::AddDomainIntegrator(LinearFormIntegrator *lfi) { DeltaLFIntegrator *maybe_delta = dynamic_cast<DeltaLFIntegrator *>(lfi); if (!maybe_delta || !maybe_delta->IsDelta()) { domain_integs.Append(lfi); } else { domain_delta_integs.Append(maybe_delta); } domain_integs_marker.Append(NULL); } void LinearForm::AddDomainIntegrator(LinearFormIntegrator *lfi, Array<int> &elem_marker) { DeltaLFIntegrator *maybe_delta = dynamic_cast<DeltaLFIntegrator *>(lfi); if (!maybe_delta || !maybe_delta->IsDelta()) { domain_integs.Append(lfi); } else { domain_delta_integs.Append(maybe_delta); } domain_integs_marker.Append(&elem_marker); } void LinearForm::AddBoundaryIntegrator (LinearFormIntegrator * lfi) { boundary_integs.Append (lfi); boundary_integs_marker.Append(NULL); // NULL -> all attributes are active } void LinearForm::AddBoundaryIntegrator (LinearFormIntegrator * lfi, Array<int> &bdr_attr_marker) { boundary_integs.Append (lfi); boundary_integs_marker.Append(&bdr_attr_marker); } void LinearForm::AddBdrFaceIntegrator (LinearFormIntegrator * lfi) { boundary_face_integs.Append(lfi); // NULL -> all attributes are active boundary_face_integs_marker.Append(NULL); } void LinearForm::AddBdrFaceIntegrator(LinearFormIntegrator *lfi, Array<int> &bdr_attr_marker) { boundary_face_integs.Append(lfi); boundary_face_integs_marker.Append(&bdr_attr_marker); } void LinearForm::AddInteriorFaceIntegrator(LinearFormIntegrator *lfi) { interior_face_integs.Append(lfi); } bool LinearForm::SupportsDevice() { // scan domain integrator to verify that all can use device assembly if (domain_integs.Size() > 0) { for (int k = 0; k < domain_integs.Size(); k++) { if (!domain_integs[k]->SupportsDevice()) { return false; } } } // boundary, delta and face integrators are not supported yet if (GetBLFI()->Size() > 0 || GetFLFI()->Size() > 0 || GetDLFI_Delta()->Size() > 0 || GetIFLFI()->Size() > 0) { return false; } const Mesh &mesh = *fes->GetMesh(); // no support for elements with varying polynomial orders if (fes->IsVariableOrder()) { return false; } // no support for 1D and embedded meshes const int mesh_dim = mesh.Dimension(); if (mesh_dim == 1 || mesh_dim != mesh.SpaceDimension()) { return false; } // tensor-product finite element space only // with point values preserving scalar fields for (int e = 0; e < fes->GetNE(); ++e) { const FiniteElement *fe = fes->GetFE(e); if (fe->GetMapType() != FiniteElement::VALUE) { return false; } if (!dynamic_cast<const TensorBasisElement*>(fe)) { return false; } } return true; } void LinearForm::Assemble(bool use_device) { Array<int> vdofs; ElementTransformation *eltrans; DofTransformation *doftrans; Vector elemvect; if (!ext && use_device && SupportsDevice()) { ext = new LinearFormExtension(this); } Vector::operator=(0.0); // The above operation is executed on device because of UseDevice(). // The first use of AddElementVector() below will move it back to host // because both 'vdofs' and 'elemvect' are on host. if (ext) { return ext->Assemble(); } if (domain_integs.Size()) { for (int k = 0; k < domain_integs.Size(); k++) { if (domain_integs_marker[k] != NULL) { MFEM_VERIFY(domain_integs_marker[k]->Size() == (fes->GetMesh()->attributes.Size() ? fes->GetMesh()->attributes.Max() : 0), "invalid element marker for domain linear form " "integrator #" << k << ", counting from zero"); } } for (int i = 0; i < fes -> GetNE(); i++) { int elem_attr = fes->GetMesh()->GetAttribute(i); for (int k = 0; k < domain_integs.Size(); k++) { if ( domain_integs_marker[k] == NULL || (*(domain_integs_marker[k]))[elem_attr-1] == 1 ) { doftrans = fes -> GetElementVDofs (i, vdofs); eltrans = fes -> GetElementTransformation (i); domain_integs[k]->AssembleRHSElementVect(*fes->GetFE(i), *eltrans, elemvect); if (doftrans) { doftrans->TransformDual(elemvect); } AddElementVector (vdofs, elemvect); } } } } AssembleDelta(); if (boundary_integs.Size()) { Mesh *mesh = fes->GetMesh(); // Which boundary attributes need to be processed? Array<int> bdr_attr_marker(mesh->bdr_attributes.Size() ? mesh->bdr_attributes.Max() : 0); bdr_attr_marker = 0; for (int k = 0; k < boundary_integs.Size(); k++) { if (boundary_integs_marker[k] == NULL) { bdr_attr_marker = 1; break; } Array<int> &bdr_marker = *boundary_integs_marker[k]; MFEM_ASSERT(bdr_marker.Size() == bdr_attr_marker.Size(), "invalid boundary marker for boundary integrator #" << k << ", counting from zero"); for (int i = 0; i < bdr_attr_marker.Size(); i++) { bdr_attr_marker[i] |= bdr_marker[i]; } } for (int i = 0; i < fes -> GetNBE(); i++) { const int bdr_attr = mesh->GetBdrAttribute(i); if (bdr_attr_marker[bdr_attr-1] == 0) { continue; } doftrans = fes -> GetBdrElementVDofs (i, vdofs); eltrans = fes -> GetBdrElementTransformation (i); for (int k=0; k < boundary_integs.Size(); k++) { if (boundary_integs_marker[k] && (*boundary_integs_marker[k])[bdr_attr-1] == 0) { continue; } boundary_integs[k]->AssembleRHSElementVect(*fes->GetBE(i), *eltrans, elemvect); if (doftrans) { doftrans->TransformDual(elemvect); } AddElementVector (vdofs, elemvect); } } } if (boundary_face_integs.Size()) { FaceElementTransformations *tr; Mesh *mesh = fes->GetMesh(); // Which boundary attributes need to be processed? Array<int> bdr_attr_marker(mesh->bdr_attributes.Size() ? mesh->bdr_attributes.Max() : 0); bdr_attr_marker = 0; for (int k = 0; k < boundary_face_integs.Size(); k++) { if (boundary_face_integs_marker[k] == NULL) { bdr_attr_marker = 1; break; } Array<int> &bdr_marker = *boundary_face_integs_marker[k]; MFEM_ASSERT(bdr_marker.Size() == bdr_attr_marker.Size(), "invalid boundary marker for boundary face integrator #" << k << ", counting from zero"); for (int i = 0; i < bdr_attr_marker.Size(); i++) { bdr_attr_marker[i] |= bdr_marker[i]; } } for (int i = 0; i < mesh->GetNBE(); i++) { const int bdr_attr = mesh->GetBdrAttribute(i); if (bdr_attr_marker[bdr_attr-1] == 0) { continue; } tr = mesh->GetBdrFaceTransformations(i); if (tr != NULL) { fes -> GetElementVDofs (tr -> Elem1No, vdofs); for (int k = 0; k < boundary_face_integs.Size(); k++) { if (boundary_face_integs_marker[k] && (*boundary_face_integs_marker[k])[bdr_attr-1] == 0) { continue; } boundary_face_integs[k]-> AssembleRHSElementVect(*fes->GetFE(tr->Elem1No), *tr, elemvect); AddElementVector (vdofs, elemvect); } } } } if (interior_face_integs.Size()) { Mesh *mesh = fes->GetMesh(); for (int k = 0; k < interior_face_integs.Size(); k++) { for (int i = 0; i < mesh->GetNumFaces(); i++) { FaceElementTransformations *tr = NULL; tr = mesh->GetInteriorFaceTransformations (i); if (tr != NULL) { fes -> GetElementVDofs (tr -> Elem1No, vdofs); Array<int> vdofs2; fes -> GetElementVDofs (tr -> Elem2No, vdofs2); vdofs.Append(vdofs2); interior_face_integs[k]-> AssembleRHSElementVect(*fes->GetFE(tr->Elem1No), *fes->GetFE(tr->Elem2No), *tr, elemvect); AddElementVector (vdofs, elemvect); } } } } } void LinearForm::Update() { SetSize(fes->GetVSize()); ResetDeltaLocations(); if (ext) { ext->Update(); } } void LinearForm::Update(FiniteElementSpace *f, Vector &v, int v_offset) { MFEM_ASSERT(v.Size() >= v_offset + f->GetVSize(), ""); fes = f; v.UseDevice(true); this->Vector::MakeRef(v, v_offset, fes->GetVSize()); ResetDeltaLocations(); if (ext) { ext->Update(); } } void LinearForm::MakeRef(FiniteElementSpace *f, Vector &v, int v_offset) { Update(f, v, v_offset); } void LinearForm::AssembleDelta() { if (domain_delta_integs.Size() == 0) { return; } if (!HaveDeltaLocations()) { int sdim = fes->GetMesh()->SpaceDimension(); Vector center; DenseMatrix centers(sdim, domain_delta_integs.Size()); for (int i = 0; i < centers.Width(); i++) { centers.GetColumnReference(i, center); domain_delta_integs[i]->GetDeltaCenter(center); MFEM_VERIFY(center.Size() == sdim, "Point dim " << center.Size() << " does not match space dim " << sdim); } fes->GetMesh()->FindPoints(centers, domain_delta_integs_elem_id, domain_delta_integs_ip); } Array<int> vdofs; Vector elemvect; for (int i = 0; i < domain_delta_integs.Size(); i++) { int elem_id = domain_delta_integs_elem_id[i]; // The delta center may be outside of this sub-domain, or // (Par)Mesh::FindPoints() failed to find this point: if (elem_id < 0) { continue; } const IntegrationPoint &ip = domain_delta_integs_ip[i]; ElementTransformation &Trans = *fes->GetElementTransformation(elem_id); Trans.SetIntPoint(&ip); fes->GetElementVDofs(elem_id, vdofs); domain_delta_integs[i]->AssembleDeltaElementVect(*fes->GetFE(elem_id), Trans, elemvect); AddElementVector(vdofs, elemvect); } } LinearForm & LinearForm::operator=(double value) { Vector::operator=(value); return *this; } LinearForm & LinearForm::operator=(const Vector &v) { MFEM_ASSERT(fes && v.Size() == fes->GetVSize(), ""); Vector::operator=(v); return *this; } LinearForm::~LinearForm() { if (!extern_lfs) { int k; for (k=0; k < domain_delta_integs.Size(); k++) { delete domain_delta_integs[k]; } for (k=0; k < domain_integs.Size(); k++) { delete domain_integs[k]; } for (k=0; k < boundary_integs.Size(); k++) { delete boundary_integs[k]; } for (k=0; k < boundary_face_integs.Size(); k++) { delete boundary_face_integs[k]; } for (k=0; k < interior_face_integs.Size(); k++) { delete interior_face_integs[k]; } } delete ext; } } <commit_msg>return false for NURBS meshs in LinearForm::SupportsDevice<commit_after>// Copyright (c) 2010-2022, Lawrence Livermore National Security, LLC. Produced // at the Lawrence Livermore National Laboratory. All Rights reserved. See files // LICENSE and NOTICE for details. LLNL-CODE-806117. // // This file is part of the MFEM library. For more information and source code // availability visit https://mfem.org. // // MFEM is free software; you can redistribute it and/or modify it under the // terms of the BSD-3 license. We welcome feedback and contributions, see file // CONTRIBUTING.md for details. // Implementation of class LinearForm #include "fem.hpp" namespace mfem { LinearForm::LinearForm(FiniteElementSpace *f, LinearForm *lf) : Vector(f->GetVSize()) { // Linear forms are stored on the device UseDevice(true); fes = f; ext = nullptr; extern_lfs = 1; // Copy the pointers to the integrators domain_integs = lf->domain_integs; domain_delta_integs = lf->domain_delta_integs; boundary_integs = lf->boundary_integs; boundary_face_integs = lf->boundary_face_integs; boundary_face_integs_marker = lf->boundary_face_integs_marker; } void LinearForm::AddDomainIntegrator(LinearFormIntegrator *lfi) { DeltaLFIntegrator *maybe_delta = dynamic_cast<DeltaLFIntegrator *>(lfi); if (!maybe_delta || !maybe_delta->IsDelta()) { domain_integs.Append(lfi); } else { domain_delta_integs.Append(maybe_delta); } domain_integs_marker.Append(NULL); } void LinearForm::AddDomainIntegrator(LinearFormIntegrator *lfi, Array<int> &elem_marker) { DeltaLFIntegrator *maybe_delta = dynamic_cast<DeltaLFIntegrator *>(lfi); if (!maybe_delta || !maybe_delta->IsDelta()) { domain_integs.Append(lfi); } else { domain_delta_integs.Append(maybe_delta); } domain_integs_marker.Append(&elem_marker); } void LinearForm::AddBoundaryIntegrator (LinearFormIntegrator * lfi) { boundary_integs.Append (lfi); boundary_integs_marker.Append(NULL); // NULL -> all attributes are active } void LinearForm::AddBoundaryIntegrator (LinearFormIntegrator * lfi, Array<int> &bdr_attr_marker) { boundary_integs.Append (lfi); boundary_integs_marker.Append(&bdr_attr_marker); } void LinearForm::AddBdrFaceIntegrator (LinearFormIntegrator * lfi) { boundary_face_integs.Append(lfi); // NULL -> all attributes are active boundary_face_integs_marker.Append(NULL); } void LinearForm::AddBdrFaceIntegrator(LinearFormIntegrator *lfi, Array<int> &bdr_attr_marker) { boundary_face_integs.Append(lfi); boundary_face_integs_marker.Append(&bdr_attr_marker); } void LinearForm::AddInteriorFaceIntegrator(LinearFormIntegrator *lfi) { interior_face_integs.Append(lfi); } bool LinearForm::SupportsDevice() { // return false for NURBS meshs, so we don’t convert it to non-NURBS // through Assemble, AssembleDevice, GetGeometricFactors and EnsureNodes if (fes->GetNURBSext()) { return false; } // scan domain integrator to verify that all can use device assembly if (domain_integs.Size() > 0) { for (int k = 0; k < domain_integs.Size(); k++) { if (!domain_integs[k]->SupportsDevice()) { return false; } } } // boundary, delta and face integrators are not supported yet if (GetBLFI()->Size() > 0 || GetFLFI()->Size() > 0 || GetDLFI_Delta()->Size() > 0 || GetIFLFI()->Size() > 0) { return false; } const Mesh &mesh = *fes->GetMesh(); // no support for elements with varying polynomial orders if (fes->IsVariableOrder()) { return false; } // no support for 1D and embedded meshes const int mesh_dim = mesh.Dimension(); if (mesh_dim == 1 || mesh_dim != mesh.SpaceDimension()) { return false; } // tensor-product finite element space only // with point values preserving scalar fields for (int e = 0; e < fes->GetNE(); ++e) { const FiniteElement *fe = fes->GetFE(e); if (fe->GetMapType() != FiniteElement::VALUE) { return false; } if (!dynamic_cast<const TensorBasisElement*>(fe)) { return false; } } return true; } void LinearForm::Assemble(bool use_device) { Array<int> vdofs; ElementTransformation *eltrans; DofTransformation *doftrans; Vector elemvect; if (!ext && use_device && SupportsDevice()) { ext = new LinearFormExtension(this); } Vector::operator=(0.0); // The above operation is executed on device because of UseDevice(). // The first use of AddElementVector() below will move it back to host // because both 'vdofs' and 'elemvect' are on host. if (ext) { return ext->Assemble(); } if (domain_integs.Size()) { for (int k = 0; k < domain_integs.Size(); k++) { if (domain_integs_marker[k] != NULL) { MFEM_VERIFY(domain_integs_marker[k]->Size() == (fes->GetMesh()->attributes.Size() ? fes->GetMesh()->attributes.Max() : 0), "invalid element marker for domain linear form " "integrator #" << k << ", counting from zero"); } } for (int i = 0; i < fes -> GetNE(); i++) { int elem_attr = fes->GetMesh()->GetAttribute(i); for (int k = 0; k < domain_integs.Size(); k++) { if ( domain_integs_marker[k] == NULL || (*(domain_integs_marker[k]))[elem_attr-1] == 1 ) { doftrans = fes -> GetElementVDofs (i, vdofs); eltrans = fes -> GetElementTransformation (i); domain_integs[k]->AssembleRHSElementVect(*fes->GetFE(i), *eltrans, elemvect); if (doftrans) { doftrans->TransformDual(elemvect); } AddElementVector (vdofs, elemvect); } } } } AssembleDelta(); if (boundary_integs.Size()) { Mesh *mesh = fes->GetMesh(); // Which boundary attributes need to be processed? Array<int> bdr_attr_marker(mesh->bdr_attributes.Size() ? mesh->bdr_attributes.Max() : 0); bdr_attr_marker = 0; for (int k = 0; k < boundary_integs.Size(); k++) { if (boundary_integs_marker[k] == NULL) { bdr_attr_marker = 1; break; } Array<int> &bdr_marker = *boundary_integs_marker[k]; MFEM_ASSERT(bdr_marker.Size() == bdr_attr_marker.Size(), "invalid boundary marker for boundary integrator #" << k << ", counting from zero"); for (int i = 0; i < bdr_attr_marker.Size(); i++) { bdr_attr_marker[i] |= bdr_marker[i]; } } for (int i = 0; i < fes -> GetNBE(); i++) { const int bdr_attr = mesh->GetBdrAttribute(i); if (bdr_attr_marker[bdr_attr-1] == 0) { continue; } doftrans = fes -> GetBdrElementVDofs (i, vdofs); eltrans = fes -> GetBdrElementTransformation (i); for (int k=0; k < boundary_integs.Size(); k++) { if (boundary_integs_marker[k] && (*boundary_integs_marker[k])[bdr_attr-1] == 0) { continue; } boundary_integs[k]->AssembleRHSElementVect(*fes->GetBE(i), *eltrans, elemvect); if (doftrans) { doftrans->TransformDual(elemvect); } AddElementVector (vdofs, elemvect); } } } if (boundary_face_integs.Size()) { FaceElementTransformations *tr; Mesh *mesh = fes->GetMesh(); // Which boundary attributes need to be processed? Array<int> bdr_attr_marker(mesh->bdr_attributes.Size() ? mesh->bdr_attributes.Max() : 0); bdr_attr_marker = 0; for (int k = 0; k < boundary_face_integs.Size(); k++) { if (boundary_face_integs_marker[k] == NULL) { bdr_attr_marker = 1; break; } Array<int> &bdr_marker = *boundary_face_integs_marker[k]; MFEM_ASSERT(bdr_marker.Size() == bdr_attr_marker.Size(), "invalid boundary marker for boundary face integrator #" << k << ", counting from zero"); for (int i = 0; i < bdr_attr_marker.Size(); i++) { bdr_attr_marker[i] |= bdr_marker[i]; } } for (int i = 0; i < mesh->GetNBE(); i++) { const int bdr_attr = mesh->GetBdrAttribute(i); if (bdr_attr_marker[bdr_attr-1] == 0) { continue; } tr = mesh->GetBdrFaceTransformations(i); if (tr != NULL) { fes -> GetElementVDofs (tr -> Elem1No, vdofs); for (int k = 0; k < boundary_face_integs.Size(); k++) { if (boundary_face_integs_marker[k] && (*boundary_face_integs_marker[k])[bdr_attr-1] == 0) { continue; } boundary_face_integs[k]-> AssembleRHSElementVect(*fes->GetFE(tr->Elem1No), *tr, elemvect); AddElementVector (vdofs, elemvect); } } } } if (interior_face_integs.Size()) { Mesh *mesh = fes->GetMesh(); for (int k = 0; k < interior_face_integs.Size(); k++) { for (int i = 0; i < mesh->GetNumFaces(); i++) { FaceElementTransformations *tr = NULL; tr = mesh->GetInteriorFaceTransformations (i); if (tr != NULL) { fes -> GetElementVDofs (tr -> Elem1No, vdofs); Array<int> vdofs2; fes -> GetElementVDofs (tr -> Elem2No, vdofs2); vdofs.Append(vdofs2); interior_face_integs[k]-> AssembleRHSElementVect(*fes->GetFE(tr->Elem1No), *fes->GetFE(tr->Elem2No), *tr, elemvect); AddElementVector (vdofs, elemvect); } } } } } void LinearForm::Update() { SetSize(fes->GetVSize()); ResetDeltaLocations(); if (ext) { ext->Update(); } } void LinearForm::Update(FiniteElementSpace *f, Vector &v, int v_offset) { MFEM_ASSERT(v.Size() >= v_offset + f->GetVSize(), ""); fes = f; v.UseDevice(true); this->Vector::MakeRef(v, v_offset, fes->GetVSize()); ResetDeltaLocations(); if (ext) { ext->Update(); } } void LinearForm::MakeRef(FiniteElementSpace *f, Vector &v, int v_offset) { Update(f, v, v_offset); } void LinearForm::AssembleDelta() { if (domain_delta_integs.Size() == 0) { return; } if (!HaveDeltaLocations()) { int sdim = fes->GetMesh()->SpaceDimension(); Vector center; DenseMatrix centers(sdim, domain_delta_integs.Size()); for (int i = 0; i < centers.Width(); i++) { centers.GetColumnReference(i, center); domain_delta_integs[i]->GetDeltaCenter(center); MFEM_VERIFY(center.Size() == sdim, "Point dim " << center.Size() << " does not match space dim " << sdim); } fes->GetMesh()->FindPoints(centers, domain_delta_integs_elem_id, domain_delta_integs_ip); } Array<int> vdofs; Vector elemvect; for (int i = 0; i < domain_delta_integs.Size(); i++) { int elem_id = domain_delta_integs_elem_id[i]; // The delta center may be outside of this sub-domain, or // (Par)Mesh::FindPoints() failed to find this point: if (elem_id < 0) { continue; } const IntegrationPoint &ip = domain_delta_integs_ip[i]; ElementTransformation &Trans = *fes->GetElementTransformation(elem_id); Trans.SetIntPoint(&ip); fes->GetElementVDofs(elem_id, vdofs); domain_delta_integs[i]->AssembleDeltaElementVect(*fes->GetFE(elem_id), Trans, elemvect); AddElementVector(vdofs, elemvect); } } LinearForm & LinearForm::operator=(double value) { Vector::operator=(value); return *this; } LinearForm & LinearForm::operator=(const Vector &v) { MFEM_ASSERT(fes && v.Size() == fes->GetVSize(), ""); Vector::operator=(v); return *this; } LinearForm::~LinearForm() { if (!extern_lfs) { int k; for (k=0; k < domain_delta_integs.Size(); k++) { delete domain_delta_integs[k]; } for (k=0; k < domain_integs.Size(); k++) { delete domain_integs[k]; } for (k=0; k < boundary_integs.Size(); k++) { delete boundary_integs[k]; } for (k=0; k < boundary_face_integs.Size(); k++) { delete boundary_face_integs[k]; } for (k=0; k < interior_face_integs.Size(); k++) { delete interior_face_integs[k]; } } delete ext; } } <|endoftext|>
<commit_before>#ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <direct.h> #ifndef strcasecmp #define strcasecmp _stricmp #endif #else #include <dirent.h> #include <unistd.h> #include <errno.h> #endif #include <cstring> #include <string> #include <set> #include <algorithm> #include <cstdio> #include <sys/stat.h> #include <ctype.h> #include "base/logging.h" #include "base/basictypes.h" #include "file/file_util.h" #include "util/text/utf8.h" #if defined(__FreeBSD__) || defined(__APPLE__) || defined(__SYMBIAN32__) #define stat64 stat #endif // Hack #ifdef __SYMBIAN32__ static inline int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result) { struct dirent *readdir_entry; readdir_entry = readdir(dirp); if (readdir_entry == NULL) { *result = NULL; return errno; } *entry = *readdir_entry; *result = entry; return 0; } #endif FILE *openCFile(const std::string &filename, const char *mode) { #if defined(_WIN32) && defined(UNICODE) return _wfopen(ConvertUTF8ToWString(filename).c_str(), ConvertUTF8ToWString(mode).c_str()); #else return fopen(filename.c_str(), mode); #endif } bool writeStringToFile(bool text_file, const std::string &str, const char *filename) { FILE *f = openCFile(filename, text_file ? "w" : "wb"); if (!f) return false; size_t len = str.size(); if (len != fwrite(str.data(), 1, str.size(), f)) { fclose(f); return false; } fclose(f); return true; } bool writeDataToFile(bool text_file, const void* data, const unsigned int size, const char *filename) { FILE *f = openCFile(filename, text_file ? "w" : "wb"); if (!f) return false; size_t len = size; if (len != fwrite(data, 1, len, f)) { fclose(f); return false; } fclose(f); return true; } uint64_t GetSize(FILE *f) { // can't use off_t here because it can be 32-bit uint64_t pos = ftell(f); if (fseek(f, 0, SEEK_END) != 0) { return 0; } uint64_t size = ftell(f); // Reset the seek position to where it was when we started. if ((size != pos) && (fseek(f, pos, SEEK_SET) != 0)) { // Should error here return 0; } return size; } bool readFileToString(bool text_file, const char *filename, std::string &str) { FILE *f = openCFile(filename, text_file ? "r" : "rb"); if (!f) return false; size_t len = (size_t)GetSize(f); char *buf = new char[len + 1]; buf[fread(buf, 1, len, f)] = 0; str = std::string(buf, len); fclose(f); delete [] buf; return true; } bool readDataFromFile(bool text_file, unsigned char* &data, const unsigned int size, const char *filename) { FILE *f = openCFile(filename, text_file ? "r" : "rb"); if (!f) return false; size_t len = (size_t)GetSize(f); if(len < size) { fclose(f); return false; } data[fread(data, 1, size, f)] = 0; fclose(f); return true; } #define DIR_SEP "/" #define DIR_SEP_CHR '\\' #ifndef METRO // Remove any ending forward slashes from directory paths // Modifies argument. static void stripTailDirSlashes(std::string &fname) { if (fname.length() > 1) { size_t i = fname.length() - 1; while (fname[i] == DIR_SEP_CHR) fname[i--] = '\0'; } return; } // Returns true if file filename exists bool exists(const std::string &filename) { #ifdef _WIN32 std::wstring wstr = ConvertUTF8ToWString(filename); return GetFileAttributes(wstr.c_str()) != 0xFFFFFFFF; #else struct stat64 file_info; std::string copy(filename); stripTailDirSlashes(copy); int result = stat64(copy.c_str(), &file_info); return (result == 0); #endif } // Returns true if filename is a directory bool isDirectory(const std::string &filename) { FileInfo info; getFileInfo(filename.c_str(), &info); return info.isDirectory; } bool getFileInfo(const char *path, FileInfo *fileInfo) { // TODO: Expand relative paths? fileInfo->fullName = path; #ifdef _WIN32 WIN32_FILE_ATTRIBUTE_DATA attrs; if (!GetFileAttributesExW(ConvertUTF8ToWString(path).c_str(), GetFileExInfoStandard, &attrs)) { fileInfo->size = 0; fileInfo->isDirectory = false; fileInfo->exists = false; return false; } fileInfo->size = (uint64_t)attrs.nFileSizeLow | ((uint64_t)attrs.nFileSizeHigh << 32); fileInfo->isDirectory = (attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; fileInfo->isWritable = (attrs.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0; fileInfo->exists = true; #else struct stat64 file_info; std::string copy(path); stripTailDirSlashes(copy); int result = stat64(copy.c_str(), &file_info); if (result < 0) { WLOG("IsDirectory: stat failed on %s", path); fileInfo->exists = false; return false; } fileInfo->isDirectory = S_ISDIR(file_info.st_mode); fileInfo->isWritable = false; fileInfo->size = file_info.st_size; fileInfo->exists = true; // HACK: approximation if (file_info.st_mode & 0200) fileInfo->isWritable = true; #endif return true; } std::string getFileExtension(const std::string &fn) { int pos = (int)fn.rfind("."); if (pos < 0) return ""; std::string ext = fn.substr(pos+1); for (size_t i = 0; i < ext.size(); i++) { ext[i] = tolower(ext[i]); } return ext; } bool FileInfo::operator <(const FileInfo &other) const { if (isDirectory && !other.isDirectory) return true; else if (!isDirectory && other.isDirectory) return false; if (strcasecmp(name.c_str(), other.name.c_str()) < 0) return true; else return false; } size_t getFilesInDir(const char *directory, std::vector<FileInfo> *files, const char *filter) { size_t foundEntries = 0; std::set<std::string> filters; std::string tmp; if (filter) { while (*filter) { if (*filter == ':') { filters.insert(tmp); tmp = ""; } else { tmp.push_back(*filter); } filter++; } } if (tmp.size()) filters.insert(tmp); #ifdef _WIN32 // Find the first file in the directory. WIN32_FIND_DATA ffd; #ifdef UNICODE HANDLE hFind = FindFirstFile((ConvertUTF8ToWString(directory) + L"\\*").c_str(), &ffd); #else HANDLE hFind = FindFirstFile((std::string(directory) + "\\*").c_str(), &ffd); #endif if (hFind == INVALID_HANDLE_VALUE) { FindClose(hFind); return 0; } // windows loop do { const std::string virtualName = ConvertWStringToUTF8(ffd.cFileName); #else struct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; }; struct dirent_large diren; struct dirent *result = NULL; //std::string directoryWithSlash = directory; //if (directoryWithSlash.back() != '/') // directoryWithSlash += "/"; DIR *dirp = opendir(directory); if (!dirp) return 0; // non windows loop while (!readdir_r(dirp, (dirent*) &diren, &result) && result) { const std::string virtualName(result->d_name); #endif // check for "." and ".." if (((virtualName[0] == '.') && (virtualName[1] == '\0')) || ((virtualName[0] == '.') && (virtualName[1] == '.') && (virtualName[2] == '\0'))) continue; // Remove dotfiles (should be made optional?) if (virtualName[0] == '.') continue; FileInfo info; info.name = virtualName; info.fullName = std::string(directory) + "/" + virtualName; info.isDirectory = isDirectory(info.fullName); info.exists = true; info.size = 0; if (!info.isDirectory) { std::string ext = getFileExtension(info.fullName); if (filter) { if (filters.find(ext) == filters.end()) continue; } } files->push_back(info); #ifdef _WIN32 } while (FindNextFile(hFind, &ffd) != 0); FindClose(hFind); #else } closedir(dirp); #endif std::sort(files->begin(), files->end()); return foundEntries; } void deleteFile(const char *file) { #ifdef _WIN32 if (!DeleteFile(ConvertUTF8ToWString(file).c_str())) { ELOG("Error deleting %s: %i", file, GetLastError()); } #else int err = unlink(file); if (err) { ELOG("Error unlinking %s: %i", file, err); } #endif } void deleteDir(const char *dir) { #ifdef _WIN32 if (!RemoveDirectory(ConvertUTF8ToWString(dir).c_str())) { ELOG("Error deleting directory %s: %i", dir, GetLastError()); } #else rmdir(dir); #endif } #endif std::string getDir(const std::string &path) { if (path == "/") return path; int n = (int)path.size() - 1; while (n >= 0 && path[n] != '\\' && path[n] != '/') n--; std::string cutpath = n > 0 ? path.substr(0, n) : ""; for (size_t i = 0; i < cutpath.size(); i++) { if (cutpath[i] == '\\') cutpath[i] = '/'; } #ifndef _WIN32 if (!cutpath.size()) { return "/"; } #endif return cutpath; } std::string getFilename(std::string path) { size_t off = getDir(path).size() + 1; if (off < path.size()) return path.substr(off); else return path; } void mkDir(const std::string &path) { #ifdef _WIN32 mkdir(path.c_str()); #else mkdir(path.c_str(), 0777); #endif } #ifdef _WIN32 // Returns a vector with the device names std::vector<std::string> getWindowsDrives() { std::vector<std::string> drives; const DWORD buffsize = GetLogicalDriveStrings(0, NULL); std::vector<TCHAR> buff(buffsize); if (GetLogicalDriveStrings(buffsize, buff.data()) == buffsize - 1) { auto drive = buff.data(); while (*drive) { std::string str(ConvertWStringToUTF8(drive)); str.pop_back(); // we don't want the final backslash str += "/"; drives.push_back(str); // advance to next drive while (*drive++) {} } } return drives; } #endif <commit_msg>Only append a slash to the directory if there isn't one on the end.<commit_after>#ifdef _WIN32 #define WIN32_LEAN_AND_MEAN #include <Windows.h> #include <direct.h> #ifndef strcasecmp #define strcasecmp _stricmp #endif #else #include <dirent.h> #include <unistd.h> #include <errno.h> #endif #include <cstring> #include <string> #include <set> #include <algorithm> #include <cstdio> #include <sys/stat.h> #include <ctype.h> #include "base/logging.h" #include "base/basictypes.h" #include "file/file_util.h" #include "util/text/utf8.h" #if defined(__FreeBSD__) || defined(__APPLE__) || defined(__SYMBIAN32__) #define stat64 stat #endif // Hack #ifdef __SYMBIAN32__ static inline int readdir_r(DIR *dirp, struct dirent *entry, struct dirent **result) { struct dirent *readdir_entry; readdir_entry = readdir(dirp); if (readdir_entry == NULL) { *result = NULL; return errno; } *entry = *readdir_entry; *result = entry; return 0; } #endif FILE *openCFile(const std::string &filename, const char *mode) { #if defined(_WIN32) && defined(UNICODE) return _wfopen(ConvertUTF8ToWString(filename).c_str(), ConvertUTF8ToWString(mode).c_str()); #else return fopen(filename.c_str(), mode); #endif } bool writeStringToFile(bool text_file, const std::string &str, const char *filename) { FILE *f = openCFile(filename, text_file ? "w" : "wb"); if (!f) return false; size_t len = str.size(); if (len != fwrite(str.data(), 1, str.size(), f)) { fclose(f); return false; } fclose(f); return true; } bool writeDataToFile(bool text_file, const void* data, const unsigned int size, const char *filename) { FILE *f = openCFile(filename, text_file ? "w" : "wb"); if (!f) return false; size_t len = size; if (len != fwrite(data, 1, len, f)) { fclose(f); return false; } fclose(f); return true; } uint64_t GetSize(FILE *f) { // can't use off_t here because it can be 32-bit uint64_t pos = ftell(f); if (fseek(f, 0, SEEK_END) != 0) { return 0; } uint64_t size = ftell(f); // Reset the seek position to where it was when we started. if ((size != pos) && (fseek(f, pos, SEEK_SET) != 0)) { // Should error here return 0; } return size; } bool readFileToString(bool text_file, const char *filename, std::string &str) { FILE *f = openCFile(filename, text_file ? "r" : "rb"); if (!f) return false; size_t len = (size_t)GetSize(f); char *buf = new char[len + 1]; buf[fread(buf, 1, len, f)] = 0; str = std::string(buf, len); fclose(f); delete [] buf; return true; } bool readDataFromFile(bool text_file, unsigned char* &data, const unsigned int size, const char *filename) { FILE *f = openCFile(filename, text_file ? "r" : "rb"); if (!f) return false; size_t len = (size_t)GetSize(f); if(len < size) { fclose(f); return false; } data[fread(data, 1, size, f)] = 0; fclose(f); return true; } #define DIR_SEP "/" #define DIR_SEP_CHR '\\' #ifndef METRO // Remove any ending forward slashes from directory paths // Modifies argument. static void stripTailDirSlashes(std::string &fname) { if (fname.length() > 1) { size_t i = fname.length() - 1; while (fname[i] == DIR_SEP_CHR) fname[i--] = '\0'; } return; } // Returns true if file filename exists bool exists(const std::string &filename) { #ifdef _WIN32 std::wstring wstr = ConvertUTF8ToWString(filename); return GetFileAttributes(wstr.c_str()) != 0xFFFFFFFF; #else struct stat64 file_info; std::string copy(filename); stripTailDirSlashes(copy); int result = stat64(copy.c_str(), &file_info); return (result == 0); #endif } // Returns true if filename is a directory bool isDirectory(const std::string &filename) { FileInfo info; getFileInfo(filename.c_str(), &info); return info.isDirectory; } bool getFileInfo(const char *path, FileInfo *fileInfo) { // TODO: Expand relative paths? fileInfo->fullName = path; #ifdef _WIN32 WIN32_FILE_ATTRIBUTE_DATA attrs; if (!GetFileAttributesExW(ConvertUTF8ToWString(path).c_str(), GetFileExInfoStandard, &attrs)) { fileInfo->size = 0; fileInfo->isDirectory = false; fileInfo->exists = false; return false; } fileInfo->size = (uint64_t)attrs.nFileSizeLow | ((uint64_t)attrs.nFileSizeHigh << 32); fileInfo->isDirectory = (attrs.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) != 0; fileInfo->isWritable = (attrs.dwFileAttributes & FILE_ATTRIBUTE_READONLY) == 0; fileInfo->exists = true; #else struct stat64 file_info; std::string copy(path); stripTailDirSlashes(copy); int result = stat64(copy.c_str(), &file_info); if (result < 0) { WLOG("IsDirectory: stat failed on %s", path); fileInfo->exists = false; return false; } fileInfo->isDirectory = S_ISDIR(file_info.st_mode); fileInfo->isWritable = false; fileInfo->size = file_info.st_size; fileInfo->exists = true; // HACK: approximation if (file_info.st_mode & 0200) fileInfo->isWritable = true; #endif return true; } std::string getFileExtension(const std::string &fn) { int pos = (int)fn.rfind("."); if (pos < 0) return ""; std::string ext = fn.substr(pos+1); for (size_t i = 0; i < ext.size(); i++) { ext[i] = tolower(ext[i]); } return ext; } bool FileInfo::operator <(const FileInfo &other) const { if (isDirectory && !other.isDirectory) return true; else if (!isDirectory && other.isDirectory) return false; if (strcasecmp(name.c_str(), other.name.c_str()) < 0) return true; else return false; } size_t getFilesInDir(const char *directory, std::vector<FileInfo> *files, const char *filter) { size_t foundEntries = 0; std::set<std::string> filters; std::string tmp; if (filter) { while (*filter) { if (*filter == ':') { filters.insert(tmp); tmp = ""; } else { tmp.push_back(*filter); } filter++; } } if (tmp.size()) filters.insert(tmp); #ifdef _WIN32 // Find the first file in the directory. WIN32_FIND_DATA ffd; #ifdef UNICODE HANDLE hFind = FindFirstFile((ConvertUTF8ToWString(directory) + L"\\*").c_str(), &ffd); #else HANDLE hFind = FindFirstFile((std::string(directory) + "\\*").c_str(), &ffd); #endif if (hFind == INVALID_HANDLE_VALUE) { FindClose(hFind); return 0; } // windows loop do { const std::string virtualName = ConvertWStringToUTF8(ffd.cFileName); #else struct dirent_large { struct dirent entry; char padding[FILENAME_MAX+1]; }; struct dirent_large diren; struct dirent *result = NULL; //std::string directoryWithSlash = directory; //if (directoryWithSlash.back() != '/') // directoryWithSlash += "/"; DIR *dirp = opendir(directory); if (!dirp) return 0; // non windows loop while (!readdir_r(dirp, (dirent*) &diren, &result) && result) { const std::string virtualName(result->d_name); #endif // check for "." and ".." if (((virtualName[0] == '.') && (virtualName[1] == '\0')) || ((virtualName[0] == '.') && (virtualName[1] == '.') && (virtualName[2] == '\0'))) continue; // Remove dotfiles (should be made optional?) if (virtualName[0] == '.') continue; FileInfo info; info.name = virtualName; std::string dir = directory; // Only append a slash if there isn't one on the end. size_t lastSlash = dir.find_last_of("/"); if (lastSlash != (dir.length() - 1)) dir.append("/"); info.fullName = dir + virtualName; info.isDirectory = isDirectory(info.fullName); info.exists = true; info.size = 0; if (!info.isDirectory) { std::string ext = getFileExtension(info.fullName); if (filter) { if (filters.find(ext) == filters.end()) continue; } } files->push_back(info); #ifdef _WIN32 } while (FindNextFile(hFind, &ffd) != 0); FindClose(hFind); #else } closedir(dirp); #endif std::sort(files->begin(), files->end()); return foundEntries; } void deleteFile(const char *file) { #ifdef _WIN32 if (!DeleteFile(ConvertUTF8ToWString(file).c_str())) { ELOG("Error deleting %s: %i", file, GetLastError()); } #else int err = unlink(file); if (err) { ELOG("Error unlinking %s: %i", file, err); } #endif } void deleteDir(const char *dir) { #ifdef _WIN32 if (!RemoveDirectory(ConvertUTF8ToWString(dir).c_str())) { ELOG("Error deleting directory %s: %i", dir, GetLastError()); } #else rmdir(dir); #endif } #endif std::string getDir(const std::string &path) { if (path == "/") return path; int n = (int)path.size() - 1; while (n >= 0 && path[n] != '\\' && path[n] != '/') n--; std::string cutpath = n > 0 ? path.substr(0, n) : ""; for (size_t i = 0; i < cutpath.size(); i++) { if (cutpath[i] == '\\') cutpath[i] = '/'; } #ifndef _WIN32 if (!cutpath.size()) { return "/"; } #endif return cutpath; } std::string getFilename(std::string path) { size_t off = getDir(path).size() + 1; if (off < path.size()) return path.substr(off); else return path; } void mkDir(const std::string &path) { #ifdef _WIN32 mkdir(path.c_str()); #else mkdir(path.c_str(), 0777); #endif } #ifdef _WIN32 // Returns a vector with the device names std::vector<std::string> getWindowsDrives() { std::vector<std::string> drives; const DWORD buffsize = GetLogicalDriveStrings(0, NULL); std::vector<TCHAR> buff(buffsize); if (GetLogicalDriveStrings(buffsize, buff.data()) == buffsize - 1) { auto drive = buff.data(); while (*drive) { std::string str(ConvertWStringToUTF8(drive)); str.pop_back(); // we don't want the final backslash str += "/"; drives.push_back(str); // advance to next drive while (*drive++) {} } } return drives; } #endif <|endoftext|>
<commit_before>/*************************************************************************** * containers/test_map.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2005, 2006 Roman Dementiev <dementiev@ira.uka.de> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <algorithm> #include <cmath> #include <stxxl/map> typedef unsigned int key_type; typedef unsigned int data_type; struct cmp : public std::less<key_type> { static key_type min_value() { return (std::numeric_limits<key_type>::min)(); } static key_type max_value() { return (std::numeric_limits<key_type>::max)(); } }; #define BLOCK_SIZE (32 * 1024) #define CACHE_SIZE (2 * 1024 * 1024 / BLOCK_SIZE) #define CACHE_ELEMENTS (BLOCK_SIZE * CACHE_SIZE / (sizeof(key_type) + sizeof(data_type))) typedef stxxl::map<key_type, data_type, cmp, BLOCK_SIZE, BLOCK_SIZE> map_type; int main(int argc, char ** argv) { stxxl::stats * bm = stxxl::stats::get_instance(); STXXL_MSG(*bm); STXXL_MSG("Block size " << BLOCK_SIZE / 1024 << " kb"); STXXL_MSG("Cache size " << (CACHE_SIZE * BLOCK_SIZE) / 1024 << " kb"); int max_mult = 256; if (argc > 1) max_mult = atoi(argv[1]); for (int mult = 1; mult < max_mult; mult *= 2) { const unsigned el = mult * (CACHE_ELEMENTS / 8); STXXL_MSG("Elements to insert " << el << " volume =" << (el * (sizeof(key_type) + sizeof(data_type))) / 1024 << " kb"); map_type * DMap = new map_type(CACHE_SIZE * BLOCK_SIZE / 2, CACHE_SIZE * BLOCK_SIZE / 2); //map_type Map(CACHE_SIZE*BLOCK_SIZE/2,CACHE_SIZE*BLOCK_SIZE/2); map_type & Map = *DMap; for (unsigned i = 0; i < el; ++i) { Map[i] = i + 1; } double writes = double(bm->get_writes()) / double(el); double logel = log(double(el)) / log(double(BLOCK_SIZE)); STXXL_MSG("Logs: writes " << writes << " logel " << logel << " writes/logel " << (writes / logel)); STXXL_MSG(*bm); bm->reset(); STXXL_MSG("Doing search"); unsigned queries = el; const map_type & ConstMap = Map; stxxl::random_number32 myrandom; for (unsigned i = 0; i < queries; ++i) { key_type key = myrandom() % el; map_type::const_iterator result = ConstMap.find(key); assert((*result).second == key + 1); } double reads = double(bm->get_reads()) / logel; double readsperq = double(bm->get_reads()) / queries; STXXL_MSG("reads/logel " << reads << " readsperq " << readsperq); STXXL_MSG(*bm); bm->reset(); } return 0; } <commit_msg>fix another memory leak found by valgrind<commit_after>/*************************************************************************** * containers/test_map.cpp * * Part of the STXXL. See http://stxxl.sourceforge.net * * Copyright (C) 2005, 2006 Roman Dementiev <dementiev@ira.uka.de> * * Distributed under the Boost Software License, Version 1.0. * (See accompanying file LICENSE_1_0.txt or copy at * http://www.boost.org/LICENSE_1_0.txt) **************************************************************************/ #include <algorithm> #include <cmath> #include <stxxl/map> typedef unsigned int key_type; typedef unsigned int data_type; struct cmp : public std::less<key_type> { static key_type min_value() { return (std::numeric_limits<key_type>::min)(); } static key_type max_value() { return (std::numeric_limits<key_type>::max)(); } }; #define BLOCK_SIZE (32 * 1024) #define CACHE_SIZE (2 * 1024 * 1024 / BLOCK_SIZE) #define CACHE_ELEMENTS (BLOCK_SIZE * CACHE_SIZE / (sizeof(key_type) + sizeof(data_type))) typedef stxxl::map<key_type, data_type, cmp, BLOCK_SIZE, BLOCK_SIZE> map_type; int main(int argc, char ** argv) { stxxl::stats * bm = stxxl::stats::get_instance(); STXXL_MSG(*bm); STXXL_MSG("Block size " << BLOCK_SIZE / 1024 << " kb"); STXXL_MSG("Cache size " << (CACHE_SIZE * BLOCK_SIZE) / 1024 << " kb"); int max_mult = 256; if (argc > 1) max_mult = atoi(argv[1]); for (int mult = 1; mult < max_mult; mult *= 2) { const unsigned el = mult * (CACHE_ELEMENTS / 8); STXXL_MSG("Elements to insert " << el << " volume =" << (el * (sizeof(key_type) + sizeof(data_type))) / 1024 << " kb"); map_type * DMap = new map_type(CACHE_SIZE * BLOCK_SIZE / 2, CACHE_SIZE * BLOCK_SIZE / 2); //map_type Map(CACHE_SIZE*BLOCK_SIZE/2,CACHE_SIZE*BLOCK_SIZE/2); map_type & Map = *DMap; for (unsigned i = 0; i < el; ++i) { Map[i] = i + 1; } double writes = double(bm->get_writes()) / double(el); double logel = log(double(el)) / log(double(BLOCK_SIZE)); STXXL_MSG("Logs: writes " << writes << " logel " << logel << " writes/logel " << (writes / logel)); STXXL_MSG(*bm); bm->reset(); STXXL_MSG("Doing search"); unsigned queries = el; const map_type & ConstMap = Map; stxxl::random_number32 myrandom; for (unsigned i = 0; i < queries; ++i) { key_type key = myrandom() % el; map_type::const_iterator result = ConstMap.find(key); assert((*result).second == key + 1); } double reads = double(bm->get_reads()) / logel; double readsperq = double(bm->get_reads()) / queries; STXXL_MSG("reads/logel " << reads << " readsperq " << readsperq); STXXL_MSG(*bm); bm->reset(); delete DMap; } return 0; } <|endoftext|>
<commit_before>/** * * \file evolution_selection.cc * \remark This file is part of VITA. * * Copyright (C) 2011-2013 EOS di Manlio Morini. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/ * */ #include "evolution_selection.h" #include "environment.h" #include "evolution.h" namespace vita { /// /// \param[in] evo pointer to the evolution strategy. /// selection_strategy::selection_strategy(const evolution *const evo) : evo_(evo) { } /// /// \return the coordinates of a random individual. /// coord selection_strategy::pickup() const { const population &pop(evo_->population()); assert(pop.layers()); const auto layer( pop.layers() == 1 ? 0 : random::between<size_t>(0, pop.layers())); return {layer, random::between<size_t>(0, pop.individuals(layer))}; } /// /// \param[in] target coordinates of a reference individual. /// \return the coordinates of a random individual "near" \a target. /// /// Parameters from the environment: /// * mate_zone - to restrict the selection of individuals to a segment of /// the population; /// * tournament_size - to control number of selected individuals. /// coord selection_strategy::pickup(const coord &target) const { const population &pop(evo_->population()); // return {target.layer, random::ring(target.index, *pop.env().mate_zone, // pop.individuals(target.layer))}; if (target.layer == 0) return {0, random::ring(target.index, *pop.env().mate_zone, pop.individuals(0))}; const auto layer(random::between(target.layer - 1, target.layer + 1)); if (layer == target.layer) return {layer, random::ring(target.index, *pop.env().mate_zone, pop.individuals(layer))}; return {layer, random::between<size_t>(0, pop.individuals(layer))}; } tournament_selection::tournament_selection(const evolution *const evo) : selection_strategy(evo) { } /* /// /// \param[in] target index of an \a individual in the \a population. /// \return index of the best \a individual found. /// /// Tournament selection works by selecting a number of individuals from the /// population at random, a tournament, and then choosing only the best /// of those individuals. /// Recall that better individuals have highter fitnesses. /// coord tournament_selection::tournament(coord target) const { const population &pop(evo_->population()); const unsigned rounds(pop.env().tournament_size); coord sel(pickup(target)); for (unsigned i(1); i < rounds; ++i) { const coord j(pickup(target)); const fitness_t fit_j(evo_->fitness(pop[j])); const fitness_t fit_sel(evo_->fitness(pop[sel])); if (fit_j > fit_sel) sel = j; } return sel; } */ /// /// \return a vector of indexes to individuals ordered in descending /// fitness. /// /// Parameters from the environment: /// * mate_zone - to restrict the selection of individuals to a segment of /// the population; /// * tournament_size - to control selection pressure. /// std::vector<coord> tournament_selection::run() { const population &pop(evo_->population()); const auto rounds(pop.env().tournament_size); const coord target(pickup()); assert(rounds); std::vector<coord> ret(rounds); // This is the inner loop of an insertion sort algorithm. It is simple, // fast (if rounds is small) and doesn't perform too much comparisons. // DO NOT USE std::sort it is way slower. for (unsigned i(0); i < rounds; ++i) { const coord new_index(pickup(target)); const fitness_t new_fitness(evo_->fitness(pop[new_index])); size_t j(0); if (pop[new_index].age > pop.max_age(new_index.layer)) j = i; else { // Where is the insertion point? while (j < i && pop[ret[j]].age < pop.max_age(ret[j].layer) && new_fitness < evo_->fitness(pop[ret[j]])) ++j; // Shift right elements after the insertion point. for (auto k(j); k < i; ++k) ret[k + 1] = ret[k]; } ret[j] = new_index; } #if !defined(NDEBUG) for (size_t i(0); i + 1 < rounds; ++i) if (pop[ret[i]].age < pop.max_age(ret[i].layer) && pop[ret[i + 1]].age < pop.max_age(ret[i + 1].layer)) assert(evo_->fitness(pop[ret[i]]) >= evo_->fitness(pop[ret[i + 1]])); else assert(pop[ret[i + 1]].age > pop.max_age(ret[i + 1].layer)); #endif return ret; } random_selection::random_selection(const evolution *const evo) : selection_strategy(evo) { } /// /// \return a vector of indexes to individuals randomly chosen. /// /// Parameters from the environment: /// * mate_zone - to restrict the selection of individuals to a segment of /// the population; /// * tournament_size - to control number of selected individuals. /// std::vector<coord> random_selection::run() { const size_t size(evo_->population().env().tournament_size); assert(size); std::vector<coord> ret(size); ret[0] = pickup(); // target for (size_t i(1); i < size; ++i) ret[i] = pickup(ret[0]); return ret; } } // namespace vita <commit_msg>Fixed small bug in ALPS selection criterion<commit_after>/** * * \file evolution_selection.cc * \remark This file is part of VITA. * * Copyright (C) 2011-2013 EOS di Manlio Morini. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/ * */ #include "evolution_selection.h" #include "environment.h" #include "evolution.h" namespace vita { /// /// \param[in] evo pointer to the evolution strategy. /// selection_strategy::selection_strategy(const evolution *const evo) : evo_(evo) { } /// /// \return the coordinates of a random individual. /// coord selection_strategy::pickup() const { const population &pop(evo_->population()); assert(pop.layers()); const auto layer( pop.layers() == 1 ? 0 : random::between<size_t>(0, pop.layers())); return {layer, random::between<size_t>(0, pop.individuals(layer))}; } /// /// \param[in] target coordinates of a reference individual. /// \return the coordinates of a random individual "near" \a target. /// /// Parameters from the environment: /// * mate_zone - to restrict the selection of individuals to a segment of /// the population; /// * tournament_size - to control number of selected individuals. /// coord selection_strategy::pickup(const coord &target) const { const population &pop(evo_->population()); // return {target.layer, random::ring(target.index, *pop.env().mate_zone, // pop.individuals(target.layer))}; if (target.layer == 0) return {0, random::ring(target.index, *pop.env().mate_zone, pop.individuals(0))}; const auto layer(random::between(target.layer - 1, target.layer + 1)); if (layer == target.layer) return {layer, random::ring(target.index, *pop.env().mate_zone, pop.individuals(layer))}; return {layer, random::between<size_t>(0, pop.individuals(layer))}; } tournament_selection::tournament_selection(const evolution *const evo) : selection_strategy(evo) { } /* /// /// \param[in] target index of an \a individual in the \a population. /// \return index of the best \a individual found. /// /// Tournament selection works by selecting a number of individuals from the /// population at random, a tournament, and then choosing only the best /// of those individuals. /// Recall that better individuals have highter fitnesses. /// coord tournament_selection::tournament(coord target) const { const population &pop(evo_->population()); const unsigned rounds(pop.env().tournament_size); coord sel(pickup(target)); for (unsigned i(1); i < rounds; ++i) { const coord j(pickup(target)); const fitness_t fit_j(evo_->fitness(pop[j])); const fitness_t fit_sel(evo_->fitness(pop[sel])); if (fit_j > fit_sel) sel = j; } return sel; } */ /// /// \return a vector of indexes to individuals ordered in descending /// fitness. /// /// Parameters from the environment: /// * mate_zone - to restrict the selection of individuals to a segment of /// the population; /// * tournament_size - to control selection pressure. /// std::vector<coord> tournament_selection::run() { const population &pop(evo_->population()); const auto rounds(pop.env().tournament_size); const coord target(pickup()); const auto max_age(pop.max_age(target.layer)); assert(rounds); std::vector<coord> ret(rounds); // This is the inner loop of an insertion sort algorithm. It is simple, // fast (if rounds is small) and doesn't perform too much comparisons. // DO NOT USE std::sort it is way slower. for (unsigned i(0); i < rounds; ++i) { const coord new_index(pickup(target)); const fitness_t new_fitness(evo_->fitness(pop[new_index])); size_t j(0); if (pop[new_index].age > max_age) j = i; else { // Where is the insertion point? while (j < i && pop[ret[j]].age <= max_age && new_fitness < evo_->fitness(pop[ret[j]])) ++j; // Shift right elements after the insertion point. for (auto k(j); k < i; ++k) ret[k + 1] = ret[k]; } ret[j] = new_index; } #if !defined(NDEBUG) for (size_t i(0); i + 1 < rounds; ++i) if (pop[ret[i]].age < max_age && pop[ret[i + 1]].age < max_age) assert(evo_->fitness(pop[ret[i]]) >= evo_->fitness(pop[ret[i + 1]])); else assert(pop[ret[i + 1]].age > max_age); #endif return ret; } random_selection::random_selection(const evolution *const evo) : selection_strategy(evo) { } /// /// \return a vector of indexes to individuals randomly chosen. /// /// Parameters from the environment: /// * mate_zone - to restrict the selection of individuals to a segment of /// the population; /// * tournament_size - to control number of selected individuals. /// std::vector<coord> random_selection::run() { const size_t size(evo_->population().env().tournament_size); assert(size); std::vector<coord> ret(size); ret[0] = pickup(); // target for (size_t i(1); i < size; ++i) ret[i] = pickup(ret[0]); return ret; } } // namespace vita <|endoftext|>
<commit_before>// EntryPoint.cpp #ifdef WIN64 #include <stdlib.h> #include <crtdbg.h> #endif #include "core/src/Platform/EntryPoint.hpp" #include "core/src/Platform/Window.hpp" #include "core/src/system/LBS.hpp" #include "core/src/system/logger.hpp" #include "core/src/entity/database.hpp" #include "core/src/system/time.hpp" #include "core/src/tests/schedulertests.hpp" #include "core/src/tests/bitfield_tests.hpp" #include "core/src/math/mat_templated.hpp" #include "app/Graphics/gfxApi.hpp" #include "core/src/filesystem/filesystem.hpp" #include "core/src/system/memview.hpp" #include "core/src/spirvcross/spirv_glsl.hpp" #include "core/src/tools/renderdoc.hpp" #include "vkShaders/sampleShader.if.hpp" #include <shaderc/shaderc.hpp> #include <cstdio> #include <iostream> #include <sparsepp.h> using namespace faze; int EntryPoint::main() { WTime t; t.firstTick(); Logger log; GraphicsInstance devices; FileSystem fs; if (!devices.createInstance("faze")) { F_ILOG("System", "Failed to create Vulkan instance, exiting"); log.update(); return 1; } { //SchedulerTests::Run(); } RenderDocApi renderdoc; auto main = [&](std::string name) { //LBS lbs; ivec2 ires = { 800, 600 }; vec2 res = { static_cast<float>(ires.x()), static_cast<float>(ires.y()) }; Window window(m_params, name, ires.x(), ires.y()); window.open(); int64_t frame = 1; { GpuDevice gpu = devices.createGpuDevice(fs); WindowSurface surface = devices.createSurface(window); auto swapchain = gpu.createSwapchain(surface, PresentMode::Mailbox); // TODO1: general, advance towards usable images // optional: cleanup texture format //renderdoc.startCapture(); { constexpr int TestBufferSize = 1 * 128; auto testHeap = gpu.createMemoryHeap(HeapDescriptor() .setName("ebin") .sizeInBytes(32000000) .setHeapType(HeapType::Upload)); // 32megs, should be the common size... auto testHeap2 = gpu.createMemoryHeap(HeapDescriptor().setName("ebinTarget").sizeInBytes(32000000).setHeapType(HeapType::Default)); // 32megs, should be the common size... auto testHeap3 = gpu.createMemoryHeap(HeapDescriptor().setName("ebinReadback").sizeInBytes(32000000).setHeapType(HeapType::Readback)); // 32megs, should be the common size... auto buffer = gpu.createBuffer(testHeap, ResourceDescriptor() .setName("testBuffer") .setFormat<float>() .setWidth(TestBufferSize) .setUsage(ResourceUsage::UploadHeap) .setDimension(FormatDimension::Buffer)); auto bufferTarget = gpu.createBuffer(testHeap2, // bind memory fails? ResourceDescriptor() .setName("testBufferTarget") .setFormat<float>() .setWidth(TestBufferSize) .enableUnorderedAccess() .setUsage(ResourceUsage::GpuOnly) .setDimension(FormatDimension::Buffer)); auto bufferTargetUav = gpu.createBufferUAV(bufferTarget); auto computeTarget = gpu.createBuffer(testHeap2, // bind memory fails? ResourceDescriptor() .setName("testBufferTarget") .setFormat<float>() .setWidth(TestBufferSize) .setUsage(ResourceUsage::GpuOnly) .enableUnorderedAccess() .setDimension(FormatDimension::Buffer)); auto computeTargetUav = gpu.createBufferUAV(computeTarget); auto bufferReadb = gpu.createBuffer(testHeap3, ResourceDescriptor() .setName("testBufferTarget") .setFormat<float>() .setWidth(TestBufferSize) .setUsage(ResourceUsage::ReadbackHeap) .setDimension(FormatDimension::Buffer)); auto testTexture = gpu.createTexture(testHeap2, ResourceDescriptor() .setName("TestTexture") .setWidth(800) .setHeight(600) .setFormat(FormatType::R8G8B8A8_Uint) .setDimension(FormatDimension::Texture2D) .setUsage(ResourceUsage::GpuOnly) .setLayout(TextureLayout::StandardSwizzle64kb)); if (buffer.isValid()) { F_LOG("yay! a buffer\n"); { auto map = buffer.Map<float>(0, TestBufferSize); if (map.isValid()) { F_LOG("yay! mapped buffer!\n"); for (auto i = 0; i < TestBufferSize; ++i) { map[i] = 1.f; } } } } ComputePipeline test = gpu.createComputePipeline<SampleShader>(ComputePipelineDescriptor().shader("sampleShader")); { auto gfx = gpu.createGraphicsCommandBuffer(); gfx.copy(buffer, bufferTarget); { auto shif = gfx.bind<SampleShader>(test); shif.read(SampleShader::dataIn, bufferTargetUav); shif.modify(SampleShader::dataOut, computeTargetUav); gfx.dispatchThreads(shif, TestBufferSize); } gpu.submit(gfx); } t.firstTick(); float value = 0.f; while (!window.simpleReadMessages(frame++)) { if (window.hasResized()) { gpu.reCreateSwapchain(swapchain, surface); window.resizeHandled(); } auto& inputs = window.inputs(); if (inputs.isPressedThisFrame(VK_ESCAPE, 1)) { // \o/ is work // mouse next, input capture in window? break; } log.update(); { auto gfx = gpu.createGraphicsCommandBuffer(); auto shif = gfx.bind<SampleShader>(test); for (int k = 0; k < 1; k++) { { shif.read(SampleShader::dataIn, computeTargetUav); shif.modify(SampleShader::dataOut, bufferTargetUav); gfx.dispatchThreads(shif, TestBufferSize); } { shif.read(SampleShader::dataIn, bufferTargetUav); shif.modify(SampleShader::dataOut, computeTargetUav); gfx.dispatchThreads(shif, TestBufferSize); } } gpu.submit(gfx); } { auto rtv = gpu.acquirePresentableImage(swapchain); { auto gfx = gpu.createGraphicsCommandBuffer(); gfx.clearRTV(rtv, value); gpu.submitSwapchain(gfx, swapchain); } gpu.present(swapchain); t.tick(); value += t.getFrameTimeDelta(); if (value > 1.f) value = 0.f; } } // outside windowloop { auto gfx = gpu.createGraphicsCommandBuffer(); gfx.copy(computeTarget, bufferReadb); gpu.submit(gfx); } gpu.waitIdle(); if (bufferReadb.isValid()) { F_LOG("yay! a buffer\n"); { auto map = bufferReadb.Map<float>(0, TestBufferSize); if (map.isValid()) { F_LOG("yay! mapped buffer! %f\n", map[TestBufferSize - 1]); log.update(); } } } //renderdoc.endCapture(); } } }; main("w1"); t.printStatistics(); log.update(); return 0; } <commit_msg>entrypoint starting to be difficult to handle<commit_after>// EntryPoint.cpp #ifdef WIN64 #include <stdlib.h> #include <crtdbg.h> #endif #include "core/src/Platform/EntryPoint.hpp" #include "core/src/Platform/Window.hpp" #include "core/src/system/LBS.hpp" #include "core/src/system/logger.hpp" #include "core/src/entity/database.hpp" #include "core/src/system/time.hpp" #include "core/src/tests/schedulertests.hpp" #include "core/src/tests/bitfield_tests.hpp" #include "core/src/math/mat_templated.hpp" #include "app/Graphics/gfxApi.hpp" #include "core/src/filesystem/filesystem.hpp" #include "core/src/system/memview.hpp" #include "core/src/spirvcross/spirv_glsl.hpp" #include "core/src/tools/renderdoc.hpp" #include "vkShaders/sampleShader.if.hpp" #include <shaderc/shaderc.hpp> #include <cstdio> #include <iostream> #include <sparsepp.h> using namespace faze; int EntryPoint::main() { WTime t; t.firstTick(); Logger log; GraphicsInstance devices; FileSystem fs; if (!devices.createInstance("faze")) { F_ILOG("System", "Failed to create Vulkan instance, exiting"); log.update(); return 1; } { //SchedulerTests::Run(); } RenderDocApi renderdoc; auto main = [&](std::string name) { //LBS lbs; ivec2 ires = { 800, 600 }; vec2 res = { static_cast<float>(ires.x()), static_cast<float>(ires.y()) }; Window window(m_params, name, ires.x(), ires.y()); window.open(); int64_t frame = 1; { GpuDevice gpu = devices.createGpuDevice(fs); WindowSurface surface = devices.createSurface(window); auto swapchain = gpu.createSwapchain(surface, PresentMode::Mailbox); // TODO1: general, advance towards usable images // optional: cleanup texture format //renderdoc.startCapture(); { constexpr int TestBufferSize = 1 * 128; auto testHeap = gpu.createMemoryHeap(HeapDescriptor() .setName("ebin") .sizeInBytes(32000000) .setHeapType(HeapType::Upload)); // 32megs, should be the common size... auto testHeap2 = gpu.createMemoryHeap(HeapDescriptor().setName("ebinTarget").sizeInBytes(32000000).setHeapType(HeapType::Default)); // 32megs, should be the common size... auto testHeap3 = gpu.createMemoryHeap(HeapDescriptor().setName("ebinReadback").sizeInBytes(32000000).setHeapType(HeapType::Readback)); // 32megs, should be the common size... auto buffer = gpu.createBuffer(testHeap, ResourceDescriptor() .setName("testBuffer") .setFormat<float>() .setWidth(TestBufferSize) .setUsage(ResourceUsage::UploadHeap) .setDimension(FormatDimension::Buffer)); auto bufferTarget = gpu.createBuffer(testHeap2, // bind memory fails? ResourceDescriptor() .setName("testBufferTarget") .setFormat<float>() .setWidth(TestBufferSize) .enableUnorderedAccess() .setUsage(ResourceUsage::GpuOnly) .setDimension(FormatDimension::Buffer)); auto bufferTargetUav = gpu.createBufferUAV(bufferTarget); auto computeTarget = gpu.createBuffer(testHeap2, // bind memory fails? ResourceDescriptor() .setName("testBufferTarget") .setFormat<float>() .setWidth(TestBufferSize) .setUsage(ResourceUsage::GpuOnly) .enableUnorderedAccess() .setDimension(FormatDimension::Buffer)); auto computeTargetUav = gpu.createBufferUAV(computeTarget); auto bufferReadb = gpu.createBuffer(testHeap3, ResourceDescriptor() .setName("testBufferTarget") .setFormat<float>() .setWidth(TestBufferSize) .setUsage(ResourceUsage::ReadbackHeap) .setDimension(FormatDimension::Buffer)); auto testTexture = gpu.createTexture(testHeap2, ResourceDescriptor() .setName("TestTexture") .setWidth(800) .setHeight(600) .setFormat(FormatType::R8G8B8A8_Uint) .setDimension(FormatDimension::Texture2D) .setUsage(ResourceUsage::GpuOnly) .setLayout(TextureLayout::StandardSwizzle64kb)); if (buffer.isValid()) { F_LOG("yay! a buffer\n"); { auto map = buffer.Map<float>(0, TestBufferSize); if (map.isValid()) { F_LOG("yay! mapped buffer!\n"); for (auto i = 0; i < TestBufferSize; ++i) { map[i] = 1.f; } } } } ComputePipeline test = gpu.createComputePipeline<SampleShader>(ComputePipelineDescriptor().shader("sampleShader")); { auto gfx = gpu.createGraphicsCommandBuffer(); gfx.copy(buffer, bufferTarget); { auto shif = gfx.bind<SampleShader>(test); shif.read(SampleShader::dataIn, bufferTargetUav); shif.modify(SampleShader::dataOut, computeTargetUav); gfx.dispatchThreads(shif, TestBufferSize); } gpu.submit(gfx); } t.firstTick(); float value = 0.f; while (!window.simpleReadMessages(frame++)) { if (window.hasResized()) { gpu.reCreateSwapchain(swapchain, surface); window.resizeHandled(); } auto& inputs = window.inputs(); if (inputs.isPressedThisFrame(VK_ESCAPE, 1)) { // \o/ is work // mouse next, input capture in window? break; } log.update(); { auto gfx = gpu.createGraphicsCommandBuffer(); auto shif = gfx.bind<SampleShader>(test); for (int k = 0; k < 1; k++) { { shif.read(SampleShader::dataIn, computeTargetUav); shif.modify(SampleShader::dataOut, bufferTargetUav); gfx.dispatchThreads(shif, TestBufferSize); } { shif.read(SampleShader::dataIn, bufferTargetUav); shif.modify(SampleShader::dataOut, computeTargetUav); gfx.dispatchThreads(shif, TestBufferSize); } } gpu.submit(gfx); } { auto rtv = gpu.acquirePresentableImage(swapchain); { auto gfx = gpu.createGraphicsCommandBuffer(); gfx.clearRTV(rtv, value); gpu.submitSwapchain(gfx, swapchain); } gpu.present(swapchain); t.tick(); value += t.getFrameTimeDelta(); if (value > 1.f) value = 0.f; } } // outside windowloop { auto gfx = gpu.createGraphicsCommandBuffer(); gfx.copy(computeTarget, bufferReadb); gpu.submit(gfx); } gpu.waitIdle(); if (bufferReadb.isValid()) { F_LOG("yay! a buffer\n"); { auto map = bufferReadb.Map<float>(0, TestBufferSize); if (map.isValid()) { F_LOG("yay! mapped buffer! %f\n", map[TestBufferSize - 1]); log.update(); } } } //renderdoc.endCapture(); } } }; main("w1"); t.printStatistics(); log.update(); return 0; }<|endoftext|>
<commit_before>/** * \file memory_manager.cpp * \brief impl of * \author Sergey Miryanov * \date 10.06.2009 * */ #include "memory_manager.h" #include "bs_exception.h" #include "bs_assert.h" #include "bs_report.h" #include "bs_kernel.h" // to avoid DUMB linker error we have to include bs_object_base.h #include "bs_object_base.h" #include "bs_tree.h" #include "allocator_interface.h" #if defined (BS_BOS_CORE_TLSF_ALLOCATOR) #include "tlsf_allocator.h" #elif defined (BS_BOS_CORE_HOARD_ALLOCATOR) #include "hoard_allocator.h" #elif defined (BS_BOS_CORE_DLMALLOC_ALLOCATOR) #include "dlmalloc_allocator.h" #elif defined (BS_BOS_CORE_TCMALLOC_ALLOCATOR) #include "tcmalloc_allocator.h" #else #include "std_allocator.h" #endif #ifdef _WIN32 #include <windows.h> #endif #ifdef BS_BOS_CORE_COLLECT_BACKTRACE #ifdef _WIN32 #include "backtrace_tools_win.h" #else #include "backtrace_tools_unix.h" #endif #endif #include "get_thread_id.h" namespace blue_sky { #ifndef BS_BACKTRACE_LEN #define BS_BACKTRACE_LEN 14 #endif struct memory_manager::allocator_info { #ifdef BS_BOS_CORE_COLLECT_BACKTRACE enum { max_backtrace_len = BS_BACKTRACE_LEN, }; struct alloc_info { size_t size_; void *backtrace_[max_backtrace_len]; size_t backtrace_len_; }; #else struct alloc_info { size_t size_; }; #endif struct dealloc_info { size_t alloc_count; size_t dealloc_count; dealloc_info () : alloc_count (0), dealloc_count (0) { } }; typedef std::map <void *, alloc_info> alloc_map_t; typedef std::map <void *, dealloc_info> dealloc_map_t; allocator_info () : alloc_call_count (0), dealloc_call_count (0), total_alloc_size (0), total_dealloc_size (0), alloc_size (0) { } size_t alloc_call_count; size_t dealloc_call_count; size_t total_alloc_size; size_t total_dealloc_size; size_t alloc_size; alloc_map_t alloc_map; dealloc_map_t dealloc_map; }; memory_manager::memory_manager () : alloc_ (0), dealloc_ (0) { alloc_ = &allocator_t::instance (); dealloc_ = &allocator_t::instance (); } memory_manager::~memory_manager () { } bool memory_manager::set_backend_allocator (allocator_interface *a) { if (alloc_ != dealloc_) { return false; } #ifdef BS_BOS_CORE_DEBUG_MEMORY BSOUT << "memory_manager: swap memory allocators begin" << bs_end; #endif dealloc_ = alloc_; alloc_ = a; return true; } void * memory_manager::allocate (size_t size) { char *ptr = (char *)alloc_->allocate (size); if (!ptr) { #ifdef BS_BOS_CORE_DEBUG_MEMORY print_info (); #endif throw bs_exception ("memory_manager::allocate_aligned", "Can't allocate memory"); } #ifdef BS_BOS_CORE_DEBUG_MEMORY store_allocate_info (ptr, size); #endif return ptr; } void memory_manager::deallocate (void *ptr) { if (!ptr) { BS_ASSERT (ptr); return ; } dealloc_->deallocate (ptr); if (alloc_ != dealloc_ && dealloc_->empty ()) { #ifdef BS_BOS_CORE_DEBUG_MEMORY BSOUT << "memory_manager: swap memory allocators complete" << bs_end; #endif dealloc_ = alloc_; } #ifdef BS_BOS_CORE_DEBUG_MEMORY store_deallocate_info (ptr); #endif } void * memory_manager::allocate_aligned (size_t size, size_t alignment) { size += alignment - 1; size += sizeof (ptr_diff_t); char *ptr = (char *)allocate (size); BS_ASSERT (ptr); ptr_diff_t new_ptr = (ptr_diff_t)ptr + sizeof (ptr_diff_t); char *aligned_ptr = (char *)((new_ptr + alignment - 1) & ~(alignment - 1)); ptr_diff_t diff = aligned_ptr - ptr; *((ptr_diff_t *)aligned_ptr - 1) = diff; return aligned_ptr; } void memory_manager::deallocate_aligned (void *ptr_) { if (ptr_ == 0) { BS_ASSERT (ptr_); return ; } ptr_diff_t diff = *((ptr_diff_t *)ptr_ - 1); char *ptr = (char *)ptr_ - diff; deallocate (ptr); } void memory_manager::store_allocate_info (void *ptr, size_t size) { thread_id_t thread_id = detail::get_thread_id (); allocator_info *info = get_allocator_info (allocator_info_map, thread_id); BS_ASSERT (info) ((size_t)ptr) (size) (thread_id); info->alloc_call_count++; info->alloc_size += size; info->total_alloc_size += size; allocator_info::alloc_map_t::iterator address_it = info->alloc_map.find (ptr); if (address_it != info->alloc_map.end ()) { print_allocate (ptr, size); print_info (info); throw bs_exception ("memory_manager::allocate", "allocate aready allocated memory"); } allocator_info::alloc_info ai; ai.size_ = size; #ifdef BS_BOS_CORE_COLLECT_BACKTRACE ai.backtrace_len_ = tools::get_backtrace (ai.backtrace_, allocator_info::max_backtrace_len); #endif info->alloc_map.insert (std::make_pair (ptr, ai)); #ifdef BS_BOS_CORE_PRINT_ALLOC_INFO BSOUT << "mem_mgr: allocate [" << ptr << " - " << size << "]" << bs_end; #endif #ifdef BS_BOS_CORE_STORE_DEALLOCATE_INFO allocator_info::dealloc_map_t::iterator dealloc_it = info->dealloc_map.find (ptr); if (dealloc_it != info->dealloc_map.end ()) { dealloc_it->second.alloc_count++; } #endif } void memory_manager::store_deallocate_info (void *ptr) { thread_id_t thread_id = detail::get_thread_id (); allocator_info *info = get_allocator_info (allocator_info_map, thread_id); BS_ASSERT (info) ((size_t)ptr) (thread_id); allocator_info::alloc_map_t::iterator address_it = info->alloc_map.find (ptr); if (address_it == info->alloc_map.end ()) { print_deallocate (ptr); print_info (info); throw bs_exception ("memory_manager::deallocate", "deallocate unknown memory"); } #ifdef BS_BOS_CORE_PRINT_ALLOC_INFO BSOUT << "mem_mgr: deallocate [" << ptr << " - " << address_it->second.size_ << "]" << bs_end; #endif info->dealloc_call_count++; info->total_dealloc_size += address_it->second.size_; info->alloc_size -= address_it->second.size_; info->alloc_map.erase (address_it); #ifdef BS_BOS_CORE_STORE_DEALLOCATE_INFO allocator_info::dealloc_map_t::iterator dealloc_it = info->dealloc_map.find (ptr); if (dealloc_it == info->dealloc_map.end ()) { allocator_info::dealloc_info di; di.dealloc_count = 1; di.alloc_count = 1; info->dealloc_map.insert (std::make_pair (ptr, di)); } else { dealloc_it->second.dealloc_count++; } #endif } memory_manager::allocator_info * memory_manager::get_allocator_info (allocator_info_map_t &locked_info, thread_id_t thread_id) { allocator_info *info = 0; allocator_info_map_t::iterator it = locked_info.find (thread_id); if (it == locked_info.end ()) { info = new allocator_info; locked_info.insert (std::make_pair (thread_id, info)); } else { info = it->second; } return info; } void memory_manager::print_allocate (void *ptr, size_t size) { BSOUT << "allocate: " << ptr << " - " << size << bs_end; } void memory_manager::print_deallocate (void *ptr) { BSOUT << "deallocate: " << ptr << bs_end; } void memory_manager::print_info (allocator_info *info, bool print_map) { #ifdef BS_BOS_CORE_DEBUG_MEMORY BSOUT << "allocate_count: " << info->alloc_call_count << bs_end; BSOUT << "deallocate_count: " << info->dealloc_call_count << bs_end; BSOUT << "total_alloc_size: " << info->total_alloc_size << bs_end; BSOUT << "total_dealloc_size: " << info->total_dealloc_size << bs_end; BSOUT << "alloc_size: " << info->alloc_size << bs_end; if (print_map) { BSOUT << "alloc_map: " << bs_end; allocator_info::alloc_map_t::iterator it = info->alloc_map.begin (), e = info->alloc_map.end (); for (; it != e; ++it) { const allocator_info::alloc_info &ai = it->second; BSOUT << "\t[" << (void *)it->first << " : " << ai.size_ << "]" << bs_end; #ifdef BS_BOS_CORE_COLLECT_BACKTRACE char **backtrace_names = tools::get_backtrace_names (ai.backtrace_, ai.backtrace_len_); for (size_t i = 0; i < ai.backtrace_len_; ++i) { if (backtrace_names[i] && strlen (backtrace_names[i])) { BSOUT << "\t\t" << i << ": " << backtrace_names[i] << bs_end; } } free (backtrace_names); #endif } } #endif } void memory_manager::print_info (bool print_map) { #ifdef BS_BOS_CORE_DEBUG_MEMORY thread_id_t thread_id = detail::get_thread_id (); allocator_info *info = get_allocator_info (allocator_info_map, thread_id); BS_ASSERT (info) (thread_id); print_info (info, print_map); #endif } } // namespace blue_sky <commit_msg>Edit: Add max_alloc_size to memory_manager<commit_after>/** * \file memory_manager.cpp * \brief impl of * \author Sergey Miryanov * \date 10.06.2009 * */ #include "memory_manager.h" #include "bs_exception.h" #include "bs_assert.h" #include "bs_report.h" #include "bs_kernel.h" // to avoid DUMB linker error we have to include bs_object_base.h #include "bs_object_base.h" #include "bs_tree.h" #include "allocator_interface.h" #if defined (BS_BOS_CORE_TLSF_ALLOCATOR) #include "tlsf_allocator.h" #elif defined (BS_BOS_CORE_HOARD_ALLOCATOR) #include "hoard_allocator.h" #elif defined (BS_BOS_CORE_DLMALLOC_ALLOCATOR) #include "dlmalloc_allocator.h" #elif defined (BS_BOS_CORE_TCMALLOC_ALLOCATOR) #include "tcmalloc_allocator.h" #else #include "std_allocator.h" #endif #ifdef _WIN32 #include <windows.h> #endif #ifdef BS_BOS_CORE_COLLECT_BACKTRACE #ifdef _WIN32 #include "backtrace_tools_win.h" #else #include "backtrace_tools_unix.h" #endif #endif #include "get_thread_id.h" namespace blue_sky { #ifndef BS_BACKTRACE_LEN #define BS_BACKTRACE_LEN 14 #endif struct memory_manager::allocator_info { #ifdef BS_BOS_CORE_COLLECT_BACKTRACE enum { max_backtrace_len = BS_BACKTRACE_LEN, }; struct alloc_info { size_t size_; void *backtrace_[max_backtrace_len]; size_t backtrace_len_; }; #else struct alloc_info { size_t size_; }; #endif struct dealloc_info { size_t alloc_count; size_t dealloc_count; dealloc_info () : alloc_count (0), dealloc_count (0) { } }; typedef std::map <void *, alloc_info> alloc_map_t; typedef std::map <void *, dealloc_info> dealloc_map_t; allocator_info () : alloc_call_count (0), dealloc_call_count (0), total_alloc_size (0), total_dealloc_size (0), alloc_size (0), max_alloc_size (0) { } size_t alloc_call_count; size_t dealloc_call_count; size_t total_alloc_size; size_t total_dealloc_size; size_t alloc_size; size_t max_alloc_size; alloc_map_t alloc_map; dealloc_map_t dealloc_map; }; memory_manager::memory_manager () : alloc_ (0), dealloc_ (0) { alloc_ = &allocator_t::instance (); dealloc_ = &allocator_t::instance (); } memory_manager::~memory_manager () { } bool memory_manager::set_backend_allocator (allocator_interface *a) { if (alloc_ != dealloc_) { return false; } #ifdef BS_BOS_CORE_DEBUG_MEMORY BSOUT << "memory_manager: swap memory allocators begin" << bs_end; #endif dealloc_ = alloc_; alloc_ = a; return true; } void * memory_manager::allocate (size_t size) { char *ptr = (char *)alloc_->allocate (size); if (!ptr) { #ifdef BS_BOS_CORE_DEBUG_MEMORY print_info (); #endif throw bs_exception ("memory_manager::allocate_aligned", "Can't allocate memory"); } #ifdef BS_BOS_CORE_DEBUG_MEMORY store_allocate_info (ptr, size); #endif return ptr; } void memory_manager::deallocate (void *ptr) { if (!ptr) { BS_ASSERT (ptr); return ; } dealloc_->deallocate (ptr); if (alloc_ != dealloc_ && dealloc_->empty ()) { #ifdef BS_BOS_CORE_DEBUG_MEMORY BSOUT << "memory_manager: swap memory allocators complete" << bs_end; #endif dealloc_ = alloc_; } #ifdef BS_BOS_CORE_DEBUG_MEMORY store_deallocate_info (ptr); #endif } void * memory_manager::allocate_aligned (size_t size, size_t alignment) { size += alignment - 1; size += sizeof (ptr_diff_t); char *ptr = (char *)allocate (size); BS_ASSERT (ptr); ptr_diff_t new_ptr = (ptr_diff_t)ptr + sizeof (ptr_diff_t); char *aligned_ptr = (char *)((new_ptr + alignment - 1) & ~(alignment - 1)); ptr_diff_t diff = aligned_ptr - ptr; *((ptr_diff_t *)aligned_ptr - 1) = diff; return aligned_ptr; } void memory_manager::deallocate_aligned (void *ptr_) { if (ptr_ == 0) { BS_ASSERT (ptr_); return ; } ptr_diff_t diff = *((ptr_diff_t *)ptr_ - 1); char *ptr = (char *)ptr_ - diff; deallocate (ptr); } void memory_manager::store_allocate_info (void *ptr, size_t size) { thread_id_t thread_id = detail::get_thread_id (); allocator_info *info = get_allocator_info (allocator_info_map, thread_id); BS_ASSERT (info) ((size_t)ptr) (size) (thread_id); info->alloc_call_count++; info->alloc_size += size; info->total_alloc_size += size; if (info->alloc_size > info->max_alloc_size) { info->max_alloc_size = info->alloc_size; } allocator_info::alloc_map_t::iterator address_it = info->alloc_map.find (ptr); if (address_it != info->alloc_map.end ()) { print_allocate (ptr, size); print_info (info); throw bs_exception ("memory_manager::allocate", "allocate aready allocated memory"); } allocator_info::alloc_info ai; ai.size_ = size; #ifdef BS_BOS_CORE_COLLECT_BACKTRACE ai.backtrace_len_ = tools::get_backtrace (ai.backtrace_, allocator_info::max_backtrace_len); #endif info->alloc_map.insert (std::make_pair (ptr, ai)); #ifdef BS_BOS_CORE_PRINT_ALLOC_INFO BSOUT << "mem_mgr: allocate [" << ptr << " - " << size << "]" << bs_end; #endif #ifdef BS_BOS_CORE_STORE_DEALLOCATE_INFO allocator_info::dealloc_map_t::iterator dealloc_it = info->dealloc_map.find (ptr); if (dealloc_it != info->dealloc_map.end ()) { dealloc_it->second.alloc_count++; } #endif } void memory_manager::store_deallocate_info (void *ptr) { thread_id_t thread_id = detail::get_thread_id (); allocator_info *info = get_allocator_info (allocator_info_map, thread_id); BS_ASSERT (info) ((size_t)ptr) (thread_id); allocator_info::alloc_map_t::iterator address_it = info->alloc_map.find (ptr); if (address_it == info->alloc_map.end ()) { print_deallocate (ptr); print_info (info); throw bs_exception ("memory_manager::deallocate", "deallocate unknown memory"); } #ifdef BS_BOS_CORE_PRINT_ALLOC_INFO BSOUT << "mem_mgr: deallocate [" << ptr << " - " << address_it->second.size_ << "]" << bs_end; #endif info->dealloc_call_count++; info->total_dealloc_size += address_it->second.size_; info->alloc_size -= address_it->second.size_; info->alloc_map.erase (address_it); #ifdef BS_BOS_CORE_STORE_DEALLOCATE_INFO allocator_info::dealloc_map_t::iterator dealloc_it = info->dealloc_map.find (ptr); if (dealloc_it == info->dealloc_map.end ()) { allocator_info::dealloc_info di; di.dealloc_count = 1; di.alloc_count = 1; info->dealloc_map.insert (std::make_pair (ptr, di)); } else { dealloc_it->second.dealloc_count++; } #endif } memory_manager::allocator_info * memory_manager::get_allocator_info (allocator_info_map_t &locked_info, thread_id_t thread_id) { allocator_info *info = 0; allocator_info_map_t::iterator it = locked_info.find (thread_id); if (it == locked_info.end ()) { info = new allocator_info; locked_info.insert (std::make_pair (thread_id, info)); } else { info = it->second; } return info; } void memory_manager::print_allocate (void *ptr, size_t size) { BSOUT << "allocate: " << ptr << " - " << size << bs_end; } void memory_manager::print_deallocate (void *ptr) { BSOUT << "deallocate: " << ptr << bs_end; } void memory_manager::print_info (allocator_info *info, bool print_map) { #ifdef BS_BOS_CORE_DEBUG_MEMORY BSOUT << "allocate_count: " << info->alloc_call_count << bs_end; BSOUT << "deallocate_count: " << info->dealloc_call_count << bs_end; BSOUT << "total_alloc_size: " << info->total_alloc_size << bs_end; BSOUT << "total_dealloc_size: " << info->total_dealloc_size << bs_end; BSOUT << "alloc_size: " << info->alloc_size << bs_end; BSOUT << "max_alloc_size: " << info->max_alloc_size << bs_end; if (print_map) { BSOUT << "alloc_map: " << bs_end; allocator_info::alloc_map_t::iterator it = info->alloc_map.begin (), e = info->alloc_map.end (); for (; it != e; ++it) { const allocator_info::alloc_info &ai = it->second; BSOUT << "\t[" << (void *)it->first << " : " << ai.size_ << "]" << bs_end; #ifdef BS_BOS_CORE_COLLECT_BACKTRACE char **backtrace_names = tools::get_backtrace_names (ai.backtrace_, ai.backtrace_len_); for (size_t i = 0; i < ai.backtrace_len_; ++i) { if (backtrace_names[i] && strlen (backtrace_names[i])) { BSOUT << "\t\t" << i << ": " << backtrace_names[i] << bs_end; } } free (backtrace_names); #endif } } #endif } void memory_manager::print_info (bool print_map) { #ifdef BS_BOS_CORE_DEBUG_MEMORY thread_id_t thread_id = detail::get_thread_id (); allocator_info *info = get_allocator_info (allocator_info_map, thread_id); BS_ASSERT (info) (thread_id); print_info (info, print_map); #endif } } // namespace blue_sky <|endoftext|>
<commit_before><commit_msg>Handle dictionaries in the same way in localize<commit_after><|endoftext|>
<commit_before>/** * @author Koen Wolters <koen.wolters@cern.ch> */ #include "DetectorHistogrammerTestModule.hpp" #include <memory> #include <string> #include <utility> #include <TApplication.h> #include <TFile.h> #include <TH2D.h> #include "core/geometry/PixelDetectorModel.hpp" #include "core/messenger/Messenger.hpp" #include "core/utils/log.h" using namespace allpix; const std::string DetectorHistogrammerModule::name = "detector_histogrammer_test"; DetectorHistogrammerModule::DetectorHistogrammerModule(Configuration config, Messenger* messenger, std::shared_ptr<Detector> detector) : Module(detector), config_(std::move(config)), detector_(std::move(detector)), deposit_message_(nullptr) { messenger->bindSingle(this, &DetectorHistogrammerModule::deposit_message_); } DetectorHistogrammerModule::~DetectorHistogrammerModule() = default; // run the deposition void DetectorHistogrammerModule::run() { // check if we got any deposits if(deposit_message_ == nullptr) { LOG(WARNING) << "Detector " << detector_->getName() << " did not get any deposits"; } // get detector model auto model = std::dynamic_pointer_cast<PixelDetectorModel>(detector_->getModel()); if(model == nullptr) { // FIXME: exception can be more appropriate here LOG(CRITICAL) << "Detector " << detector_->getName() << " is not a PixelDetectorModel: ignored as other types are currently unsupported!"; return; } // create root file std::string file_name = config_.get<std::string>("file_prefix") + "_" + detector_->getName() + ".root"; auto file = new TFile(file_name.c_str(), "RECREATE"); // create histogram std::string plot_name = "plot_" + detector_->getName(); std::string plot_title = "Histogram for " + detector_->getName(); auto histogram = new TH2F(plot_name.c_str(), plot_title.c_str(), model->getNPixelsX(), -model->getHalfSensorSizeX(), model->getHalfSensorSizeX(), model->getNPixelsY(), -model->getHalfSensorSizeY(), model->getHalfSensorSizeY()); for(auto& deposit : deposit_message_->getData()) { auto vec = deposit.getPosition(); double energy = deposit.getEnergy(); histogram->Fill(vec.x(), vec.y(), energy); } histogram->Write(); file->Close(); } <commit_msg>return if no deposit is found in detector<commit_after>/** * @author Koen Wolters <koen.wolters@cern.ch> */ #include "DetectorHistogrammerTestModule.hpp" #include <memory> #include <string> #include <utility> #include <TApplication.h> #include <TFile.h> #include <TH2D.h> #include "core/geometry/PixelDetectorModel.hpp" #include "core/messenger/Messenger.hpp" #include "core/utils/log.h" using namespace allpix; const std::string DetectorHistogrammerModule::name = "detector_histogrammer_test"; DetectorHistogrammerModule::DetectorHistogrammerModule(Configuration config, Messenger* messenger, std::shared_ptr<Detector> detector) : Module(detector), config_(std::move(config)), detector_(std::move(detector)), deposit_message_(nullptr) { messenger->bindSingle(this, &DetectorHistogrammerModule::deposit_message_); } DetectorHistogrammerModule::~DetectorHistogrammerModule() = default; // run the deposition void DetectorHistogrammerModule::run() { // check if we got any deposits if(deposit_message_ == nullptr) { LOG(WARNING) << "Detector " << detector_->getName() << " did not get any deposits... skipping!"; return; } // get detector model auto model = std::dynamic_pointer_cast<PixelDetectorModel>(detector_->getModel()); if(model == nullptr) { // FIXME: exception can be more appropriate here LOG(CRITICAL) << "Detector " << detector_->getName() << " is not a PixelDetectorModel: ignored as other types are currently unsupported!"; return; } // create root file std::string file_name = config_.get<std::string>("file_prefix") + "_" + detector_->getName() + ".root"; auto file = new TFile(file_name.c_str(), "RECREATE"); // create histogram std::string plot_name = "plot_" + detector_->getName(); std::string plot_title = "Histogram for " + detector_->getName(); auto histogram = new TH2F(plot_name.c_str(), plot_title.c_str(), model->getNPixelsX(), -model->getHalfSensorSizeX(), model->getHalfSensorSizeX(), model->getNPixelsY(), -model->getHalfSensorSizeY(), model->getHalfSensorSizeY()); for(auto& deposit : deposit_message_->getData()) { auto vec = deposit.getPosition(); double energy = deposit.getEnergy(); histogram->Fill(vec.x(), vec.y(), energy); } histogram->Write(); file->Close(); } <|endoftext|>
<commit_before>/********************************************************************* *\ * INTEL CORPORATION PROPRIETARY INFORMATION * This software is supplied under the terms of a license agreement or * nondisclosure agreement with Intel Corporation and may not be copied * or disclosed except in accordance with the terms of that agreement. * Copyright (C) 2014 Intel Corporation. All Rights Reserved. ********************************************************************* */ #include "ospcommon.h" // embree: #include "embree2/rtcore.h" //embree/include/embree.h" // C-lib #include <time.h> #include <sys/time.h> #include <sys/times.h> namespace ospray { /*! logging level - '0' means 'no logging at all', increasing numbers mean increasing verbosity of log messages */ uint32 logLevel = 0; bool debugMode = false; /*! for debugging. compute a checksum for given area range... */ void *computeCheckSum(const void *ptr, size_t numBytes) { long *end = (long *)((char *)ptr + (numBytes - (numBytes%8))); long *mem = (long *)ptr; long sum = 0; long i = 0; int nextPing = 1; while (mem < end) { sum += (i+13) * *mem; ++i; ++mem; // if (i==nextPing) { // std::cout << "checksum after " << (i*8) << " bytes: " << (int*)sum << std::endl; // nextPing += nextPing; // } } return (void *)sum; } void doAssertion(const char *file, int line, const char *expr, const char *expl) { if (expl) fprintf(stderr,"%s:%u: Assertion failed: \"%s\":\nAdditional Info: %s\n", file, line, expr, expl); else fprintf(stderr,"%s:%u: Assertion failed: \"%s\".\n", file, line, expr); abort(); } double getSysTime() { struct timeval tp; gettimeofday(&tp,NULL); return double(tp.tv_sec) + double(tp.tv_usec)/1E6; } void init(int *_ac, const char ***_av) { int &ac = *_ac; char ** &av = *(char ***)_av; debugMode = false; for (int i=1;i<ac;) { std::string parm = av[i]; if (parm == "--osp:debug") { debugMode = true; removeArgs(ac,av,i,1); } else if (parm == "--osp:verbose") { logLevel = 1; removeArgs(ac,av,i,1); } else if (parm == "--osp:vv") { logLevel = 2; removeArgs(ac,av,i,1); } else if (parm == "--osp:loglevel") { logLevel = atoi(av[i+1]); removeArgs(ac,av,i,2); } else { ++i; } } } void removeArgs(int &ac, char **&av, int where, int howMany) { for (int i=where+howMany;i<ac;i++) av[i-howMany] = av[i]; ac -= howMany; } } <commit_msg>bugfix for wrongly initilized debugmode - same fix as in devel branch<commit_after>/********************************************************************* *\ * INTEL CORPORATION PROPRIETARY INFORMATION * This software is supplied under the terms of a license agreement or * nondisclosure agreement with Intel Corporation and may not be copied * or disclosed except in accordance with the terms of that agreement. * Copyright (C) 2014 Intel Corporation. All Rights Reserved. ********************************************************************* */ #include "ospcommon.h" // embree: #include "embree2/rtcore.h" //embree/include/embree.h" // C-lib #include <time.h> #include <sys/time.h> #include <sys/times.h> namespace ospray { /*! logging level - '0' means 'no logging at all', increasing numbers mean increasing verbosity of log messages */ uint32 logLevel = 0; bool debugMode = false; /*! for debugging. compute a checksum for given area range... */ void *computeCheckSum(const void *ptr, size_t numBytes) { long *end = (long *)((char *)ptr + (numBytes - (numBytes%8))); long *mem = (long *)ptr; long sum = 0; long i = 0; int nextPing = 1; while (mem < end) { sum += (i+13) * *mem; ++i; ++mem; // if (i==nextPing) { // std::cout << "checksum after " << (i*8) << " bytes: " << (int*)sum << std::endl; // nextPing += nextPing; // } } return (void *)sum; } void doAssertion(const char *file, int line, const char *expr, const char *expl) { if (expl) fprintf(stderr,"%s:%u: Assertion failed: \"%s\":\nAdditional Info: %s\n", file, line, expr, expl); else fprintf(stderr,"%s:%u: Assertion failed: \"%s\".\n", file, line, expr); abort(); } double getSysTime() { struct timeval tp; gettimeofday(&tp,NULL); return double(tp.tv_sec) + double(tp.tv_usec)/1E6; } void init(int *_ac, const char ***_av) { int &ac = *_ac; char ** &av = *(char ***)_av; for (int i=1;i<ac;) { std::string parm = av[i]; if (parm == "--osp:debug") { debugMode = true; removeArgs(ac,av,i,1); } else if (parm == "--osp:verbose") { logLevel = 1; removeArgs(ac,av,i,1); } else if (parm == "--osp:vv") { logLevel = 2; removeArgs(ac,av,i,1); } else if (parm == "--osp:loglevel") { logLevel = atoi(av[i+1]); removeArgs(ac,av,i,2); } else { ++i; } } } void removeArgs(int &ac, char **&av, int where, int howMany) { for (int i=where+howMany;i<ac;i++) av[i-howMany] = av[i]; ac -= howMany; } } <|endoftext|>
<commit_before>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/video/capture/screen/screen_capture_device.h" #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/sequenced_task_runner.h" #include "base/synchronization/lock.h" #include "media/video/capture/screen/mouse_cursor_shape.h" #include "media/video/capture/screen/screen_capture_data.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkDevice.h" namespace media { namespace { const int kBytesPerPixel = 4; } // namespace class ScreenCaptureDevice::Core : public base::RefCountedThreadSafe<Core>, public ScreenCapturer::Delegate { public: explicit Core(scoped_refptr<base::SequencedTaskRunner> task_runner); // Helper used in tests to supply a fake capturer. void SetScreenCapturerForTest(scoped_ptr<ScreenCapturer> capturer) { screen_capturer_ = capturer.Pass(); } // Implementation of VideoCaptureDevice methods. void Allocate(int width, int height, int frame_rate, EventHandler* event_handler); void Start(); void Stop(); void DeAllocate(); // ScreenCapturer::Delegate interface. Called by |screen_capturer_| on the // |task_runner_|. virtual void OnCaptureCompleted( scoped_refptr<ScreenCaptureData> capture_data) OVERRIDE; virtual void OnCursorShapeChanged( scoped_ptr<MouseCursorShape> cursor_shape) OVERRIDE; private: friend class base::RefCountedThreadSafe<Core>; virtual ~Core(); // Helper methods that run on the |task_runner_|. Posted from the // corresponding public methods. void DoAllocate(int frame_rate); void DoStart(); void DoStop(); void DoDeAllocate(); // Helper to schedule capture tasks. void ScheduleCaptureTimer(); // Method that is scheduled on |task_runner_| to be called on regular interval // to capture the screen. void OnCaptureTimer(); // Captures a single frame. void DoCapture(); // Task runner used for screen capturing operations. scoped_refptr<base::SequencedTaskRunner> task_runner_; // |event_handler_lock_| must be locked whenever |event_handler_| is used. // It's necessary because DeAllocate() needs to reset it on the calling thread // to ensure that the event handler is not called once DeAllocate() returns. base::Lock event_handler_lock_; EventHandler* event_handler_; // Frame rate specified to Allocate(). int frame_rate_; // The underlying ScreenCapturer instance used to capture frames. scoped_ptr<ScreenCapturer> screen_capturer_; // After Allocate() is called we need to call OnFrameInfo() method of the // |event_handler_| to specify the size of the frames this capturer will // produce. In order to get screen size from |screen_capturer_| we need to // capture at least one frame. Once screen size is known it's stored in // |frame_size_|. bool waiting_for_frame_size_; SkISize frame_size_; SkBitmap resized_bitmap_; // True between DoStart() and DoStop(). Can't just check |event_handler_| // because |event_handler_| is used on the caller thread. bool started_; // True when we have delayed OnCaptureTimer() task posted on // |task_runner_|. bool capture_task_posted_; // True when waiting for |screen_capturer_| to capture current frame. bool capture_in_progress_; DISALLOW_COPY_AND_ASSIGN(Core); }; ScreenCaptureDevice::Core::Core( scoped_refptr<base::SequencedTaskRunner> task_runner) : task_runner_(task_runner), event_handler_(NULL), waiting_for_frame_size_(false), started_(false), capture_task_posted_(false), capture_in_progress_(false) { } ScreenCaptureDevice::Core::~Core() { } void ScreenCaptureDevice::Core::Allocate(int width, int height, int frame_rate, EventHandler* event_handler) { DCHECK_GT(width, 0); DCHECK_GT(height, 0); DCHECK_GT(frame_rate, 0); { base::AutoLock auto_lock(event_handler_lock_); event_handler_ = event_handler; } task_runner_->PostTask( FROM_HERE, base::Bind(&Core::DoAllocate, this, frame_rate)); } void ScreenCaptureDevice::Core::Start() { task_runner_->PostTask( FROM_HERE, base::Bind(&Core::DoStart, this)); } void ScreenCaptureDevice::Core::Stop() { task_runner_->PostTask( FROM_HERE, base::Bind(&Core::DoStop, this)); } void ScreenCaptureDevice::Core::DeAllocate() { { base::AutoLock auto_lock(event_handler_lock_); event_handler_ = NULL; } task_runner_->PostTask(FROM_HERE, base::Bind(&Core::DoDeAllocate, this)); } void ScreenCaptureDevice::Core::OnCaptureCompleted( scoped_refptr<ScreenCaptureData> capture_data) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); DCHECK(capture_in_progress_); DCHECK(!capture_data->size().isEmpty()); capture_in_progress_ = false; if (waiting_for_frame_size_) { frame_size_ = capture_data->size(); waiting_for_frame_size_ = false; // Inform the EventHandler of the video frame dimensions and format. VideoCaptureCapability caps; caps.width = frame_size_.width(); caps.height = frame_size_.height(); caps.frame_rate = frame_rate_; caps.color = VideoCaptureCapability::kARGB; caps.expected_capture_delay = base::Time::kMillisecondsPerSecond / frame_rate_; caps.interlaced = false; base::AutoLock auto_lock(event_handler_lock_); if (event_handler_) event_handler_->OnFrameInfo(caps); } if (!started_) return; size_t buffer_size = frame_size_.width() * frame_size_.height() * ScreenCaptureData::kBytesPerPixel; if (capture_data->size() == frame_size_) { // If the captured frame matches the requested size, we don't need to // resize it. resized_bitmap_.reset(); base::AutoLock auto_lock(event_handler_lock_); if (event_handler_) { event_handler_->OnIncomingCapturedFrame( capture_data->data(), buffer_size, base::Time::Now(), 0, false, false); } return; } // In case screen size has changed we need to resize the image. Resized image // is stored to |resized_bitmap_|. Only regions of the screen that are // changing are copied. SkRegion dirty_region = capture_data->dirty_region(); if (resized_bitmap_.width() != frame_size_.width() || resized_bitmap_.height() != frame_size_.height()) { resized_bitmap_.setConfig(SkBitmap::kARGB_8888_Config, frame_size_.width(), frame_size_.height()); resized_bitmap_.setIsOpaque(true); resized_bitmap_.allocPixels(); dirty_region.setRect(SkIRect::MakeSize(frame_size_)); } float scale_x = static_cast<float>(frame_size_.width()) / capture_data->size().width(); float scale_y = static_cast<float>(frame_size_.height()) / capture_data->size().height(); float scale; float x, y; // Center the image in case aspect ratio is different. if (scale_x > scale_y) { scale = scale_y; x = (scale_x - scale_y) / scale * frame_size_.width() / 2.0; y = 0.f; } else { scale = scale_x; x = 0.f; y = (scale_y - scale_x) / scale * frame_size_.height() / 2.0; } // Create skia device and canvas that draw to |resized_bitmap_|. SkDevice device(resized_bitmap_); SkCanvas canvas(&device); canvas.scale(scale, scale); int source_stride = capture_data->stride(); for (SkRegion::Iterator i(dirty_region); !i.done(); i.next()) { SkBitmap source_bitmap; source_bitmap.setConfig(SkBitmap::kARGB_8888_Config, i.rect().width(), i.rect().height(), source_stride); source_bitmap.setIsOpaque(true); source_bitmap.setPixels( capture_data->data() + i.rect().top() * source_stride + i.rect().left() * ScreenCaptureData::kBytesPerPixel); canvas.drawBitmap(source_bitmap, i.rect().left() + x / scale, i.rect().top() + y / scale, NULL); } base::AutoLock auto_lock(event_handler_lock_); if (event_handler_) { event_handler_->OnIncomingCapturedFrame( reinterpret_cast<uint8*>(resized_bitmap_.getPixels()), buffer_size, base::Time::Now(), 0, false, false); } } void ScreenCaptureDevice::Core::OnCursorShapeChanged( scoped_ptr<MouseCursorShape> cursor_shape) { // TODO(sergeyu): Store mouse cursor shape and then render it to each captured // frame. crbug.com/173265 . DCHECK(task_runner_->RunsTasksOnCurrentThread()); } void ScreenCaptureDevice::Core::DoAllocate(int frame_rate) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); frame_rate_ = frame_rate; // Create and start frame capturer. if (!screen_capturer_) screen_capturer_ = ScreenCapturer::Create(); if (screen_capturer_) screen_capturer_->Start(this); // Capture first frame, so that we can call OnFrameInfo() callback. waiting_for_frame_size_ = true; DoCapture(); } void ScreenCaptureDevice::Core::DoStart() { DCHECK(task_runner_->RunsTasksOnCurrentThread()); started_ = true; if (!capture_task_posted_) { ScheduleCaptureTimer(); DoCapture(); } } void ScreenCaptureDevice::Core::DoStop() { DCHECK(task_runner_->RunsTasksOnCurrentThread()); started_ = false; resized_bitmap_.reset(); } void ScreenCaptureDevice::Core::DoDeAllocate() { DCHECK(task_runner_->RunsTasksOnCurrentThread()); DoStop(); if (screen_capturer_) { screen_capturer_->Stop(); screen_capturer_.reset(); } waiting_for_frame_size_ = false; } void ScreenCaptureDevice::Core::ScheduleCaptureTimer() { DCHECK(!capture_task_posted_); capture_task_posted_ = true; task_runner_->PostDelayedTask( FROM_HERE, base::Bind(&Core::OnCaptureTimer, this), base::TimeDelta::FromSeconds(1) / frame_rate_); } void ScreenCaptureDevice::Core::OnCaptureTimer() { DCHECK(capture_task_posted_); capture_task_posted_ = false; if (!started_) return; // Schedule a task for the next frame. ScheduleCaptureTimer(); DoCapture(); } void ScreenCaptureDevice::Core::DoCapture() { DCHECK(!capture_in_progress_); capture_in_progress_ = true; screen_capturer_->CaptureFrame(); // Assume that ScreenCapturer always calls OnCaptureCompleted() // callback before it returns. // // TODO(sergeyu): Fix ScreenCapturer to return video frame // synchronously instead of using Delegate interface. DCHECK(!capture_in_progress_); } ScreenCaptureDevice::ScreenCaptureDevice( scoped_refptr<base::SequencedTaskRunner> task_runner) : core_(new Core(task_runner)) { name_.device_name = "Screen"; } ScreenCaptureDevice::~ScreenCaptureDevice() { DeAllocate(); } void ScreenCaptureDevice::SetScreenCapturerForTest( scoped_ptr<ScreenCapturer> capturer) { core_->SetScreenCapturerForTest(capturer.Pass()); } void ScreenCaptureDevice::Allocate(int width, int height, int frame_rate, EventHandler* event_handler) { core_->Allocate(width, height, frame_rate, event_handler); } void ScreenCaptureDevice::Start() { core_->Start(); } void ScreenCaptureDevice::Stop() { core_->Stop(); } void ScreenCaptureDevice::DeAllocate() { core_->DeAllocate(); } const VideoCaptureDevice::Name& ScreenCaptureDevice::device_name() { return name_; } } // namespace media <commit_msg>Take advantage of XDAMAGE to support Screen Capture under ChromeOS.<commit_after>// Copyright (c) 2013 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "media/video/capture/screen/screen_capture_device.h" #include "base/bind.h" #include "base/location.h" #include "base/logging.h" #include "base/sequenced_task_runner.h" #include "base/synchronization/lock.h" #include "media/video/capture/screen/mouse_cursor_shape.h" #include "media/video/capture/screen/screen_capture_data.h" #include "third_party/skia/include/core/SkCanvas.h" #include "third_party/skia/include/core/SkDevice.h" namespace media { namespace { const int kBytesPerPixel = 4; } // namespace class ScreenCaptureDevice::Core : public base::RefCountedThreadSafe<Core>, public ScreenCapturer::Delegate { public: explicit Core(scoped_refptr<base::SequencedTaskRunner> task_runner); // Helper used in tests to supply a fake capturer. void SetScreenCapturerForTest(scoped_ptr<ScreenCapturer> capturer) { screen_capturer_ = capturer.Pass(); } // Implementation of VideoCaptureDevice methods. void Allocate(int width, int height, int frame_rate, EventHandler* event_handler); void Start(); void Stop(); void DeAllocate(); // ScreenCapturer::Delegate interface. Called by |screen_capturer_| on the // |task_runner_|. virtual void OnCaptureCompleted( scoped_refptr<ScreenCaptureData> capture_data) OVERRIDE; virtual void OnCursorShapeChanged( scoped_ptr<MouseCursorShape> cursor_shape) OVERRIDE; private: friend class base::RefCountedThreadSafe<Core>; virtual ~Core(); // Helper methods that run on the |task_runner_|. Posted from the // corresponding public methods. void DoAllocate(int frame_rate); void DoStart(); void DoStop(); void DoDeAllocate(); // Helper to schedule capture tasks. void ScheduleCaptureTimer(); // Method that is scheduled on |task_runner_| to be called on regular interval // to capture the screen. void OnCaptureTimer(); // Captures a single frame. void DoCapture(); // Task runner used for screen capturing operations. scoped_refptr<base::SequencedTaskRunner> task_runner_; // |event_handler_lock_| must be locked whenever |event_handler_| is used. // It's necessary because DeAllocate() needs to reset it on the calling thread // to ensure that the event handler is not called once DeAllocate() returns. base::Lock event_handler_lock_; EventHandler* event_handler_; // Frame rate specified to Allocate(). int frame_rate_; // The underlying ScreenCapturer instance used to capture frames. scoped_ptr<ScreenCapturer> screen_capturer_; // After Allocate() is called we need to call OnFrameInfo() method of the // |event_handler_| to specify the size of the frames this capturer will // produce. In order to get screen size from |screen_capturer_| we need to // capture at least one frame. Once screen size is known it's stored in // |frame_size_|. bool waiting_for_frame_size_; SkISize frame_size_; SkBitmap resized_bitmap_; // True between DoStart() and DoStop(). Can't just check |event_handler_| // because |event_handler_| is used on the caller thread. bool started_; // True when we have delayed OnCaptureTimer() task posted on // |task_runner_|. bool capture_task_posted_; // True when waiting for |screen_capturer_| to capture current frame. bool capture_in_progress_; DISALLOW_COPY_AND_ASSIGN(Core); }; ScreenCaptureDevice::Core::Core( scoped_refptr<base::SequencedTaskRunner> task_runner) : task_runner_(task_runner), event_handler_(NULL), waiting_for_frame_size_(false), started_(false), capture_task_posted_(false), capture_in_progress_(false) { } ScreenCaptureDevice::Core::~Core() { } void ScreenCaptureDevice::Core::Allocate(int width, int height, int frame_rate, EventHandler* event_handler) { DCHECK_GT(width, 0); DCHECK_GT(height, 0); DCHECK_GT(frame_rate, 0); { base::AutoLock auto_lock(event_handler_lock_); event_handler_ = event_handler; } task_runner_->PostTask( FROM_HERE, base::Bind(&Core::DoAllocate, this, frame_rate)); } void ScreenCaptureDevice::Core::Start() { task_runner_->PostTask( FROM_HERE, base::Bind(&Core::DoStart, this)); } void ScreenCaptureDevice::Core::Stop() { task_runner_->PostTask( FROM_HERE, base::Bind(&Core::DoStop, this)); } void ScreenCaptureDevice::Core::DeAllocate() { { base::AutoLock auto_lock(event_handler_lock_); event_handler_ = NULL; } task_runner_->PostTask(FROM_HERE, base::Bind(&Core::DoDeAllocate, this)); } void ScreenCaptureDevice::Core::OnCaptureCompleted( scoped_refptr<ScreenCaptureData> capture_data) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); DCHECK(capture_in_progress_); DCHECK(!capture_data->size().isEmpty()); capture_in_progress_ = false; if (waiting_for_frame_size_) { frame_size_ = capture_data->size(); waiting_for_frame_size_ = false; // Inform the EventHandler of the video frame dimensions and format. VideoCaptureCapability caps; caps.width = frame_size_.width(); caps.height = frame_size_.height(); caps.frame_rate = frame_rate_; caps.color = VideoCaptureCapability::kARGB; caps.expected_capture_delay = base::Time::kMillisecondsPerSecond / frame_rate_; caps.interlaced = false; base::AutoLock auto_lock(event_handler_lock_); if (event_handler_) event_handler_->OnFrameInfo(caps); } if (!started_) return; size_t buffer_size = frame_size_.width() * frame_size_.height() * ScreenCaptureData::kBytesPerPixel; if (capture_data->size() == frame_size_) { // If the captured frame matches the requested size, we don't need to // resize it. resized_bitmap_.reset(); base::AutoLock auto_lock(event_handler_lock_); if (event_handler_) { event_handler_->OnIncomingCapturedFrame( capture_data->data(), buffer_size, base::Time::Now(), 0, false, false); } return; } // In case screen size has changed we need to resize the image. Resized image // is stored to |resized_bitmap_|. Only regions of the screen that are // changing are copied. SkRegion dirty_region = capture_data->dirty_region(); if (resized_bitmap_.width() != frame_size_.width() || resized_bitmap_.height() != frame_size_.height()) { resized_bitmap_.setConfig(SkBitmap::kARGB_8888_Config, frame_size_.width(), frame_size_.height()); resized_bitmap_.setIsOpaque(true); resized_bitmap_.allocPixels(); dirty_region.setRect(SkIRect::MakeSize(frame_size_)); } float scale_x = static_cast<float>(frame_size_.width()) / capture_data->size().width(); float scale_y = static_cast<float>(frame_size_.height()) / capture_data->size().height(); float scale; float x, y; // Center the image in case aspect ratio is different. if (scale_x > scale_y) { scale = scale_y; x = (scale_x - scale_y) / scale * frame_size_.width() / 2.0; y = 0.f; } else { scale = scale_x; x = 0.f; y = (scale_y - scale_x) / scale * frame_size_.height() / 2.0; } // Create skia device and canvas that draw to |resized_bitmap_|. SkDevice device(resized_bitmap_); SkCanvas canvas(&device); canvas.scale(scale, scale); int source_stride = capture_data->stride(); for (SkRegion::Iterator i(dirty_region); !i.done(); i.next()) { SkBitmap source_bitmap; source_bitmap.setConfig(SkBitmap::kARGB_8888_Config, i.rect().width(), i.rect().height(), source_stride); source_bitmap.setIsOpaque(true); source_bitmap.setPixels( capture_data->data() + i.rect().top() * source_stride + i.rect().left() * ScreenCaptureData::kBytesPerPixel); canvas.drawBitmap(source_bitmap, i.rect().left() + x / scale, i.rect().top() + y / scale, NULL); } base::AutoLock auto_lock(event_handler_lock_); if (event_handler_) { event_handler_->OnIncomingCapturedFrame( reinterpret_cast<uint8*>(resized_bitmap_.getPixels()), buffer_size, base::Time::Now(), 0, false, false); } } void ScreenCaptureDevice::Core::OnCursorShapeChanged( scoped_ptr<MouseCursorShape> cursor_shape) { // TODO(sergeyu): Store mouse cursor shape and then render it to each captured // frame. crbug.com/173265 . DCHECK(task_runner_->RunsTasksOnCurrentThread()); } void ScreenCaptureDevice::Core::DoAllocate(int frame_rate) { DCHECK(task_runner_->RunsTasksOnCurrentThread()); frame_rate_ = frame_rate; // Create and start frame capturer. #if defined(OS_CHROMEOS) // ScreenCapturerX11 polls by default, due to poor driver support for DAMAGE. // ChromeOS' drivers [can be patched to] support DAMAGE properly, so use it. if (!screen_capturer_) screen_capturer_ = ScreenCapturer::CreateWithXDamage(true); #else if (!screen_capturer_) screen_capturer_ = ScreenCapturer::Create(); #endif if (screen_capturer_) screen_capturer_->Start(this); // Capture first frame, so that we can call OnFrameInfo() callback. waiting_for_frame_size_ = true; DoCapture(); } void ScreenCaptureDevice::Core::DoStart() { DCHECK(task_runner_->RunsTasksOnCurrentThread()); started_ = true; if (!capture_task_posted_) { ScheduleCaptureTimer(); DoCapture(); } } void ScreenCaptureDevice::Core::DoStop() { DCHECK(task_runner_->RunsTasksOnCurrentThread()); started_ = false; resized_bitmap_.reset(); } void ScreenCaptureDevice::Core::DoDeAllocate() { DCHECK(task_runner_->RunsTasksOnCurrentThread()); DoStop(); if (screen_capturer_) { screen_capturer_->Stop(); screen_capturer_.reset(); } waiting_for_frame_size_ = false; } void ScreenCaptureDevice::Core::ScheduleCaptureTimer() { DCHECK(!capture_task_posted_); capture_task_posted_ = true; task_runner_->PostDelayedTask( FROM_HERE, base::Bind(&Core::OnCaptureTimer, this), base::TimeDelta::FromSeconds(1) / frame_rate_); } void ScreenCaptureDevice::Core::OnCaptureTimer() { DCHECK(capture_task_posted_); capture_task_posted_ = false; if (!started_) return; // Schedule a task for the next frame. ScheduleCaptureTimer(); DoCapture(); } void ScreenCaptureDevice::Core::DoCapture() { DCHECK(!capture_in_progress_); capture_in_progress_ = true; screen_capturer_->CaptureFrame(); // Assume that ScreenCapturer always calls OnCaptureCompleted() // callback before it returns. // // TODO(sergeyu): Fix ScreenCapturer to return video frame // synchronously instead of using Delegate interface. DCHECK(!capture_in_progress_); } ScreenCaptureDevice::ScreenCaptureDevice( scoped_refptr<base::SequencedTaskRunner> task_runner) : core_(new Core(task_runner)) { name_.device_name = "Screen"; } ScreenCaptureDevice::~ScreenCaptureDevice() { DeAllocate(); } void ScreenCaptureDevice::SetScreenCapturerForTest( scoped_ptr<ScreenCapturer> capturer) { core_->SetScreenCapturerForTest(capturer.Pass()); } void ScreenCaptureDevice::Allocate(int width, int height, int frame_rate, EventHandler* event_handler) { core_->Allocate(width, height, frame_rate, event_handler); } void ScreenCaptureDevice::Start() { core_->Start(); } void ScreenCaptureDevice::Stop() { core_->Stop(); } void ScreenCaptureDevice::DeAllocate() { core_->DeAllocate(); } const VideoCaptureDevice::Name& ScreenCaptureDevice::device_name() { return name_; } } // namespace media <|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/menu_bar_helper.h" #include <algorithm> #include "app/gtk_signal_registrar.h" #include "base/logging.h" #include "chrome/browser/gtk/gtk_util.h" namespace { // Recursively find all the GtkMenus that are attached to menu item |child| // and add them to |data|, which is a vector of GtkWidgets. void PopulateSubmenus(GtkWidget* child, gpointer data) { std::vector<GtkWidget*>* submenus = static_cast<std::vector<GtkWidget*>*>(data); GtkWidget* submenu = gtk_menu_item_get_submenu(GTK_MENU_ITEM(child)); if (submenu) { submenus->push_back(submenu); gtk_container_foreach(GTK_CONTAINER(submenu), PopulateSubmenus, submenus); } } // Is the cursor over |menu| or one of its parent menus? bool MotionIsOverMenu(GtkWidget* menu, GdkEventMotion* motion) { if (motion->x >= 0 && motion->y >= 0 && motion->x < menu->allocation.width && motion->y < menu->allocation.height) { return true; } while (menu) { GtkWidget* menu_item = gtk_menu_get_attach_widget(GTK_MENU(menu)); if (!menu_item) return false; GtkWidget* parent = gtk_widget_get_parent(menu_item); if (gtk_util::WidgetContainsCursor(parent)) return true; menu = parent; } return false; } } // namespace MenuBarHelper::MenuBarHelper(Delegate* delegate) : button_showing_menu_(NULL), showing_menu_(NULL), delegate_(delegate) { DCHECK(delegate_); } MenuBarHelper::~MenuBarHelper() { } void MenuBarHelper::Add(GtkWidget* button) { buttons_.push_back(button); } void MenuBarHelper::Remove(GtkWidget* button) { std::vector<GtkWidget*>::iterator iter = find(buttons_.begin(), buttons_.end(), button); if (iter == buttons_.end()) { NOTREACHED(); return; } buttons_.erase(iter); } void MenuBarHelper::Clear() { buttons_.clear(); } void MenuBarHelper::MenuStartedShowing(GtkWidget* button, GtkWidget* menu) { DCHECK(GTK_IS_MENU(menu)); button_showing_menu_ = button; showing_menu_ = menu; signal_handlers_.reset(new GtkSignalRegistrar()); signal_handlers_->Connect(menu, "motion-notify-event", G_CALLBACK(OnMenuMotionNotifyThunk), this); signal_handlers_->Connect(menu, "hide", G_CALLBACK(OnMenuHiddenThunk), this); signal_handlers_->Connect(menu, "move-current", G_CALLBACK(OnMenuMoveCurrentThunk), this); gtk_container_foreach(GTK_CONTAINER(menu), PopulateSubmenus, &submenus_); for (size_t i = 0; i < submenus_.size(); ++i) { signal_handlers_->Connect(submenus_[i], "motion-notify-event", G_CALLBACK(OnMenuMotionNotifyThunk), this); } } gboolean MenuBarHelper::OnMenuMotionNotify(GtkWidget* menu, GdkEventMotion* motion) { // Don't do anything if pointer is in the menu. if (MotionIsOverMenu(menu, motion)) return FALSE; if (buttons_.empty()) return FALSE; gint x = 0; gint y = 0; GtkWidget* last_button = NULL; for (size_t i = 0; i < buttons_.size(); ++i) { GtkWidget* button = buttons_[i]; // Figure out coordinates relative to this button. Avoid using // gtk_widget_get_pointer() unnecessarily. if (i == 0) { // We have to make this call because the menu is a popup window, so it // doesn't share a toplevel with the buttons and we can't just use // gtk_widget_translate_coordinates(). gtk_widget_get_pointer(buttons_[0], &x, &y); } else { gint last_x = x; gint last_y = y; if (!gtk_widget_translate_coordinates( last_button, button, last_x, last_y, &x, &y)) { NOTREACHED(); return FALSE; } } last_button = button; if (x >= 0 && y >= 0 && x < button->allocation.width && y < button->allocation.height) { if (button != button_showing_menu_) delegate_->PopupForButton(button); return TRUE; } } return FALSE; } void MenuBarHelper::OnMenuHidden(GtkWidget* menu) { DCHECK_EQ(showing_menu_, menu); signal_handlers_.reset(); showing_menu_ = NULL; button_showing_menu_ = NULL; submenus_.clear(); } void MenuBarHelper::OnMenuMoveCurrent(GtkWidget* menu, GtkMenuDirectionType dir) { // The menu directions are triggered by the arrow keys as follows // // PARENT left // CHILD right // NEXT down // PREV up // // We only care about left and right. Note that for RTL, they are swapped. switch (dir) { case GTK_MENU_DIR_CHILD: { GtkWidget* active_item = GTK_MENU_SHELL(menu)->active_menu_item; // The move is going to open a submenu; don't override default behavior. if (active_item && gtk_menu_item_get_submenu(GTK_MENU_ITEM(active_item))) return; // Fall through. } case GTK_MENU_DIR_PARENT: { delegate_->PopupForButtonNextTo(button_showing_menu_, dir); break; } default: return; } // This signal doesn't have a return value; we have to manually stop its // propagation. g_signal_stop_emission_by_name(menu, "move-current"); } <commit_msg>GTK: minor MenuBarHelper fix.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/gtk/menu_bar_helper.h" #include <algorithm> #include "app/gtk_signal_registrar.h" #include "base/logging.h" #include "chrome/browser/gtk/gtk_util.h" namespace { // Recursively find all the GtkMenus that are attached to menu item |child| // and add them to |data|, which is a vector of GtkWidgets. void PopulateSubmenus(GtkWidget* child, gpointer data) { std::vector<GtkWidget*>* submenus = static_cast<std::vector<GtkWidget*>*>(data); GtkWidget* submenu = gtk_menu_item_get_submenu(GTK_MENU_ITEM(child)); if (submenu) { submenus->push_back(submenu); gtk_container_foreach(GTK_CONTAINER(submenu), PopulateSubmenus, submenus); } } // Is the cursor over |menu| or one of its parent menus? bool MotionIsOverMenu(GtkWidget* menu, GdkEventMotion* motion) { if (motion->x >= 0 && motion->y >= 0 && motion->x < menu->allocation.width && motion->y < menu->allocation.height) { return true; } while (menu) { GtkWidget* menu_item = gtk_menu_get_attach_widget(GTK_MENU(menu)); if (!menu_item) return false; GtkWidget* parent = gtk_widget_get_parent(menu_item); if (gtk_util::WidgetContainsCursor(parent)) return true; menu = parent; } return false; } } // namespace MenuBarHelper::MenuBarHelper(Delegate* delegate) : button_showing_menu_(NULL), showing_menu_(NULL), delegate_(delegate) { DCHECK(delegate_); } MenuBarHelper::~MenuBarHelper() { } void MenuBarHelper::Add(GtkWidget* button) { buttons_.push_back(button); } void MenuBarHelper::Remove(GtkWidget* button) { std::vector<GtkWidget*>::iterator iter = find(buttons_.begin(), buttons_.end(), button); if (iter == buttons_.end()) { NOTREACHED(); return; } buttons_.erase(iter); } void MenuBarHelper::Clear() { buttons_.clear(); } void MenuBarHelper::MenuStartedShowing(GtkWidget* button, GtkWidget* menu) { DCHECK(GTK_IS_MENU(menu)); button_showing_menu_ = button; showing_menu_ = menu; signal_handlers_.reset(new GtkSignalRegistrar()); signal_handlers_->Connect(menu, "motion-notify-event", G_CALLBACK(OnMenuMotionNotifyThunk), this); signal_handlers_->Connect(menu, "hide", G_CALLBACK(OnMenuHiddenThunk), this); signal_handlers_->Connect(menu, "move-current", G_CALLBACK(OnMenuMoveCurrentThunk), this); gtk_container_foreach(GTK_CONTAINER(menu), PopulateSubmenus, &submenus_); for (size_t i = 0; i < submenus_.size(); ++i) { signal_handlers_->Connect(submenus_[i], "motion-notify-event", G_CALLBACK(OnMenuMotionNotifyThunk), this); } } gboolean MenuBarHelper::OnMenuMotionNotify(GtkWidget* menu, GdkEventMotion* motion) { // Don't do anything if pointer is in the menu. if (MotionIsOverMenu(menu, motion)) return FALSE; if (buttons_.empty()) return FALSE; gint x = 0; gint y = 0; GtkWidget* last_button = NULL; for (size_t i = 0; i < buttons_.size(); ++i) { GtkWidget* button = buttons_[i]; // Figure out coordinates relative to this button. Avoid using // gtk_widget_get_pointer() unnecessarily. if (i == 0) { // We have to make this call because the menu is a popup window, so it // doesn't share a toplevel with the buttons and we can't just use // gtk_widget_translate_coordinates(). gtk_widget_get_pointer(buttons_[0], &x, &y); } else { gint last_x = x; gint last_y = y; if (!gtk_widget_translate_coordinates( last_button, button, last_x, last_y, &x, &y)) { // |button| may not be realized. continue; } } last_button = button; if (x >= 0 && y >= 0 && x < button->allocation.width && y < button->allocation.height) { if (button != button_showing_menu_) delegate_->PopupForButton(button); return TRUE; } } return FALSE; } void MenuBarHelper::OnMenuHidden(GtkWidget* menu) { DCHECK_EQ(showing_menu_, menu); signal_handlers_.reset(); showing_menu_ = NULL; button_showing_menu_ = NULL; submenus_.clear(); } void MenuBarHelper::OnMenuMoveCurrent(GtkWidget* menu, GtkMenuDirectionType dir) { // The menu directions are triggered by the arrow keys as follows // // PARENT left // CHILD right // NEXT down // PREV up // // We only care about left and right. Note that for RTL, they are swapped. switch (dir) { case GTK_MENU_DIR_CHILD: { GtkWidget* active_item = GTK_MENU_SHELL(menu)->active_menu_item; // The move is going to open a submenu; don't override default behavior. if (active_item && gtk_menu_item_get_submenu(GTK_MENU_ITEM(active_item))) return; // Fall through. } case GTK_MENU_DIR_PARENT: { delegate_->PopupForButtonNextTo(button_showing_menu_, dir); break; } default: return; } // This signal doesn't have a return value; we have to manually stop its // propagation. g_signal_stop_emission_by_name(menu, "move-current"); } <|endoftext|>
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/tabs/side_tab.h" #include "app/gfx/canvas.h" #include "app/resource_bundle.h" namespace { const int kVerticalTabHeight = 27; const int kTextPadding = 4; const int kFavIconHeight = 16; }; // static gfx::Font* SideTab::font_ = NULL; //////////////////////////////////////////////////////////////////////////////// // SideTab, public: SideTab::SideTab(SideTabModel* model) : model_(model) { InitClass(); } SideTab::~SideTab() { } //////////////////////////////////////////////////////////////////////////////// // SideTab, views::View overrides: void SideTab::Layout() { // TODO(beng): } void SideTab::Paint(gfx::Canvas* canvas) { canvas->FillRectInt(model_->IsSelected(this) ? SK_ColorBLUE : SK_ColorRED, 0, 0, width(), height()); gfx::Rect text_rect = GetLocalBounds(false); text_rect.Inset(kTextPadding, kTextPadding, kTextPadding, kTextPadding); canvas->DrawStringInt(model_->GetTitle(this), *font_, SK_ColorBLACK, text_rect.x(), text_rect.y(), text_rect.width(), text_rect.height()); } gfx::Size SideTab::GetPreferredSize() { const int kTabHeight = std::max(font_->height() + 2 * kTextPadding, kFavIconHeight + 2 * kTextPadding); return gfx::Size(0, kTabHeight); } //////////////////////////////////////////////////////////////////////////////// // SideTab, private: // static void SideTab::InitClass() { static bool initialized = false; if (!initialized) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); font_ = new gfx::Font(rb.GetFont(ResourceBundle::BaseFont)); initialized = true; } } <commit_msg>fix bustage<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/browser/views/tabs/side_tab.h" #include "app/gfx/canvas.h" #include "app/resource_bundle.h" namespace { const int kVerticalTabHeight = 27; const int kTextPadding = 4; const int kFavIconHeight = 16; }; // static gfx::Font* SideTab::font_ = NULL; //////////////////////////////////////////////////////////////////////////////// // SideTab, public: SideTab::SideTab(SideTabModel* model) : model_(model) { InitClass(); } SideTab::~SideTab() { } //////////////////////////////////////////////////////////////////////////////// // SideTab, views::View overrides: void SideTab::Layout() { // TODO(beng): } void SideTab::Paint(gfx::Canvas* canvas) { canvas->FillRectInt(model_->IsSelected(this) ? SK_ColorBLUE : SK_ColorRED, 0, 0, width(), height()); gfx::Rect text_rect = GetLocalBounds(false); text_rect.Inset(kTextPadding, kTextPadding, kTextPadding, kTextPadding); canvas->DrawStringInt(UTF16ToWideHack(model_->GetTitle(this)), *font_, SK_ColorBLACK, text_rect.x(), text_rect.y(), text_rect.width(), text_rect.height()); } gfx::Size SideTab::GetPreferredSize() { const int kTabHeight = std::max(font_->height() + 2 * kTextPadding, kFavIconHeight + 2 * kTextPadding); return gfx::Size(0, kTabHeight); } //////////////////////////////////////////////////////////////////////////////// // SideTab, private: // static void SideTab::InitClass() { static bool initialized = false; if (!initialized) { ResourceBundle& rb = ResourceBundle::GetSharedInstance(); font_ = new gfx::Font(rb.GetFont(ResourceBundle::BaseFont)); initialized = true; } } <|endoftext|>
<commit_before>#include "unzipper.h" #include "defs.h" #include "tools.h" #include <functional> #include <exception> #include <fstream> #include <stdexcept> namespace zipper { struct Unzipper::Impl { Unzipper& m_outer; zipFile m_zf; ourmemory_t m_zipmem; zlib_filefunc_def m_filefunc; private: bool initMemory(zlib_filefunc_def& filefunc) { m_zf = unzOpen2("__notused__", &filefunc); return m_zf != NULL; } bool locateEntry(const std::string& name) { return UNZ_OK == unzLocateFile(m_zf, name.c_str(), NULL); } ZipEntry currentEntryInfo() { unz_file_info64 file_info = { 0 }; char filename_inzip[256] = { 0 }; int err = unzGetCurrentFileInfo64(m_zf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); if (UNZ_OK != err) throw EXCEPTION_CLASS("Error, couln't get the current entry info"); return ZipEntry(std::string(filename_inzip), file_info.compressed_size, file_info.uncompressed_size, file_info.tmu_date.tm_year, file_info.tmu_date.tm_mon, file_info.tmu_date.tm_mday, file_info.tmu_date.tm_hour, file_info.tmu_date.tm_min, file_info.tmu_date.tm_sec, file_info.dosDate); } #if 0 // lambda as a parameter https://en.wikipedia.org/wiki/C%2B%2B11#Polymorphic_wrappers_for_function_objects void iterEntries(std::function<void(ZipEntry&)> callback) { int err = unzGoToFirstFile(m_zf); if (UNZ_OK == err) { do { ZipEntry entryinfo = currentEntryInfo(); if (entryinfo.valid()) { callback(entryinfo); err = unzGoToNextFile(m_zf); } else err = UNZ_ERRNO; } while (UNZ_OK == err); if (UNZ_END_OF_LIST_OF_FILE != err && UNZ_OK != err) return; } } #endif void getEntries(std::vector<ZipEntry>& entries) { int err = unzGoToFirstFile(m_zf); if (UNZ_OK == err) { do { ZipEntry entryinfo = currentEntryInfo(); if (entryinfo.valid()) { entries.push_back(entryinfo); err = unzGoToNextFile(m_zf); } else err = UNZ_ERRNO; } while (UNZ_OK == err); if (UNZ_END_OF_LIST_OF_FILE != err && UNZ_OK != err) return; } } public: #if 0 bool extractCurrentEntry(ZipEntry& entryinfo, int (extractStrategy)(ZipEntry&) ) { int err = UNZ_OK; if (!entryinfo.valid()) return false; err = extractStrategy(entryinfo); if (UNZ_OK == err) { err = unzCloseCurrentFile(m_zf); if (UNZ_OK != err) throw EXCEPTION_CLASS(("Error " + std::to_string(err) + " closing internal file '" + entryinfo.name + "' in zip").c_str()); } return UNZ_OK == err; } #endif bool extractCurrentEntryToFile(ZipEntry& entryinfo, const std::string& fileName) { int err = UNZ_OK; if (!entryinfo.valid()) return false; err = extractToFile(fileName, entryinfo); if (UNZ_OK == err) { err = unzCloseCurrentFile(m_zf); if (UNZ_OK != err) { std::stringstream str; str << "Error " << err << " openinginternal file '" << entryinfo.name << "' in zip"; throw EXCEPTION_CLASS(str.str().c_str()); } } return UNZ_OK == err; } bool extractCurrentEntryToStream(ZipEntry& entryinfo, std::ostream& stream) { int err = UNZ_OK; if (!entryinfo.valid()) return false; err = extractToStream(stream, entryinfo); if (UNZ_OK == err) { err = unzCloseCurrentFile(m_zf); if (UNZ_OK != err) { std::stringstream str; str << "Error " << err << " opening internal file '" << entryinfo.name << "' in zip"; throw EXCEPTION_CLASS(str.str().c_str()); } } return UNZ_OK == err; } bool extractCurrentEntryToMemory(ZipEntry& entryinfo, std::vector<unsigned char>& outvec) { int err = UNZ_OK; if (!entryinfo.valid()) return false; err = extractToMemory(outvec, entryinfo); if (UNZ_OK == err) { err = unzCloseCurrentFile(m_zf); if (UNZ_OK != err) { std::stringstream str; str << "Error " << err << " opening internal file '" << entryinfo.name << "' in zip"; throw EXCEPTION_CLASS(str.str().c_str()); } } return UNZ_OK == err; } int extractToFile(const std::string& filename, ZipEntry& info) { int err = UNZ_ERRNO; /* If zip entry is a directory then create it on disk */ makedir(parentDirectory(filename)); /* Create the file on disk so we can unzip to it */ std::ofstream output_file(filename.c_str(), std::ofstream::binary); if (output_file.good()) { if (extractToStream(output_file, info)) err = UNZ_OK; output_file.close(); /* Set the time of the file that has been unzipped */ tm_unz timeaux; memcpy(&timeaux, &info.unixdate, sizeof(timeaux)); changeFileDate(filename, info.dosdate, timeaux); } else output_file.close(); return err; } int extractToStream(std::ostream& stream, ZipEntry& info) { size_t err = UNZ_ERRNO; err = unzOpenCurrentFilePassword(m_zf, m_outer.m_password.c_str()); if (UNZ_OK != err) { std::stringstream str; str << "Error " << err << " opening internal file '" << info.name << "' in zip"; throw EXCEPTION_CLASS(str.str().c_str()); } std::vector<char> buffer; buffer.resize(WRITEBUFFERSIZE); do { err = unzReadCurrentFile(m_zf, buffer.data(), (unsigned int)buffer.size()); if (err < 0 || err == 0) break; stream.write(buffer.data(), err); if (!stream.good()) { err = UNZ_ERRNO; break; } } while (err > 0); stream.flush(); return (int)err; } int extractToMemory(std::vector<unsigned char>& outvec, ZipEntry& info) { size_t err = UNZ_ERRNO; err = unzOpenCurrentFilePassword(m_zf, m_outer.m_password.c_str()); if (UNZ_OK != err) { std::stringstream str; str << "Error " << err << " opening internal file '" << info.name << "' in zip"; throw EXCEPTION_CLASS(str.str().c_str()); } std::vector<unsigned char> buffer; buffer.resize(WRITEBUFFERSIZE); outvec.reserve((size_t)info.uncompressedSize); do { err = unzReadCurrentFile(m_zf, buffer.data(), (unsigned int)buffer.size()); if (err < 0 || err == 0) break; outvec.insert(outvec.end(), buffer.data(), buffer.data() + err); } while (err > 0); return (int)err; } public: Impl(Unzipper& outer) : m_outer(outer), m_zipmem(), m_filefunc() { m_zf = NULL; } ~Impl() { } void close() { if (m_zf) unzClose(m_zf); } bool initFile(const std::string& filename) { #ifdef USEWIN32IOAPI zlib_filefunc64_def ffunc; fill_win32_filefunc64A(&ffunc); m_zf = unzOpen2_64(filename.c_str(), &ffunc); #else m_zf = unzOpen64(filename.c_str()); #endif return m_zf != NULL; } bool initWithStream(std::istream& stream) { stream.seekg(0, std::ios::end); size_t size = (size_t)stream.tellg(); stream.seekg(0); if (size > 0) { m_zipmem.base = new char[(size_t)size]; stream.read(m_zipmem.base, size); } fill_memory_filefunc(&m_filefunc, &m_zipmem); return initMemory(m_filefunc); } bool initWithVector(std::vector<unsigned char>& buffer) { if (!buffer.empty()) { m_zipmem.base = (char*)buffer.data(); m_zipmem.size = (uLong)buffer.size(); } fill_memory_filefunc(&m_filefunc, &m_zipmem); return initMemory(m_filefunc); } std::vector<ZipEntry> entries() { std::vector<ZipEntry> entrylist; getEntries(entrylist); return entrylist; } bool extractAll(const std::string& destination, const std::map<std::string, std::string>& alternativeNames) { std::vector<ZipEntry> entries; getEntries(entries); std::vector<ZipEntry>::iterator it = entries.begin(); for (; it != entries.end(); ++it) { std::string alternativeName = destination.empty() ? "" : destination + "/"; if (alternativeNames.find(it->name) != alternativeNames.end()) alternativeName += alternativeNames.at(it->name); else alternativeName += it->name; this->extractCurrentEntryToFile(*it, alternativeName); }; return true; } bool extractEntry(const std::string& name, const std::string& destination) { std::string outputFile = destination.empty() ? name : destination + "\\" + name; if (locateEntry(name)) { ZipEntry entry = currentEntryInfo(); return extractCurrentEntryToFile(entry, outputFile); } else { return false; } } bool extractEntryToStream(const std::string& name, std::ostream& stream) { if (locateEntry(name)) { ZipEntry entry = currentEntryInfo(); return extractCurrentEntryToStream(entry, stream); } else { return false; } } bool extractEntryToMemory(const std::string& name, std::vector<unsigned char>& vec) { if (locateEntry(name)) { ZipEntry entry = currentEntryInfo(); return extractCurrentEntryToMemory(entry, vec); } else { return false; } } }; Unzipper::Unzipper(std::istream& zippedBuffer) : m_ibuffer(zippedBuffer) , m_vecbuffer(*(new std::vector<unsigned char>())) //not used but using local variable throws exception , m_usingMemoryVector(false) , m_usingStream(true) , m_impl(new Impl(*this)) { if (!m_impl->initWithStream(m_ibuffer)) throw EXCEPTION_CLASS("Error loading zip in memory!"); m_open = true; } Unzipper::Unzipper(std::vector<unsigned char>& zippedBuffer) : m_ibuffer(*(new std::stringstream())) //not used but using local variable throws exception , m_vecbuffer(zippedBuffer) , m_usingMemoryVector(true) , m_usingStream(false) , m_impl(new Impl(*this)) { if (!m_impl->initWithVector(m_vecbuffer)) throw EXCEPTION_CLASS("Error loading zip in memory!"); m_open = true; } Unzipper::Unzipper(const std::string& zipname) : m_ibuffer(*(new std::stringstream())) //not used but using local variable throws exception , m_vecbuffer(*(new std::vector<unsigned char>())) //not used but using local variable throws exception , m_zipname(zipname) , m_usingMemoryVector(false) , m_usingStream(false) , m_impl(new Impl(*this)) { if (!m_impl->initFile(zipname)) throw EXCEPTION_CLASS("Error loading zip file!"); m_open = true; } Unzipper::Unzipper(const std::string& zipname, const std::string& password) : m_ibuffer(*(new std::stringstream())) //not used but using local variable throws exception , m_vecbuffer(*(new std::vector<unsigned char>())) //not used but using local variable throws exception , m_zipname(zipname) , m_password(password) , m_usingMemoryVector(false) , m_usingStream(false) , m_impl(new Impl(*this)) { if (!m_impl->initFile(zipname)) throw EXCEPTION_CLASS("Error loading zip file!"); m_open = true; } Unzipper::~Unzipper(void) { close(); } std::vector<ZipEntry> Unzipper::entries() { return m_impl->entries(); } bool Unzipper::extractEntry(const std::string& name, const std::string& destination) { return m_impl->extractEntry(name, destination); } bool Unzipper::extractEntryToStream(const std::string& name, std::ostream& stream) { return m_impl->extractEntryToStream(name, stream); } bool Unzipper::extractEntryToMemory(const std::string& name, std::vector<unsigned char>& vec) { return m_impl->extractEntryToMemory(name, vec); } bool Unzipper::extract(const std::string& destination, const std::map<std::string, std::string>& alternativeNames) { return m_impl->extractAll(destination, alternativeNames); } bool Unzipper::extract(const std::string& destination) { return m_impl->extractAll(destination, std::map<std::string, std::string>()); } void Unzipper::close() { if (m_open) { m_impl->close(); m_open = false; } } } <commit_msg>- need to locate the individual entries when extracting all<commit_after>#include "unzipper.h" #include "defs.h" #include "tools.h" #include <functional> #include <exception> #include <fstream> #include <stdexcept> namespace zipper { struct Unzipper::Impl { Unzipper& m_outer; zipFile m_zf; ourmemory_t m_zipmem; zlib_filefunc_def m_filefunc; private: bool initMemory(zlib_filefunc_def& filefunc) { m_zf = unzOpen2("__notused__", &filefunc); return m_zf != NULL; } bool locateEntry(const std::string& name) { return UNZ_OK == unzLocateFile(m_zf, name.c_str(), NULL); } ZipEntry currentEntryInfo() { unz_file_info64 file_info = { 0 }; char filename_inzip[256] = { 0 }; int err = unzGetCurrentFileInfo64(m_zf, &file_info, filename_inzip, sizeof(filename_inzip), NULL, 0, NULL, 0); if (UNZ_OK != err) throw EXCEPTION_CLASS("Error, couln't get the current entry info"); return ZipEntry(std::string(filename_inzip), file_info.compressed_size, file_info.uncompressed_size, file_info.tmu_date.tm_year, file_info.tmu_date.tm_mon, file_info.tmu_date.tm_mday, file_info.tmu_date.tm_hour, file_info.tmu_date.tm_min, file_info.tmu_date.tm_sec, file_info.dosDate); } #if 0 // lambda as a parameter https://en.wikipedia.org/wiki/C%2B%2B11#Polymorphic_wrappers_for_function_objects void iterEntries(std::function<void(ZipEntry&)> callback) { int err = unzGoToFirstFile(m_zf); if (UNZ_OK == err) { do { ZipEntry entryinfo = currentEntryInfo(); if (entryinfo.valid()) { callback(entryinfo); err = unzGoToNextFile(m_zf); } else err = UNZ_ERRNO; } while (UNZ_OK == err); if (UNZ_END_OF_LIST_OF_FILE != err && UNZ_OK != err) return; } } #endif void getEntries(std::vector<ZipEntry>& entries) { int err = unzGoToFirstFile(m_zf); if (UNZ_OK == err) { do { ZipEntry entryinfo = currentEntryInfo(); if (entryinfo.valid()) { entries.push_back(entryinfo); err = unzGoToNextFile(m_zf); } else err = UNZ_ERRNO; } while (UNZ_OK == err); if (UNZ_END_OF_LIST_OF_FILE != err && UNZ_OK != err) return; } } public: #if 0 bool extractCurrentEntry(ZipEntry& entryinfo, int (extractStrategy)(ZipEntry&) ) { int err = UNZ_OK; if (!entryinfo.valid()) return false; err = extractStrategy(entryinfo); if (UNZ_OK == err) { err = unzCloseCurrentFile(m_zf); if (UNZ_OK != err) throw EXCEPTION_CLASS(("Error " + std::to_string(err) + " closing internal file '" + entryinfo.name + "' in zip").c_str()); } return UNZ_OK == err; } #endif bool extractCurrentEntryToFile(ZipEntry& entryinfo, const std::string& fileName) { int err = UNZ_OK; if (!entryinfo.valid()) return false; err = extractToFile(fileName, entryinfo); if (UNZ_OK == err) { err = unzCloseCurrentFile(m_zf); if (UNZ_OK != err) { std::stringstream str; str << "Error " << err << " openinginternal file '" << entryinfo.name << "' in zip"; throw EXCEPTION_CLASS(str.str().c_str()); } } return UNZ_OK == err; } bool extractCurrentEntryToStream(ZipEntry& entryinfo, std::ostream& stream) { int err = UNZ_OK; if (!entryinfo.valid()) return false; err = extractToStream(stream, entryinfo); if (UNZ_OK == err) { err = unzCloseCurrentFile(m_zf); if (UNZ_OK != err) { std::stringstream str; str << "Error " << err << " opening internal file '" << entryinfo.name << "' in zip"; throw EXCEPTION_CLASS(str.str().c_str()); } } return UNZ_OK == err; } bool extractCurrentEntryToMemory(ZipEntry& entryinfo, std::vector<unsigned char>& outvec) { int err = UNZ_OK; if (!entryinfo.valid()) return false; err = extractToMemory(outvec, entryinfo); if (UNZ_OK == err) { err = unzCloseCurrentFile(m_zf); if (UNZ_OK != err) { std::stringstream str; str << "Error " << err << " opening internal file '" << entryinfo.name << "' in zip"; throw EXCEPTION_CLASS(str.str().c_str()); } } return UNZ_OK == err; } int extractToFile(const std::string& filename, ZipEntry& info) { int err = UNZ_ERRNO; /* If zip entry is a directory then create it on disk */ makedir(parentDirectory(filename)); /* Create the file on disk so we can unzip to it */ std::ofstream output_file(filename.c_str(), std::ofstream::binary); if (output_file.good()) { if (extractToStream(output_file, info)) err = UNZ_OK; output_file.close(); /* Set the time of the file that has been unzipped */ tm_unz timeaux; memcpy(&timeaux, &info.unixdate, sizeof(timeaux)); changeFileDate(filename, info.dosdate, timeaux); } else output_file.close(); return err; } int extractToStream(std::ostream& stream, ZipEntry& info) { size_t err = UNZ_ERRNO; err = unzOpenCurrentFilePassword(m_zf, m_outer.m_password.c_str()); if (UNZ_OK != err) { std::stringstream str; str << "Error " << err << " opening internal file '" << info.name << "' in zip"; throw EXCEPTION_CLASS(str.str().c_str()); } std::vector<char> buffer; buffer.resize(WRITEBUFFERSIZE); do { err = unzReadCurrentFile(m_zf, buffer.data(), (unsigned int)buffer.size()); if (err < 0 || err == 0) break; stream.write(buffer.data(), err); if (!stream.good()) { err = UNZ_ERRNO; break; } } while (err > 0); stream.flush(); return (int)err; } int extractToMemory(std::vector<unsigned char>& outvec, ZipEntry& info) { size_t err = UNZ_ERRNO; err = unzOpenCurrentFilePassword(m_zf, m_outer.m_password.c_str()); if (UNZ_OK != err) { std::stringstream str; str << "Error " << err << " opening internal file '" << info.name << "' in zip"; throw EXCEPTION_CLASS(str.str().c_str()); } std::vector<unsigned char> buffer; buffer.resize(WRITEBUFFERSIZE); outvec.reserve((size_t)info.uncompressedSize); do { err = unzReadCurrentFile(m_zf, buffer.data(), (unsigned int)buffer.size()); if (err < 0 || err == 0) break; outvec.insert(outvec.end(), buffer.data(), buffer.data() + err); } while (err > 0); return (int)err; } public: Impl(Unzipper& outer) : m_outer(outer), m_zipmem(), m_filefunc() { m_zf = NULL; } ~Impl() { } void close() { if (m_zf) unzClose(m_zf); } bool initFile(const std::string& filename) { #ifdef USEWIN32IOAPI zlib_filefunc64_def ffunc; fill_win32_filefunc64A(&ffunc); m_zf = unzOpen2_64(filename.c_str(), &ffunc); #else m_zf = unzOpen64(filename.c_str()); #endif return m_zf != NULL; } bool initWithStream(std::istream& stream) { stream.seekg(0, std::ios::end); size_t size = (size_t)stream.tellg(); stream.seekg(0); if (size > 0) { m_zipmem.base = new char[(size_t)size]; stream.read(m_zipmem.base, size); } fill_memory_filefunc(&m_filefunc, &m_zipmem); return initMemory(m_filefunc); } bool initWithVector(std::vector<unsigned char>& buffer) { if (!buffer.empty()) { m_zipmem.base = (char*)buffer.data(); m_zipmem.size = (uLong)buffer.size(); } fill_memory_filefunc(&m_filefunc, &m_zipmem); return initMemory(m_filefunc); } std::vector<ZipEntry> entries() { std::vector<ZipEntry> entrylist; getEntries(entrylist); return entrylist; } bool extractAll(const std::string& destination, const std::map<std::string, std::string>& alternativeNames) { std::vector<ZipEntry> entries; getEntries(entries); std::vector<ZipEntry>::iterator it = entries.begin(); for (; it != entries.end(); ++it) { if (!locateEntry(it->name)) continue; std::string alternativeName = destination.empty() ? "" : destination + "/"; if (alternativeNames.find(it->name) != alternativeNames.end()) alternativeName += alternativeNames.at(it->name); else alternativeName += it->name; this->extractCurrentEntryToFile(*it, alternativeName); }; return true; } bool extractEntry(const std::string& name, const std::string& destination) { std::string outputFile = destination.empty() ? name : destination + "\\" + name; if (locateEntry(name)) { ZipEntry entry = currentEntryInfo(); return extractCurrentEntryToFile(entry, outputFile); } else { return false; } } bool extractEntryToStream(const std::string& name, std::ostream& stream) { if (locateEntry(name)) { ZipEntry entry = currentEntryInfo(); return extractCurrentEntryToStream(entry, stream); } else { return false; } } bool extractEntryToMemory(const std::string& name, std::vector<unsigned char>& vec) { if (locateEntry(name)) { ZipEntry entry = currentEntryInfo(); return extractCurrentEntryToMemory(entry, vec); } else { return false; } } }; Unzipper::Unzipper(std::istream& zippedBuffer) : m_ibuffer(zippedBuffer) , m_vecbuffer(*(new std::vector<unsigned char>())) //not used but using local variable throws exception , m_usingMemoryVector(false) , m_usingStream(true) , m_impl(new Impl(*this)) { if (!m_impl->initWithStream(m_ibuffer)) throw EXCEPTION_CLASS("Error loading zip in memory!"); m_open = true; } Unzipper::Unzipper(std::vector<unsigned char>& zippedBuffer) : m_ibuffer(*(new std::stringstream())) //not used but using local variable throws exception , m_vecbuffer(zippedBuffer) , m_usingMemoryVector(true) , m_usingStream(false) , m_impl(new Impl(*this)) { if (!m_impl->initWithVector(m_vecbuffer)) throw EXCEPTION_CLASS("Error loading zip in memory!"); m_open = true; } Unzipper::Unzipper(const std::string& zipname) : m_ibuffer(*(new std::stringstream())) //not used but using local variable throws exception , m_vecbuffer(*(new std::vector<unsigned char>())) //not used but using local variable throws exception , m_zipname(zipname) , m_usingMemoryVector(false) , m_usingStream(false) , m_impl(new Impl(*this)) { if (!m_impl->initFile(zipname)) throw EXCEPTION_CLASS("Error loading zip file!"); m_open = true; } Unzipper::Unzipper(const std::string& zipname, const std::string& password) : m_ibuffer(*(new std::stringstream())) //not used but using local variable throws exception , m_vecbuffer(*(new std::vector<unsigned char>())) //not used but using local variable throws exception , m_zipname(zipname) , m_password(password) , m_usingMemoryVector(false) , m_usingStream(false) , m_impl(new Impl(*this)) { if (!m_impl->initFile(zipname)) throw EXCEPTION_CLASS("Error loading zip file!"); m_open = true; } Unzipper::~Unzipper(void) { close(); } std::vector<ZipEntry> Unzipper::entries() { return m_impl->entries(); } bool Unzipper::extractEntry(const std::string& name, const std::string& destination) { return m_impl->extractEntry(name, destination); } bool Unzipper::extractEntryToStream(const std::string& name, std::ostream& stream) { return m_impl->extractEntryToStream(name, stream); } bool Unzipper::extractEntryToMemory(const std::string& name, std::vector<unsigned char>& vec) { return m_impl->extractEntryToMemory(name, vec); } bool Unzipper::extract(const std::string& destination, const std::map<std::string, std::string>& alternativeNames) { return m_impl->extractAll(destination, alternativeNames); } bool Unzipper::extract(const std::string& destination) { return m_impl->extractAll(destination, std::map<std::string, std::string>()); } void Unzipper::close() { if (m_open) { m_impl->close(); m_open = false; } } } <|endoftext|>
<commit_before>#define _USE_MATH_DEFINES #include <uWS/uWS.h> #include <iostream> #include "json.hpp" #include "PID.h" #include <math.h> using namespace std; // for convenience using json = nlohmann::json; // For converting back and forth between radians and degrees. constexpr double pi() { return M_PI; } double deg2rad(double x) { return x * pi() / 180; } double rad2deg(double x) { return x * 180 / pi(); } // Checks if the SocketIO event has JSON data. // If there is data the JSON object in string format will be returned, // else the empty string "" will be returned. std::stringstream hasData(std::string s) { auto found_null = s.find("null"); auto b1 = s.find_first_of("["); auto b2 = s.find_last_of("]"); if (found_null != std::string::npos) { return std::stringstream(); } else if (b1 != std::string::npos && b2 != std::string::npos) { std::stringstream tmp = std::stringstream(); tmp.str(s.substr(b1, b2 - b1 + 1)); return tmp; } return std::stringstream(); } int main() { uWS::Hub h; PID pid; // TODO: Initialize the pid variable. h.onMessage([&pid](uWS::WebSocket<uWS::SERVER> *ws, char *data, size_t length, uWS::OpCode opCode) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message // The 2 signifies a websocket event if (length && length > 2 && data[0] == '4' && data[1] == '2') { auto s = hasData(std::string(data)); if (s.str() != "") { auto j = json::parse(s); std::string event = j[0].get<std::string>(); if (event == "telemetry") { // j[1] is the data JSON object double cte = std::stod(j[1]["cte"].get<std::string>()); double speed = std::stod(j[1]["speed"].get<std::string>()); double angle = std::stod(j[1]["steering_angle"].get<std::string>()); /* * TODO: Calcuate steering value here, remember the steering value is * [-1, 1]. * NOTE: Feel free to play around with the throttle and speed. Maybe use * another PID controller to control the speed! */ /***************************************************************************** * Setup ****************************************************************************/ // TODO REVIEW THIS NONE RIGHT YET double steer_value = 0 ; double err = 0 ; double prev_cte = 0 ; double int_cte = 0 ; double diff_cte = 0 ; /***************************************************************************** * Twiddle ****************************************************************************/ vector<double> parameters; parameters = { 5.0, 5.0, 0.1 } ; vector<double> tune_parameters; tune_parameters = { 1.0, 1.0, 1.0 }; // double sum_tune_parameters = tune_parameters.sum() ; double best_err = 99999999.0; int counter = 0 ; cout << "Iteration" << counter << "\t best error" << best_err << "\t parameters" << parameters[0] << parameters[1] << parameters[2] << endl ; for (int i = 0; i < 3; i++) { parameters[i] += tune_parameters[i]; double current_error = 1; // TODO set current error UpdateError(cte)? // print(sum_parameters) if (current_error < best_err) { //last update worked, keep going tune_parameters[i] *= 1.1; best_err = current_error; // exit, since increase worked, -> loop } else { parameters[i] -= 2 * tune_parameters[i]; current_error = 1; // TODO set current error // check if decrease worked, if not, do a "reset" on the parameters if (current_error < best_err) { best_err = current_error; tune_parameters[i] *= 1.1; } else { parameters[i] += tune_parameters[i]; tune_parameters[i] *= .95; } } } /***************************************************************************** * Proportional integral derivative controller ****************************************************************************/ diff_cte = cte - prev_cte ; int_cte += cte ; steer_value = -parameters[0] * cte - parameters[1] * diff_cte - parameters[2] * int_cte ; prev_cte = cte ; // update CTE for next loop counter += 1 ; // DEBUG std::cout << "CTE: " << cte << " Steering Value: " << steer_value << std::endl; json msgJson; msgJson["steering_angle"] = steer_value; msgJson["throttle"] = 0.3; auto msg = "42[\"steer\"," + msgJson.dump() + "]"; std::cout << msg << std::endl; (*ws).send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } else { // Manual driving std::string msg = "42[\"manual\",{}]"; (*ws).send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } }); h.onConnection([&h](uWS::WebSocket<uWS::SERVER> *ws, uWS::HttpRequest req) { std::cout << "Connected!!!" << std::endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> *ws, int code, char *message, size_t length) { (*ws).close(); std::cout << "Disconnected" << std::endl; }); int port = 4567; if (h.listen("0.0.0.0", port)) { std::cout << "Listening to port " << port << std::endl; } else { std::cerr << "Failed to listen to port" << std::endl; return -1; } h.run(); }<commit_msg>changes per Ralph68 thank you for your help!<commit_after>#define _USE_MATH_DEFINES #include "uWS/uWS.h" #include <iostream> #include "json.hpp" #include "PID.h" #include <math.h> using namespace std; // for convenience using json = nlohmann::json; // For converting back and forth between radians and degrees. constexpr double pi() { return M_PI; } double deg2rad(double x) { return x * pi() / 180; } double rad2deg(double x) { return x * 180 / pi(); } // Checks if the SocketIO event has JSON data. // If there is data the JSON object in string format will be returned, // else the empty string "" will be returned. std::stringstream hasData(std::string s) { auto found_null = s.find("null"); auto b1 = s.find_first_of("["); auto b2 = s.find_last_of("]"); if (found_null != std::string::npos) { return std::stringstream(); } else if (b1 != std::string::npos && b2 != std::string::npos) { std::stringstream tmp = std::stringstream(); tmp.str(s.substr(b1, b2 - b1 + 1)); return tmp; } return std::stringstream(); } int main() { uWS::Hub h; PID pid; // TODO: Initialize the pid variable. h.onMessage([&pid](uWS::WebSocket<uWS::SERVER> ws, char *data, size_t length, uWS::OpCode opCode) { // "42" at the start of the message means there's a websocket message event. // The 4 signifies a websocket message // The 2 signifies a websocket event if (length && length > 2 && data[0] == '4' && data[1] == '2') { auto s = hasData(std::string(data)); if (s.str() != "") { auto j = json::parse(s); std::string event = j[0].get<std::string>(); if (event == "telemetry") { // j[1] is the data JSON object double cte = std::stod(j[1]["cte"].get<std::string>()); double speed = std::stod(j[1]["speed"].get<std::string>()); double angle = std::stod(j[1]["steering_angle"].get<std::string>()); /* * TODO: Calcuate steering value here, remember the steering value is * [-1, 1]. * NOTE: Feel free to play around with the throttle and speed. Maybe use * another PID controller to control the speed! */ /***************************************************************************** * Setup ****************************************************************************/ // TODO REVIEW THIS NONE RIGHT YET double steer_value = 0 ; double err = 0 ; double prev_cte = 0 ; double int_cte = 0 ; double diff_cte = 0 ; /***************************************************************************** * Twiddle ****************************************************************************/ vector<double> parameters; parameters = { 5.0, 5.0, 0.1 } ; vector<double> tune_parameters; tune_parameters = { 1.0, 1.0, 1.0 }; // double sum_tune_parameters = tune_parameters.sum() ; double best_err = 99999999.0; int counter = 0 ; cout << "Iteration" << counter << "\t best error" << best_err << "\t parameters" << parameters[0] << parameters[1] << parameters[2] << endl ; for (int i = 0; i < 3; i++) { parameters[i] += tune_parameters[i]; double current_error = 1; // TODO set current error UpdateError(cte)? // print(sum_parameters) if (current_error < best_err) { //last update worked, keep going tune_parameters[i] *= 1.1; best_err = current_error; // exit, since increase worked, -> loop } else { parameters[i] -= 2 * tune_parameters[i]; current_error = 1; // TODO set current error // check if decrease worked, if not, do a "reset" on the parameters if (current_error < best_err) { best_err = current_error; tune_parameters[i] *= 1.1; } else { parameters[i] += tune_parameters[i]; tune_parameters[i] *= .95; } } } /***************************************************************************** * Proportional integral derivative controller ****************************************************************************/ diff_cte = cte - prev_cte ; int_cte += cte ; steer_value = -parameters[0] * cte - parameters[1] * diff_cte - parameters[2] * int_cte ; prev_cte = cte ; // update CTE for next loop counter += 1 ; // DEBUG std::cout << "CTE: " << cte << " Steering Value: " << steer_value << std::endl; json msgJson; msgJson["steering_angle"] = steer_value; msgJson["throttle"] = 0.3; auto msg = "42[\"steer\"," + msgJson.dump() + "]"; std::cout << msg << std::endl; (ws).send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } else { // Manual driving std::string msg = "42[\"manual\",{}]"; (ws).send(msg.data(), msg.length(), uWS::OpCode::TEXT); } } }); h.onConnection([&h](uWS::WebSocket<uWS::SERVER> ws, uWS::HttpRequest req) { std::cout << "Connected!!!" << std::endl; }); h.onDisconnection([&h](uWS::WebSocket<uWS::SERVER> ws, int code, char *message, size_t length) { (ws).close(); std::cout << "Disconnected" << std::endl; }); int port = 4567; if (h.listen("0.0.0.0", port)) { std::cout << "Listening to port " << port << std::endl; } else { std::cerr << "Failed to listen to port" << std::endl; return -1; } h.run(); }<|endoftext|>
<commit_before>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2019-5-11 22:04:36 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; const int MAX_SIZE = 1000010; const long long MOD = 1000000007; long long inv[MAX_SIZE]; long long fact[MAX_SIZE]; long long factinv[MAX_SIZE]; void init() { inv[1] = 1; for (int i = 2; i < MAX_SIZE; i++) { inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD; } fact[0] = factinv[0] = 1; for (int i = 1; i < MAX_SIZE; i++) { fact[i] = (i * fact[i - 1]) % MOD; factinv[i] = (inv[i] * factinv[i - 1]) % MOD; } } long long C(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD; } return 0; } long long power(long long x, long long n) { if (n == 0) { return 1; } else if (n % 2 == 1) { return (x * power(x, n - 1)) % MOD; } else { long long half = power(x, n / 2); return (half * half) % MOD; } } long long gcd(long long x, long long y) { return y ? gcd(y, x % y) : x; } typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; typedef tuple<int, int> edge; typedef tuple<int, int, int> info; int N, M; int a[210]; int b[210]; vector<edge> V[20]; vector<int> W[1 << 20]; vector<int> memo[1 << 20]; set<int> sets[1 << 20]; void add_mask(int mask, int num) { if (sets[mask].find(num) != sets[mask].end()) { return; } sets[mask].insert(num); for (auto i = 0; i < N; i++) { if (((mask >> i) & 1) == 0) { add_mask(mask + (1 << i), num); } } } int main() { init(); cin >> N >> M; for (auto i = 0; i < M; i++) { cin >> a[i] >> b[i]; a[i]--; b[i]--; } for (auto i = 0; i < N - 1; i++) { V[a[i]].push_back(edge(b[i], i)); V[b[i]].push_back(edge(a[i], i)); } for (auto i = N - 1; i < M; i++) { edge from[20]; fill(from, from + 20, edge(-1, -1)); stack<info> S; S.push(info(a[i], -1, -1)); while (!S.empty()) { info e = S.top(); int dst = get<0>(e); int src = get<1>(e); int num = get<2>(e); S.pop(); if (from[dst] == edge(-1, -1)) { from[dst] = edge(src, num); if (dst == b[i]) { break; } for (auto x : V[dst]) { int next = get<0>(x); int next_num = get<1>(x); if (from[next] == edge(-1, -1)) { S.push(info(next, dst, next_num)); } } } } int mask = 0; int temp = b[i]; while (temp != a[i]) { int num = get<1>(from[temp]); mask += (1 << num); temp = get<0>(from[temp]); } int x = (1 << N) - mask; ll score = 0; for (auto i = 0; i < N; i++) { if ((x >> i) & 1) { score++; } } memo[mask].push_back(i); } for (auto i = 0; i < (1 << N); i++) { for (auto x : memo[i]) { add_mask(i, x); } } #if DEBUG == 1 if (N < 10) { for (auto i = 0; i < (1 << N); i++) { cerr << "sets[" << i << "] = {"; for (auto x : sets[i]) { cerr << x << ", "; } cerr << "}" << endl; } } #endif ll ans = (fact[N] * fact[M]) % MOD; }<commit_msg>tried F.cpp to 'F'<commit_after>#define DEBUG 1 /** * File : F.cpp * Author : Kazune Takahashi * Created : 2019-5-11 22:04:36 * Powered by Visual Studio Code */ #include <iostream> #include <iomanip> // << fixed << setprecision(xxx) #include <algorithm> // do { } while ( next_permutation(A, A+xxx) ) ; #include <vector> #include <string> // to_string(nnn) // substr(m, n) // stoi(nnn) #include <complex> #include <tuple> #include <queue> #include <stack> #include <map> // if (M.find(key) != M.end()) { } #include <set> #include <functional> #include <random> // auto rd = bind(uniform_int_distribution<int>(0, 9), mt19937(10101010)); #include <chrono> // std::chrono::system_clock::time_point start_time, end_time; // start = std::chrono::system_clock::now(); // double elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(end_time-start_time).count(); #include <cctype> #include <cassert> #include <cmath> #include <cstdio> #include <cstdlib> using namespace std; const int MAX_SIZE = 1000010; const long long MOD = 1000000007; long long inv[MAX_SIZE]; long long fact[MAX_SIZE]; long long factinv[MAX_SIZE]; void init() { inv[1] = 1; for (int i = 2; i < MAX_SIZE; i++) { inv[i] = ((MOD - inv[MOD % i]) * (MOD / i)) % MOD; } fact[0] = factinv[0] = 1; for (int i = 1; i < MAX_SIZE; i++) { fact[i] = (i * fact[i - 1]) % MOD; factinv[i] = (inv[i] * factinv[i - 1]) % MOD; } } long long C(int n, int k) { if (n >= 0 && k >= 0 && n - k >= 0) { return ((fact[n] * factinv[k]) % MOD * factinv[n - k]) % MOD; } return 0; } long long power(long long x, long long n) { if (n == 0) { return 1; } else if (n % 2 == 1) { return (x * power(x, n - 1)) % MOD; } else { long long half = power(x, n / 2); return (half * half) % MOD; } } long long gcd(long long x, long long y) { return y ? gcd(y, x % y) : x; } typedef long long ll; // const int dx[4] = {1, 0, -1, 0}; // const int dy[4] = {0, 1, 0, -1}; // const int C = 1e6+10; // const ll M = 1000000007; typedef tuple<int, int> edge; typedef tuple<int, int, int> info; int N, M; int a[210]; int b[210]; vector<edge> V[20]; vector<int> W[1 << 20]; vector<int> memo[1 << 20]; set<int> sets[1 << 20]; void add_mask(int mask, int num) { if (sets[mask].find(num) != sets[mask].end()) { return; } sets[mask].insert(num); for (auto i = 0; i < N; i++) { if (((mask >> i) & 1) == 0) { add_mask(mask + (1 << i), num); } } } int main() { init(); cin >> N >> M; for (auto i = 0; i < M; i++) { cin >> a[i] >> b[i]; a[i]--; b[i]--; } for (auto i = 0; i < N - 1; i++) { V[a[i]].push_back(edge(b[i], i)); V[b[i]].push_back(edge(a[i], i)); } for (auto i = N - 1; i < M; i++) { edge from[20]; fill(from, from + 20, edge(-1, -1)); stack<info> S; S.push(info(a[i], -1, -1)); while (!S.empty()) { info e = S.top(); int dst = get<0>(e); int src = get<1>(e); int num = get<2>(e); S.pop(); if (from[dst] == edge(-1, -1)) { from[dst] = edge(src, num); if (dst == b[i]) { break; } for (auto x : V[dst]) { int next = get<0>(x); int next_num = get<1>(x); if (from[next] == edge(-1, -1)) { S.push(info(next, dst, next_num)); } } } } int mask = 0; int temp = b[i]; while (temp != a[i]) { int num = get<1>(from[temp]); mask += (1 << num); temp = get<0>(from[temp]); } int x = (1 << N) - mask; ll score = 0; for (auto i = 0; i < N; i++) { if ((x >> i) & 1) { score++; } } memo[mask].push_back(i); } for (auto i = 0; i < (1 << N); i++) { for (auto x : memo[i]) { add_mask(i, x); } } #if DEBUG == 1 if (N < 16) { for (auto i = 0; i < (1 << N); i++) { cerr << "sets[" << i << "] = {"; for (auto x : sets[i]) { cerr << x << ", "; } cerr << "}" << endl; } } #endif ll ans = (fact[N] * fact[M]) % MOD; }<|endoftext|>
<commit_before>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/external_extension.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/render_messages_params.h" #include "chrome/renderer/render_view.h" #include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" #include "v8/include/v8.h" using WebKit::WebFrame; using WebKit::WebView; namespace extensions_v8 { static const char* const kSearchProviderApiV1 = "var external;" "if (!external)" " external = {};" "external.AddSearchProvider = function(name) {" " native function NativeAddSearchProvider();" " NativeAddSearchProvider(name);" "};"; static const char* const kSearchProviderApiV2 = "var external;" "if (!external)" " external = {};" "external.AddSearchProvider = function(name, default_provider) {" " native function NativeAddSearchProvider();" " NativeAddSearchProvider(name, default_provider);" "};" "external.IsSearchProviderInstalled = function(name) {" " native function NativeIsSearchProviderInstalled();" " return NativeIsSearchProviderInstalled(name);" "};"; #undef SEARCH_PROVIDER_API_V1 const char* const kExternalExtensionName = "v8/External"; // Should the new api's "IsSearchProviderInstalled and InstallSearchProvider // with an extra parameter to indicate if the provider should be the default" // be available? static bool EnableSearchProviderV2() { return CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableSearchProviderApiV2); } class ExternalExtensionWrapper : public v8::Extension { public: ExternalExtensionWrapper(); // Allows v8's javascript code to call the native functions defined // in this class for window.external. virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction( v8::Handle<v8::String> name); // Helper function to find the RenderView. May return NULL. static RenderView* GetRenderView(); // Implementation of window.external.AddSearchProvider. static v8::Handle<v8::Value> AddSearchProvider(const v8::Arguments& args); // Implementation of window.external.IsSearchProviderInstalled. static v8::Handle<v8::Value> IsSearchProviderInstalled( const v8::Arguments& args); private: DISALLOW_COPY_AND_ASSIGN(ExternalExtensionWrapper); }; ExternalExtensionWrapper::ExternalExtensionWrapper() : v8::Extension( kExternalExtensionName, !EnableSearchProviderV2() ? kSearchProviderApiV1 : kSearchProviderApiV2) { } v8::Handle<v8::FunctionTemplate> ExternalExtensionWrapper::GetNativeFunction( v8::Handle<v8::String> name) { if (name->Equals(v8::String::New("NativeAddSearchProvider"))) return v8::FunctionTemplate::New(AddSearchProvider); if (name->Equals(v8::String::New("NativeIsSearchProviderInstalled"))) return v8::FunctionTemplate::New(IsSearchProviderInstalled); return v8::Handle<v8::FunctionTemplate>(); } // static RenderView* ExternalExtensionWrapper::GetRenderView() { WebFrame* webframe = WebFrame::frameForEnteredContext(); DCHECK(webframe) << "There should be an active frame since we just got " "a native function called."; if (!webframe) return NULL; WebView* webview = webframe->view(); if (!webview) return NULL; // can happen during closing return RenderView::FromWebView(webview); } // static v8::Handle<v8::Value> ExternalExtensionWrapper::AddSearchProvider( const v8::Arguments& args) { if (!args.Length()) return v8::Undefined(); std::string name = std::string(*v8::String::Utf8Value(args[0])); if (!name.length()) return v8::Undefined(); ViewHostMsg_PageHasOSDD_Type provider_type = ((args.Length() < 2) || !args[1]->BooleanValue()) ? ViewHostMsg_PageHasOSDD_Type::Explicit() : ViewHostMsg_PageHasOSDD_Type::ExplicitDefault(); RenderView* render_view = GetRenderView(); if (!render_view) return v8::Undefined(); render_view->AddSearchProvider(name, provider_type); return v8::Undefined(); } // static v8::Handle<v8::Value> ExternalExtensionWrapper::IsSearchProviderInstalled( const v8::Arguments& args) { if (!args.Length()) return v8::Undefined(); std::string name = std::string(*v8::String::Utf8Value(args[0])); if (!name.length()) return v8::Undefined(); RenderView* render_view = GetRenderView(); if (!render_view) return v8::Undefined(); WebFrame* webframe = WebFrame::frameForEnteredContext(); if (!webframe) return v8::Undefined(); ViewHostMsg_GetSearchProviderInstallState_Params install = render_view->GetSearchProviderInstallState(webframe, name); if (install.state == ViewHostMsg_GetSearchProviderInstallState_Params::DENIED) { // FIXME: throw access denied exception. return v8::ThrowException(v8::Exception::Error(v8::String::Empty())); } return v8::Integer::New(install.state); } v8::Extension* ExternalExtension::Get() { return new ExternalExtensionWrapper(); } } // namespace extensions_v8 <commit_msg>Expose IsDefaultSearchProvider and SetDefaultSearchProvider by default on Windows.<commit_after>// Copyright (c) 2009 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "chrome/renderer/external_extension.h" #include "base/command_line.h" #include "chrome/common/chrome_switches.h" #include "chrome/common/render_messages_params.h" #include "chrome/renderer/render_view.h" #include "third_party/WebKit/WebKit/chromium/public/WebFrame.h" #include "v8/include/v8.h" using WebKit::WebFrame; using WebKit::WebView; namespace extensions_v8 { static const char* const kSearchProviderApiV1 = "var external;" "if (!external)" " external = {};" "external.AddSearchProvider = function(name) {" " native function NativeAddSearchProvider();" " NativeAddSearchProvider(name);" "};"; static const char* const kSearchProviderApiV2 = "var external;" "if (!external)" " external = {};" "external.AddSearchProvider = function(name, default_provider) {" " native function NativeAddSearchProvider();" " NativeAddSearchProvider(name, default_provider);" "};" "external.IsSearchProviderInstalled = function(name) {" " native function NativeIsSearchProviderInstalled();" " return NativeIsSearchProviderInstalled(name);" "};"; #undef SEARCH_PROVIDER_API_V1 const char* const kExternalExtensionName = "v8/External"; // Should the new api's "IsSearchProviderInstalled and InstallSearchProvider // with an extra parameter to indicate if the provider should be the default" // be available? static bool EnableSearchProviderV2() { #if defined(OS_WIN) return true; #else return CommandLine::ForCurrentProcess()->HasSwitch( switches::kEnableSearchProviderApiV2); #endif } class ExternalExtensionWrapper : public v8::Extension { public: ExternalExtensionWrapper(); // Allows v8's javascript code to call the native functions defined // in this class for window.external. virtual v8::Handle<v8::FunctionTemplate> GetNativeFunction( v8::Handle<v8::String> name); // Helper function to find the RenderView. May return NULL. static RenderView* GetRenderView(); // Implementation of window.external.AddSearchProvider. static v8::Handle<v8::Value> AddSearchProvider(const v8::Arguments& args); // Implementation of window.external.IsSearchProviderInstalled. static v8::Handle<v8::Value> IsSearchProviderInstalled( const v8::Arguments& args); private: DISALLOW_COPY_AND_ASSIGN(ExternalExtensionWrapper); }; ExternalExtensionWrapper::ExternalExtensionWrapper() : v8::Extension( kExternalExtensionName, !EnableSearchProviderV2() ? kSearchProviderApiV1 : kSearchProviderApiV2) { } v8::Handle<v8::FunctionTemplate> ExternalExtensionWrapper::GetNativeFunction( v8::Handle<v8::String> name) { if (name->Equals(v8::String::New("NativeAddSearchProvider"))) return v8::FunctionTemplate::New(AddSearchProvider); if (name->Equals(v8::String::New("NativeIsSearchProviderInstalled"))) return v8::FunctionTemplate::New(IsSearchProviderInstalled); return v8::Handle<v8::FunctionTemplate>(); } // static RenderView* ExternalExtensionWrapper::GetRenderView() { WebFrame* webframe = WebFrame::frameForEnteredContext(); DCHECK(webframe) << "There should be an active frame since we just got " "a native function called."; if (!webframe) return NULL; WebView* webview = webframe->view(); if (!webview) return NULL; // can happen during closing return RenderView::FromWebView(webview); } // static v8::Handle<v8::Value> ExternalExtensionWrapper::AddSearchProvider( const v8::Arguments& args) { if (!args.Length()) return v8::Undefined(); std::string name = std::string(*v8::String::Utf8Value(args[0])); if (!name.length()) return v8::Undefined(); ViewHostMsg_PageHasOSDD_Type provider_type = ((args.Length() < 2) || !args[1]->BooleanValue()) ? ViewHostMsg_PageHasOSDD_Type::Explicit() : ViewHostMsg_PageHasOSDD_Type::ExplicitDefault(); RenderView* render_view = GetRenderView(); if (!render_view) return v8::Undefined(); render_view->AddSearchProvider(name, provider_type); return v8::Undefined(); } // static v8::Handle<v8::Value> ExternalExtensionWrapper::IsSearchProviderInstalled( const v8::Arguments& args) { if (!args.Length()) return v8::Undefined(); std::string name = std::string(*v8::String::Utf8Value(args[0])); if (!name.length()) return v8::Undefined(); RenderView* render_view = GetRenderView(); if (!render_view) return v8::Undefined(); WebFrame* webframe = WebFrame::frameForEnteredContext(); if (!webframe) return v8::Undefined(); ViewHostMsg_GetSearchProviderInstallState_Params install = render_view->GetSearchProviderInstallState(webframe, name); if (install.state == ViewHostMsg_GetSearchProviderInstallState_Params::DENIED) { // FIXME: throw access denied exception. return v8::ThrowException(v8::Exception::Error(v8::String::Empty())); } return v8::Integer::New(install.state); } v8::Extension* ExternalExtension::Get() { return new ExternalExtensionWrapper(); } } // namespace extensions_v8 <|endoftext|>
<commit_before>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CIRCULAR_BUFFER_HH_ #define CIRCULAR_BUFFER_HH_ // A growable double-ended queue container that can be efficiently // extended (and shrunk) from both ends. Implementation is a single // storage vector. // // Similar to libstdc++'s std::deque, except that it uses a single level // store, and so is more efficient for simple stored items. // Similar to boost::circular_buffer_space_optimized, except it uses // uninitialized storage for unoccupied elements (and thus move/copy // constructors instead of move/copy assignments, which are less efficient). #include "transfer.hh" #include <memory> #include <algorithm> template <typename T, typename Alloc = std::allocator<T>> class circular_buffer { struct impl : Alloc { T* storage = nullptr; T* begin = nullptr; T* end = nullptr; // never points at storage+capacity size_t size = 0; size_t capacity = 0; }; impl _impl; public: using value_type = T; using size_type = size_t; using reference = T&; using pointer = T*; using const_reference = const T&; using const_pointer = const T*; public: circular_buffer() = default; circular_buffer(circular_buffer&& X); circular_buffer(const circular_buffer& X) = delete; ~circular_buffer(); circular_buffer& operator=(const circular_buffer&) = delete; circular_buffer& operator=(circular_buffer&&) = delete; void push_front(const T& data); void push_front(T&& data); template <typename... A> void emplace_front(A... args); void push_back(const T& data); void push_back(T&& data); template <typename... A> void emplace_back(A... args); T& front(); T& back(); void pop_front(); void pop_back(); bool empty() const; size_t size() const; size_t capacity() const; T& operator[](size_t idx); template <typename Func> void for_each(Func func); private: void expand(); void maybe_expand(size_t nr = 1); T* pre_push_front(); T* pre_push_back(); void post_push_front(T* p); void post_push_back(T* p); }; template <typename T, typename Alloc> inline bool circular_buffer<T, Alloc>::empty() const { return _impl.begin == _impl.end; } template <typename T, typename Alloc> inline size_t circular_buffer<T, Alloc>::size() const { return _impl.size; } template <typename T, typename Alloc> inline size_t circular_buffer<T, Alloc>::capacity() const { // we never use all of the elements, since end == begin means empty return _impl.capacity ? _impl.capacity - 1 : 0; } template <typename T, typename Alloc> inline circular_buffer<T, Alloc>::circular_buffer(circular_buffer&& x) : _impl(std::move(x._impl)) { x._impl = {}; } template <typename T, typename Alloc> template <typename Func> inline void circular_buffer<T, Alloc>::for_each(Func func) { auto p = _impl.begin; auto e = _impl.storage + _impl.capacity; if (p > _impl.end) { while (p < e) { func(*p++); } p = _impl.storage; } while (p < _impl.end) { func(*p++); } } template <typename T, typename Alloc> inline circular_buffer<T, Alloc>::~circular_buffer() { for_each([this] (T& obj) { _impl.destroy(&obj); }); _impl.deallocate(_impl.storage, _impl.capacity); } template <typename T, typename Alloc> void circular_buffer<T, Alloc>::expand() { auto new_cap = std::max<size_t>(_impl.capacity * 2, 2); auto new_storage = _impl.allocate(new_cap); auto p = new_storage; try { for_each([this, &p] (T& obj) { transfer_pass1(_impl, &obj, p++); }); } catch (...) { while (p != new_storage) { _impl.destroy(--p); } _impl.deallocate(new_storage, new_cap); throw; } p = new_storage; for_each([this, &p] (T& obj) { transfer_pass2(_impl, &obj, p++); }); std::swap(_impl.storage, new_storage); std::swap(_impl.capacity, new_cap); _impl.begin = _impl.storage; _impl.end = p; _impl.deallocate(new_storage, new_cap); } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::maybe_expand(size_t nr) { // one item is always unused if (_impl.size + nr >= _impl.capacity) { expand(); } } template <typename T, typename Alloc> inline T* circular_buffer<T, Alloc>::pre_push_front() { maybe_expand(); if (_impl.begin == _impl.storage) { return _impl.storage + _impl.capacity - 1; } else { return _impl.begin - 1; } } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::post_push_front(T* p) { _impl.begin = p; ++_impl.size; } template <typename T, typename Alloc> inline T* circular_buffer<T, Alloc>::pre_push_back() { maybe_expand(); return _impl.end; } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::post_push_back(T* p) { if (++p == _impl.storage + _impl.capacity) { p = _impl.storage; } _impl.end = p; ++_impl.size; } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::push_front(const T& data) { auto p = pre_push_front(); _impl.construct(p, data); post_push_front(p); } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::push_front(T&& data) { auto p = pre_push_front(); _impl.construct(p, std::move(data)); post_push_front(p); } template <typename T, typename Alloc> template <typename... Args> inline void circular_buffer<T, Alloc>::emplace_front(Args... args) { auto p = pre_push_front(); _impl.construct(p, std::forward<Args>(args)...); post_push_front(p); } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::push_back(const T& data) { auto p = pre_push_back(); _impl.construct(p, data); post_push_back(p); } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::push_back(T&& data) { auto p = pre_push_back(); _impl.construct(p, std::move(data)); post_push_back(p); } template <typename T, typename Alloc> template <typename... Args> inline void circular_buffer<T, Alloc>::emplace_back(Args... args) { auto p = pre_push_back(); _impl.construct(p, std::forward<Args>(args)...); post_push_back(p); } template <typename T, typename Alloc> inline T& circular_buffer<T, Alloc>::front() { return *_impl.begin; } template <typename T, typename Alloc> inline T& circular_buffer<T, Alloc>::back() { if (_impl.end == _impl.storage) { return *(_impl.storage + _impl.capacity - 1); } else { return *_impl.end; } } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::pop_front() { ++_impl.begin; if (_impl.begin == _impl.storage + _impl.capacity) { _impl.begin = _impl.storage; } --_impl.size; } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::pop_back() { if (_impl.end == _impl.begin) { _impl.end = _impl.storage + _impl.capacity; } --_impl.end; --_impl.size; } template <typename T, typename Alloc> inline T& circular_buffer<T, Alloc>::operator[](size_t idx) { auto p = _impl.begin + idx; if (p >= _impl.storage + _impl.capacity) { p -= _impl.capacity; } return *p; } #endif /* CIRCULAR_BUFFER_HH_ */ <commit_msg>circular_buffer: fix pop_front(), pop_back()<commit_after>/* * Copyright (C) 2014 Cloudius Systems, Ltd. */ #ifndef CIRCULAR_BUFFER_HH_ #define CIRCULAR_BUFFER_HH_ // A growable double-ended queue container that can be efficiently // extended (and shrunk) from both ends. Implementation is a single // storage vector. // // Similar to libstdc++'s std::deque, except that it uses a single level // store, and so is more efficient for simple stored items. // Similar to boost::circular_buffer_space_optimized, except it uses // uninitialized storage for unoccupied elements (and thus move/copy // constructors instead of move/copy assignments, which are less efficient). #include "transfer.hh" #include <memory> #include <algorithm> template <typename T, typename Alloc = std::allocator<T>> class circular_buffer { struct impl : Alloc { T* storage = nullptr; T* begin = nullptr; T* end = nullptr; // never points at storage+capacity size_t size = 0; size_t capacity = 0; }; impl _impl; public: using value_type = T; using size_type = size_t; using reference = T&; using pointer = T*; using const_reference = const T&; using const_pointer = const T*; public: circular_buffer() = default; circular_buffer(circular_buffer&& X); circular_buffer(const circular_buffer& X) = delete; ~circular_buffer(); circular_buffer& operator=(const circular_buffer&) = delete; circular_buffer& operator=(circular_buffer&&) = delete; void push_front(const T& data); void push_front(T&& data); template <typename... A> void emplace_front(A... args); void push_back(const T& data); void push_back(T&& data); template <typename... A> void emplace_back(A... args); T& front(); T& back(); void pop_front(); void pop_back(); bool empty() const; size_t size() const; size_t capacity() const; T& operator[](size_t idx); template <typename Func> void for_each(Func func); private: void expand(); void maybe_expand(size_t nr = 1); T* pre_push_front(); T* pre_push_back(); void post_push_front(T* p); void post_push_back(T* p); }; template <typename T, typename Alloc> inline bool circular_buffer<T, Alloc>::empty() const { return _impl.begin == _impl.end; } template <typename T, typename Alloc> inline size_t circular_buffer<T, Alloc>::size() const { return _impl.size; } template <typename T, typename Alloc> inline size_t circular_buffer<T, Alloc>::capacity() const { // we never use all of the elements, since end == begin means empty return _impl.capacity ? _impl.capacity - 1 : 0; } template <typename T, typename Alloc> inline circular_buffer<T, Alloc>::circular_buffer(circular_buffer&& x) : _impl(std::move(x._impl)) { x._impl = {}; } template <typename T, typename Alloc> template <typename Func> inline void circular_buffer<T, Alloc>::for_each(Func func) { auto p = _impl.begin; auto e = _impl.storage + _impl.capacity; if (p > _impl.end) { while (p < e) { func(*p++); } p = _impl.storage; } while (p < _impl.end) { func(*p++); } } template <typename T, typename Alloc> inline circular_buffer<T, Alloc>::~circular_buffer() { for_each([this] (T& obj) { _impl.destroy(&obj); }); _impl.deallocate(_impl.storage, _impl.capacity); } template <typename T, typename Alloc> void circular_buffer<T, Alloc>::expand() { auto new_cap = std::max<size_t>(_impl.capacity * 2, 2); auto new_storage = _impl.allocate(new_cap); auto p = new_storage; try { for_each([this, &p] (T& obj) { transfer_pass1(_impl, &obj, p++); }); } catch (...) { while (p != new_storage) { _impl.destroy(--p); } _impl.deallocate(new_storage, new_cap); throw; } p = new_storage; for_each([this, &p] (T& obj) { transfer_pass2(_impl, &obj, p++); }); std::swap(_impl.storage, new_storage); std::swap(_impl.capacity, new_cap); _impl.begin = _impl.storage; _impl.end = p; _impl.deallocate(new_storage, new_cap); } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::maybe_expand(size_t nr) { // one item is always unused if (_impl.size + nr >= _impl.capacity) { expand(); } } template <typename T, typename Alloc> inline T* circular_buffer<T, Alloc>::pre_push_front() { maybe_expand(); if (_impl.begin == _impl.storage) { return _impl.storage + _impl.capacity - 1; } else { return _impl.begin - 1; } } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::post_push_front(T* p) { _impl.begin = p; ++_impl.size; } template <typename T, typename Alloc> inline T* circular_buffer<T, Alloc>::pre_push_back() { maybe_expand(); return _impl.end; } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::post_push_back(T* p) { if (++p == _impl.storage + _impl.capacity) { p = _impl.storage; } _impl.end = p; ++_impl.size; } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::push_front(const T& data) { auto p = pre_push_front(); _impl.construct(p, data); post_push_front(p); } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::push_front(T&& data) { auto p = pre_push_front(); _impl.construct(p, std::move(data)); post_push_front(p); } template <typename T, typename Alloc> template <typename... Args> inline void circular_buffer<T, Alloc>::emplace_front(Args... args) { auto p = pre_push_front(); _impl.construct(p, std::forward<Args>(args)...); post_push_front(p); } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::push_back(const T& data) { auto p = pre_push_back(); _impl.construct(p, data); post_push_back(p); } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::push_back(T&& data) { auto p = pre_push_back(); _impl.construct(p, std::move(data)); post_push_back(p); } template <typename T, typename Alloc> template <typename... Args> inline void circular_buffer<T, Alloc>::emplace_back(Args... args) { auto p = pre_push_back(); _impl.construct(p, std::forward<Args>(args)...); post_push_back(p); } template <typename T, typename Alloc> inline T& circular_buffer<T, Alloc>::front() { return *_impl.begin; } template <typename T, typename Alloc> inline T& circular_buffer<T, Alloc>::back() { if (_impl.end == _impl.storage) { return *(_impl.storage + _impl.capacity - 1); } else { return *_impl.end; } } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::pop_front() { _impl.destroy(&front()); ++_impl.begin; if (_impl.begin == _impl.storage + _impl.capacity) { _impl.begin = _impl.storage; } --_impl.size; } template <typename T, typename Alloc> inline void circular_buffer<T, Alloc>::pop_back() { _impl.destroy(&back()); if (_impl.end == _impl.begin) { _impl.end = _impl.storage + _impl.capacity; } --_impl.end; --_impl.size; } template <typename T, typename Alloc> inline T& circular_buffer<T, Alloc>::operator[](size_t idx) { auto p = _impl.begin + idx; if (p >= _impl.storage + _impl.capacity) { p -= _impl.capacity; } return *p; } #endif /* CIRCULAR_BUFFER_HH_ */ <|endoftext|>
<commit_before>//===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the RABasic function pass, which provides a minimal // implementation of the basic register allocator. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "regalloc" #include "RegAllocBase.h" #include "LiveDebugVariables.h" #include "LiveRangeEdit.h" #include "RenderMachineFunction.h" #include "Spiller.h" #include "VirtRegMap.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Function.h" #include "llvm/PassAnalysisSupport.h" #include "llvm/CodeGen/CalcSpillWeights.h" #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/LiveStackAnalysis.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/RegAllocRegistry.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include <cstdlib> #include <queue> using namespace llvm; static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator", createBasicRegisterAllocator); namespace { struct CompSpillWeight { bool operator()(LiveInterval *A, LiveInterval *B) const { return A->weight < B->weight; } }; } namespace { /// RABasic provides a minimal implementation of the basic register allocation /// algorithm. It prioritizes live virtual registers by spill weight and spills /// whenever a register is unavailable. This is not practical in production but /// provides a useful baseline both for measuring other allocators and comparing /// the speed of the basic algorithm against other styles of allocators. class RABasic : public MachineFunctionPass, public RegAllocBase { // context MachineFunction *MF; // analyses LiveStacks *LS; RenderMachineFunction *RMF; // state std::auto_ptr<Spiller> SpillerInstance; std::priority_queue<LiveInterval*, std::vector<LiveInterval*>, CompSpillWeight> Queue; public: RABasic(); /// Return the pass name. virtual const char* getPassName() const { return "Basic Register Allocator"; } /// RABasic analysis usage. virtual void getAnalysisUsage(AnalysisUsage &AU) const; virtual void releaseMemory(); virtual Spiller &spiller() { return *SpillerInstance; } virtual float getPriority(LiveInterval *LI) { return LI->weight; } virtual void enqueue(LiveInterval *LI) { Queue.push(LI); } virtual LiveInterval *dequeue() { if (Queue.empty()) return 0; LiveInterval *LI = Queue.top(); Queue.pop(); return LI; } virtual unsigned selectOrSplit(LiveInterval &VirtReg, SmallVectorImpl<LiveInterval*> &SplitVRegs); /// Perform register allocation. virtual bool runOnMachineFunction(MachineFunction &mf); // Helper for spilling all live virtual registers currently unified under preg // that interfere with the most recently queried lvr. Return true if spilling // was successful, and append any new spilled/split intervals to splitLVRs. bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg, SmallVectorImpl<LiveInterval*> &SplitVRegs); void spillReg(LiveInterval &VirtReg, unsigned PhysReg, SmallVectorImpl<LiveInterval*> &SplitVRegs); static char ID; }; char RABasic::ID = 0; } // end anonymous namespace RABasic::RABasic(): MachineFunctionPass(ID) { initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry()); initializeLiveIntervalsPass(*PassRegistry::getPassRegistry()); initializeSlotIndexesPass(*PassRegistry::getPassRegistry()); initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry()); initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry()); initializeMachineSchedulerPass(*PassRegistry::getPassRegistry()); initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry()); initializeLiveStacksPass(*PassRegistry::getPassRegistry()); initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry()); initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry()); initializeVirtRegMapPass(*PassRegistry::getPassRegistry()); initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry()); } void RABasic::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); AU.addRequired<AliasAnalysis>(); AU.addPreserved<AliasAnalysis>(); AU.addRequired<LiveIntervals>(); AU.addPreserved<SlotIndexes>(); AU.addRequired<LiveDebugVariables>(); AU.addPreserved<LiveDebugVariables>(); if (StrongPHIElim) AU.addRequiredID(StrongPHIEliminationID); AU.addRequiredTransitiveID(RegisterCoalescerPassID); AU.addRequired<CalculateSpillWeights>(); AU.addRequired<LiveStacks>(); AU.addPreserved<LiveStacks>(); AU.addRequiredID(MachineDominatorsID); AU.addPreservedID(MachineDominatorsID); AU.addRequired<MachineLoopInfo>(); AU.addPreserved<MachineLoopInfo>(); AU.addRequired<VirtRegMap>(); AU.addPreserved<VirtRegMap>(); DEBUG(AU.addRequired<RenderMachineFunction>()); MachineFunctionPass::getAnalysisUsage(AU); } void RABasic::releaseMemory() { SpillerInstance.reset(0); RegAllocBase::releaseMemory(); } // Helper for spillInterferences() that spills all interfering vregs currently // assigned to this physical register. void RABasic::spillReg(LiveInterval& VirtReg, unsigned PhysReg, SmallVectorImpl<LiveInterval*> &SplitVRegs) { LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg); assert(Q.seenAllInterferences() && "need collectInterferences()"); const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs(); for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(), E = PendingSpills.end(); I != E; ++I) { LiveInterval &SpilledVReg = **I; DEBUG(dbgs() << "extracting from " << TRI->getName(PhysReg) << " " << SpilledVReg << '\n'); // Deallocate the interfering vreg by removing it from the union. // A LiveInterval instance may not be in a union during modification! unassign(SpilledVReg, PhysReg); // Spill the extracted interval. LiveRangeEdit LRE(SpilledVReg, SplitVRegs, 0, &PendingSpills); spiller().spill(LRE); } // After extracting segments, the query's results are invalid. But keep the // contents valid until we're done accessing pendingSpills. Q.clear(); } // Spill or split all live virtual registers currently unified under PhysReg // that interfere with VirtReg. The newly spilled or split live intervals are // returned by appending them to SplitVRegs. bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg, SmallVectorImpl<LiveInterval*> &SplitVRegs) { // Record each interference and determine if all are spillable before mutating // either the union or live intervals. unsigned NumInterferences = 0; // Collect interferences assigned to any alias of the physical register. for (const unsigned *asI = TRI->getOverlaps(PhysReg); *asI; ++asI) { LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI); NumInterferences += QAlias.collectInterferingVRegs(); if (QAlias.seenUnspillableVReg()) { return false; } } DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) << " interferences with " << VirtReg << "\n"); assert(NumInterferences > 0 && "expect interference"); // Spill each interfering vreg allocated to PhysReg or an alias. for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) spillReg(VirtReg, *AliasI, SplitVRegs); return true; } // Driver for the register assignment and splitting heuristics. // Manages iteration over the LiveIntervalUnions. // // This is a minimal implementation of register assignment and splitting that // spills whenever we run out of registers. // // selectOrSplit can only be called once per live virtual register. We then do a // single interference test for each register the correct class until we find an // available register. So, the number of interference tests in the worst case is // |vregs| * |machineregs|. And since the number of interference tests is // minimal, there is no value in caching them outside the scope of // selectOrSplit(). unsigned RABasic::selectOrSplit(LiveInterval &VirtReg, SmallVectorImpl<LiveInterval*> &SplitVRegs) { // Populate a list of physical register spill candidates. SmallVector<unsigned, 8> PhysRegSpillCands; // Check for an available register in this class. ArrayRef<unsigned> Order = RegClassInfo.getOrder(MRI->getRegClass(VirtReg.reg)); for (ArrayRef<unsigned>::iterator I = Order.begin(), E = Order.end(); I != E; ++I) { unsigned PhysReg = *I; // Check interference and as a side effect, intialize queries for this // VirtReg and its aliases. unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg); if (interfReg == 0) { // Found an available register. return PhysReg; } LiveIntervalUnion::Query &IntfQ = query(VirtReg, interfReg); IntfQ.collectInterferingVRegs(1); LiveInterval *interferingVirtReg = IntfQ.interferingVRegs().front(); // The current VirtReg must either be spillable, or one of its interferences // must have less spill weight. if (interferingVirtReg->weight < VirtReg.weight ) { PhysRegSpillCands.push_back(PhysReg); } } // Try to spill another interfering reg with less spill weight. for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(), PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) { if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue; assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 && "Interference after spill."); // Tell the caller to allocate to this newly freed physical register. return *PhysRegI; } // No other spill candidates were found, so spill the current VirtReg. DEBUG(dbgs() << "spilling: " << VirtReg << '\n'); if (!VirtReg.isSpillable()) return ~0u; LiveRangeEdit LRE(VirtReg, SplitVRegs); spiller().spill(LRE); // The live virtual register requesting allocation was spilled, so tell // the caller not to allocate anything during this round. return 0; } bool RABasic::runOnMachineFunction(MachineFunction &mf) { DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n" << "********** Function: " << ((Value*)mf.getFunction())->getName() << '\n'); MF = &mf; DEBUG(RMF = &getAnalysis<RenderMachineFunction>()); RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>()); SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM)); allocatePhysRegs(); addMBBLiveIns(MF); // Diagnostic output before rewriting DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n"); // optional HTML output DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM)); // FIXME: Verification currently must run before VirtRegRewriter. We should // make the rewriter a separate pass and override verifyAnalysis instead. When // that happens, verification naturally falls under VerifyMachineCode. #ifndef NDEBUG if (VerifyEnabled) { // Verify accuracy of LiveIntervals. The standard machine code verifier // ensures that each LiveIntervals covers all uses of the virtual reg. // FIXME: MachineVerifier is badly broken when using the standard // spiller. Always use -spiller=inline with -verify-regalloc. Even with the // inline spiller, some tests fail to verify because the coalescer does not // always generate verifiable code. MF->verify(this, "In RABasic::verify"); // Verify that LiveIntervals are partitioned into unions and disjoint within // the unions. verify(); } #endif // !NDEBUG // Run rewriter VRM->rewrite(LIS->getSlotIndexes()); // Write out new DBG_VALUE instructions. getAnalysis<LiveDebugVariables>().emitDebugValues(VRM); // The pass output is in VirtRegMap. Release all the transient data. releaseMemory(); return true; } FunctionPass* llvm::createBasicRegisterAllocator() { return new RABasic(); } <commit_msg>Add Register mask support to RABasic.<commit_after>//===-- RegAllocBasic.cpp - Basic Register Allocator ----------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines the RABasic function pass, which provides a minimal // implementation of the basic register allocator. // //===----------------------------------------------------------------------===// #define DEBUG_TYPE "regalloc" #include "RegAllocBase.h" #include "LiveDebugVariables.h" #include "LiveRangeEdit.h" #include "RenderMachineFunction.h" #include "Spiller.h" #include "VirtRegMap.h" #include "llvm/Analysis/AliasAnalysis.h" #include "llvm/Function.h" #include "llvm/PassAnalysisSupport.h" #include "llvm/CodeGen/CalcSpillWeights.h" #include "llvm/CodeGen/LiveIntervalAnalysis.h" #include "llvm/CodeGen/LiveStackAnalysis.h" #include "llvm/CodeGen/MachineFunctionPass.h" #include "llvm/CodeGen/MachineInstr.h" #include "llvm/CodeGen/MachineLoopInfo.h" #include "llvm/CodeGen/MachineRegisterInfo.h" #include "llvm/CodeGen/Passes.h" #include "llvm/CodeGen/RegAllocRegistry.h" #include "llvm/Target/TargetMachine.h" #include "llvm/Target/TargetOptions.h" #include "llvm/Target/TargetRegisterInfo.h" #include "llvm/Support/Debug.h" #include "llvm/Support/raw_ostream.h" #include <cstdlib> #include <queue> using namespace llvm; static RegisterRegAlloc basicRegAlloc("basic", "basic register allocator", createBasicRegisterAllocator); namespace { struct CompSpillWeight { bool operator()(LiveInterval *A, LiveInterval *B) const { return A->weight < B->weight; } }; } namespace { /// RABasic provides a minimal implementation of the basic register allocation /// algorithm. It prioritizes live virtual registers by spill weight and spills /// whenever a register is unavailable. This is not practical in production but /// provides a useful baseline both for measuring other allocators and comparing /// the speed of the basic algorithm against other styles of allocators. class RABasic : public MachineFunctionPass, public RegAllocBase { // context MachineFunction *MF; // analyses LiveStacks *LS; RenderMachineFunction *RMF; // state std::auto_ptr<Spiller> SpillerInstance; std::priority_queue<LiveInterval*, std::vector<LiveInterval*>, CompSpillWeight> Queue; // Scratch space. Allocated here to avoid repeated malloc calls in // selectOrSplit(). BitVector UsableRegs; public: RABasic(); /// Return the pass name. virtual const char* getPassName() const { return "Basic Register Allocator"; } /// RABasic analysis usage. virtual void getAnalysisUsage(AnalysisUsage &AU) const; virtual void releaseMemory(); virtual Spiller &spiller() { return *SpillerInstance; } virtual float getPriority(LiveInterval *LI) { return LI->weight; } virtual void enqueue(LiveInterval *LI) { Queue.push(LI); } virtual LiveInterval *dequeue() { if (Queue.empty()) return 0; LiveInterval *LI = Queue.top(); Queue.pop(); return LI; } virtual unsigned selectOrSplit(LiveInterval &VirtReg, SmallVectorImpl<LiveInterval*> &SplitVRegs); /// Perform register allocation. virtual bool runOnMachineFunction(MachineFunction &mf); // Helper for spilling all live virtual registers currently unified under preg // that interfere with the most recently queried lvr. Return true if spilling // was successful, and append any new spilled/split intervals to splitLVRs. bool spillInterferences(LiveInterval &VirtReg, unsigned PhysReg, SmallVectorImpl<LiveInterval*> &SplitVRegs); void spillReg(LiveInterval &VirtReg, unsigned PhysReg, SmallVectorImpl<LiveInterval*> &SplitVRegs); static char ID; }; char RABasic::ID = 0; } // end anonymous namespace RABasic::RABasic(): MachineFunctionPass(ID) { initializeLiveDebugVariablesPass(*PassRegistry::getPassRegistry()); initializeLiveIntervalsPass(*PassRegistry::getPassRegistry()); initializeSlotIndexesPass(*PassRegistry::getPassRegistry()); initializeStrongPHIEliminationPass(*PassRegistry::getPassRegistry()); initializeRegisterCoalescerPass(*PassRegistry::getPassRegistry()); initializeMachineSchedulerPass(*PassRegistry::getPassRegistry()); initializeCalculateSpillWeightsPass(*PassRegistry::getPassRegistry()); initializeLiveStacksPass(*PassRegistry::getPassRegistry()); initializeMachineDominatorTreePass(*PassRegistry::getPassRegistry()); initializeMachineLoopInfoPass(*PassRegistry::getPassRegistry()); initializeVirtRegMapPass(*PassRegistry::getPassRegistry()); initializeRenderMachineFunctionPass(*PassRegistry::getPassRegistry()); } void RABasic::getAnalysisUsage(AnalysisUsage &AU) const { AU.setPreservesCFG(); AU.addRequired<AliasAnalysis>(); AU.addPreserved<AliasAnalysis>(); AU.addRequired<LiveIntervals>(); AU.addPreserved<SlotIndexes>(); AU.addRequired<LiveDebugVariables>(); AU.addPreserved<LiveDebugVariables>(); if (StrongPHIElim) AU.addRequiredID(StrongPHIEliminationID); AU.addRequiredTransitiveID(RegisterCoalescerPassID); AU.addRequired<CalculateSpillWeights>(); AU.addRequired<LiveStacks>(); AU.addPreserved<LiveStacks>(); AU.addRequiredID(MachineDominatorsID); AU.addPreservedID(MachineDominatorsID); AU.addRequired<MachineLoopInfo>(); AU.addPreserved<MachineLoopInfo>(); AU.addRequired<VirtRegMap>(); AU.addPreserved<VirtRegMap>(); DEBUG(AU.addRequired<RenderMachineFunction>()); MachineFunctionPass::getAnalysisUsage(AU); } void RABasic::releaseMemory() { SpillerInstance.reset(0); RegAllocBase::releaseMemory(); } // Helper for spillInterferences() that spills all interfering vregs currently // assigned to this physical register. void RABasic::spillReg(LiveInterval& VirtReg, unsigned PhysReg, SmallVectorImpl<LiveInterval*> &SplitVRegs) { LiveIntervalUnion::Query &Q = query(VirtReg, PhysReg); assert(Q.seenAllInterferences() && "need collectInterferences()"); const SmallVectorImpl<LiveInterval*> &PendingSpills = Q.interferingVRegs(); for (SmallVectorImpl<LiveInterval*>::const_iterator I = PendingSpills.begin(), E = PendingSpills.end(); I != E; ++I) { LiveInterval &SpilledVReg = **I; DEBUG(dbgs() << "extracting from " << TRI->getName(PhysReg) << " " << SpilledVReg << '\n'); // Deallocate the interfering vreg by removing it from the union. // A LiveInterval instance may not be in a union during modification! unassign(SpilledVReg, PhysReg); // Spill the extracted interval. LiveRangeEdit LRE(SpilledVReg, SplitVRegs, 0, &PendingSpills); spiller().spill(LRE); } // After extracting segments, the query's results are invalid. But keep the // contents valid until we're done accessing pendingSpills. Q.clear(); } // Spill or split all live virtual registers currently unified under PhysReg // that interfere with VirtReg. The newly spilled or split live intervals are // returned by appending them to SplitVRegs. bool RABasic::spillInterferences(LiveInterval &VirtReg, unsigned PhysReg, SmallVectorImpl<LiveInterval*> &SplitVRegs) { // Record each interference and determine if all are spillable before mutating // either the union or live intervals. unsigned NumInterferences = 0; // Collect interferences assigned to any alias of the physical register. for (const unsigned *asI = TRI->getOverlaps(PhysReg); *asI; ++asI) { LiveIntervalUnion::Query &QAlias = query(VirtReg, *asI); NumInterferences += QAlias.collectInterferingVRegs(); if (QAlias.seenUnspillableVReg()) { return false; } } DEBUG(dbgs() << "spilling " << TRI->getName(PhysReg) << " interferences with " << VirtReg << "\n"); assert(NumInterferences > 0 && "expect interference"); // Spill each interfering vreg allocated to PhysReg or an alias. for (const unsigned *AliasI = TRI->getOverlaps(PhysReg); *AliasI; ++AliasI) spillReg(VirtReg, *AliasI, SplitVRegs); return true; } // Driver for the register assignment and splitting heuristics. // Manages iteration over the LiveIntervalUnions. // // This is a minimal implementation of register assignment and splitting that // spills whenever we run out of registers. // // selectOrSplit can only be called once per live virtual register. We then do a // single interference test for each register the correct class until we find an // available register. So, the number of interference tests in the worst case is // |vregs| * |machineregs|. And since the number of interference tests is // minimal, there is no value in caching them outside the scope of // selectOrSplit(). unsigned RABasic::selectOrSplit(LiveInterval &VirtReg, SmallVectorImpl<LiveInterval*> &SplitVRegs) { // Check for register mask interference. When live ranges cross calls, the // set of usable registers is reduced to the callee-saved ones. bool CrossRegMasks = LIS->checkRegMaskInterference(VirtReg, UsableRegs); // Populate a list of physical register spill candidates. SmallVector<unsigned, 8> PhysRegSpillCands; // Check for an available register in this class. ArrayRef<unsigned> Order = RegClassInfo.getOrder(MRI->getRegClass(VirtReg.reg)); for (ArrayRef<unsigned>::iterator I = Order.begin(), E = Order.end(); I != E; ++I) { unsigned PhysReg = *I; // If PhysReg is clobbered by a register mask, it isn't useful for // allocation or spilling. if (CrossRegMasks && !UsableRegs.test(PhysReg)) continue; // Check interference and as a side effect, intialize queries for this // VirtReg and its aliases. unsigned interfReg = checkPhysRegInterference(VirtReg, PhysReg); if (interfReg == 0) { // Found an available register. return PhysReg; } LiveIntervalUnion::Query &IntfQ = query(VirtReg, interfReg); IntfQ.collectInterferingVRegs(1); LiveInterval *interferingVirtReg = IntfQ.interferingVRegs().front(); // The current VirtReg must either be spillable, or one of its interferences // must have less spill weight. if (interferingVirtReg->weight < VirtReg.weight ) { PhysRegSpillCands.push_back(PhysReg); } } // Try to spill another interfering reg with less spill weight. for (SmallVectorImpl<unsigned>::iterator PhysRegI = PhysRegSpillCands.begin(), PhysRegE = PhysRegSpillCands.end(); PhysRegI != PhysRegE; ++PhysRegI) { if (!spillInterferences(VirtReg, *PhysRegI, SplitVRegs)) continue; assert(checkPhysRegInterference(VirtReg, *PhysRegI) == 0 && "Interference after spill."); // Tell the caller to allocate to this newly freed physical register. return *PhysRegI; } // No other spill candidates were found, so spill the current VirtReg. DEBUG(dbgs() << "spilling: " << VirtReg << '\n'); if (!VirtReg.isSpillable()) return ~0u; LiveRangeEdit LRE(VirtReg, SplitVRegs); spiller().spill(LRE); // The live virtual register requesting allocation was spilled, so tell // the caller not to allocate anything during this round. return 0; } bool RABasic::runOnMachineFunction(MachineFunction &mf) { DEBUG(dbgs() << "********** BASIC REGISTER ALLOCATION **********\n" << "********** Function: " << ((Value*)mf.getFunction())->getName() << '\n'); MF = &mf; DEBUG(RMF = &getAnalysis<RenderMachineFunction>()); RegAllocBase::init(getAnalysis<VirtRegMap>(), getAnalysis<LiveIntervals>()); SpillerInstance.reset(createInlineSpiller(*this, *MF, *VRM)); allocatePhysRegs(); addMBBLiveIns(MF); // Diagnostic output before rewriting DEBUG(dbgs() << "Post alloc VirtRegMap:\n" << *VRM << "\n"); // optional HTML output DEBUG(RMF->renderMachineFunction("After basic register allocation.", VRM)); // FIXME: Verification currently must run before VirtRegRewriter. We should // make the rewriter a separate pass and override verifyAnalysis instead. When // that happens, verification naturally falls under VerifyMachineCode. #ifndef NDEBUG if (VerifyEnabled) { // Verify accuracy of LiveIntervals. The standard machine code verifier // ensures that each LiveIntervals covers all uses of the virtual reg. // FIXME: MachineVerifier is badly broken when using the standard // spiller. Always use -spiller=inline with -verify-regalloc. Even with the // inline spiller, some tests fail to verify because the coalescer does not // always generate verifiable code. MF->verify(this, "In RABasic::verify"); // Verify that LiveIntervals are partitioned into unions and disjoint within // the unions. verify(); } #endif // !NDEBUG // Run rewriter VRM->rewrite(LIS->getSlotIndexes()); // Write out new DBG_VALUE instructions. getAnalysis<LiveDebugVariables>().emitDebugValues(VRM); // The pass output is in VirtRegMap. Release all the transient data. releaseMemory(); return true; } FunctionPass* llvm::createBasicRegisterAllocator() { return new RABasic(); } <|endoftext|>
<commit_before>/************************************************************************* * * $RCSfile: inspagob.cxx,v $ * * $Revision: 1.5 $ * * last change: $Author: obo $ $Date: 2004-01-20 10:45:47 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #pragma hdrstop #include "inspagob.hxx" #include "strings.hrc" #include "res_bmp.hrc" #include "sdresid.hxx" #include "drawdoc.hxx" #include "DrawDocShell.hxx" #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #include "inspagob.hrc" /************************************************************************* |* |* Ctor |* \************************************************************************/ SdInsertPagesObjsDlg::SdInsertPagesObjsDlg( ::Window* pWindow, const SdDrawDocument* pInDoc, SfxMedium* pSfxMedium, const String& rFileName ) : ModalDialog ( pWindow, SdResId( DLG_INSERT_PAGES_OBJS ) ), aLbTree ( this, SdResId( LB_TREE ) ), aBtnOk ( this, SdResId( BTN_OK ) ), aBtnCancel ( this, SdResId( BTN_CANCEL ) ), aBtnHelp ( this, SdResId( BTN_HELP ) ), aCbxLink ( this, SdResId( CBX_LINK ) ), aCbxMasters ( this, SdResId( CBX_CHECK_MASTERS ) ), pDoc ( pInDoc ), pMedium ( pSfxMedium ), rName ( rFileName ) { FreeResource(); aLbTree.SetViewFrame( ( (SdDrawDocument*) pInDoc )->GetDocSh()->GetViewShell()->GetViewFrame() ); aLbTree.SetSelectHdl( LINK( this, SdInsertPagesObjsDlg, SelectObjectHdl ) ); // Text wird eingefuegt if( !pMedium ) SetText( String( SdResId( STR_INSERT_TEXT ) ) ); Reset(); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SdInsertPagesObjsDlg::~SdInsertPagesObjsDlg() { } /************************************************************************* |* |* Fuellt die TreeLB in Abhaengigkeit des Mediums. Ist kein Medium |* vorhanden, handelt es sich um ein Text- und kein Drawdokument |* \************************************************************************/ void SdInsertPagesObjsDlg::Reset() { if( pMedium ) { aLbTree.SetSelectionMode( MULTIPLE_SELECTION ); aLbTree.Fill( pDoc, pMedium, rName ); } else { Color aColor( COL_WHITE ); Bitmap aBmpText( SdResId( BMP_DOC_TEXT ) ); Image aImgText( aBmpText, aColor ); Bitmap aBmpTextH( SdResId( BMP_DOC_TEXT_H ) ); Image aImgTextH( aBmpTextH, Color( COL_BLACK ) ); SvLBoxEntry* pEntry = aLbTree.InsertEntry( rName, aImgText, aImgText ); aLbTree.SetExpandedEntryBmp( pEntry, aImgTextH, BMP_COLOR_HIGHCONTRAST ); aLbTree.SetCollapsedEntryBmp( pEntry, aImgTextH, BMP_COLOR_HIGHCONTRAST ); } aCbxMasters.Check( TRUE ); } /************************************************************************* |* |* Liefert die Liste zurueck |* nType == 0 -> Seiten |* nType == 1 -> Objekte |* \************************************************************************/ List* SdInsertPagesObjsDlg::GetList( USHORT nType ) { // Bei Draw-Dokumenten muss bei der Selektion des Dokumentes NULL // zurueckgegeben werden if( pMedium ) { // Um zu gewaehrleisten, dass die Bookmarks geoeffnet sind // (Wenn gesamtes Dokument ausgewaehlt wurde) aLbTree.GetBookmarkDoc(); // Wenn das Dokument (mit-)selektiert oder nichst selektiert ist, // wird das gesamte Dokument (und nicht mehr!) eingefuegt. if( aLbTree.GetSelectionCount() == 0 || ( aLbTree.IsSelected( aLbTree.First() ) ) ) //return( aLbTree.GetBookmarkList( nType ) ); return( NULL ); // #37350# } return( aLbTree.GetSelectEntryList( nType ) ); } /************************************************************************* |* |* Ist Verknuepfung gechecked |* \************************************************************************/ BOOL SdInsertPagesObjsDlg::IsLink() { return( aCbxLink.IsChecked() ); } /************************************************************************* |* |* Ist Verknuepfung gechecked |* \************************************************************************/ BOOL SdInsertPagesObjsDlg::IsRemoveUnnessesaryMasterPages() const { return( aCbxMasters.IsChecked() ); } /************************************************************************* |* |* Enabled und selektiert Endfarben-LB |* \************************************************************************/ IMPL_LINK( SdInsertPagesObjsDlg, SelectObjectHdl, void *, p ) { if( aLbTree.IsLinkableSelected() ) aCbxLink.Enable(); else aCbxLink.Disable(); return( 0 ); } <commit_msg>INTEGRATION: CWS tune03 (1.5.186); FILE MERGED 2004/08/08 12:54:06 mhu 1.5.186.1: #i29979# Added SD_DLLPUBLIC/PRIVATE (see sddllapi.h) to exported symbols/classes.<commit_after>/************************************************************************* * * $RCSfile: inspagob.cxx,v $ * * $Revision: 1.6 $ * * last change: $Author: rt $ $Date: 2004-08-23 08:16:45 $ * * The Contents of this file are made available subject to the terms of * either of the following licenses * * - GNU Lesser General Public License Version 2.1 * - Sun Industry Standards Source License Version 1.1 * * Sun Microsystems Inc., October, 2000 * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2000 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * * * Sun Industry Standards Source License Version 1.1 * ================================================= * The contents of this file are subject to the Sun Industry Standards * Source License Version 1.1 (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.openoffice.org/license.html. * * Software provided under this License is provided on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, * WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS, * MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING. * See the License for the specific provisions governing your rights and * obligations concerning the Software. * * The Initial Developer of the Original Code is: Sun Microsystems, Inc. * * Copyright: 2000 by Sun Microsystems, Inc. * * All Rights Reserved. * * Contributor(s): _______________________________________ * * ************************************************************************/ #ifdef SD_DLLIMPLEMENTATION #undef SD_DLLIMPLEMENTATION #endif #pragma hdrstop #include "inspagob.hxx" #include "strings.hrc" #include "res_bmp.hrc" #include "sdresid.hxx" #include "drawdoc.hxx" #include "DrawDocShell.hxx" #ifndef SD_VIEW_SHELL_HXX #include "ViewShell.hxx" #endif #include "inspagob.hrc" /************************************************************************* |* |* Ctor |* \************************************************************************/ SdInsertPagesObjsDlg::SdInsertPagesObjsDlg( ::Window* pWindow, const SdDrawDocument* pInDoc, SfxMedium* pSfxMedium, const String& rFileName ) : ModalDialog ( pWindow, SdResId( DLG_INSERT_PAGES_OBJS ) ), aLbTree ( this, SdResId( LB_TREE ) ), aBtnOk ( this, SdResId( BTN_OK ) ), aBtnCancel ( this, SdResId( BTN_CANCEL ) ), aBtnHelp ( this, SdResId( BTN_HELP ) ), aCbxLink ( this, SdResId( CBX_LINK ) ), aCbxMasters ( this, SdResId( CBX_CHECK_MASTERS ) ), pDoc ( pInDoc ), pMedium ( pSfxMedium ), rName ( rFileName ) { FreeResource(); aLbTree.SetViewFrame( ( (SdDrawDocument*) pInDoc )->GetDocSh()->GetViewShell()->GetViewFrame() ); aLbTree.SetSelectHdl( LINK( this, SdInsertPagesObjsDlg, SelectObjectHdl ) ); // Text wird eingefuegt if( !pMedium ) SetText( String( SdResId( STR_INSERT_TEXT ) ) ); Reset(); } /************************************************************************* |* |* Dtor |* \************************************************************************/ SdInsertPagesObjsDlg::~SdInsertPagesObjsDlg() { } /************************************************************************* |* |* Fuellt die TreeLB in Abhaengigkeit des Mediums. Ist kein Medium |* vorhanden, handelt es sich um ein Text- und kein Drawdokument |* \************************************************************************/ void SdInsertPagesObjsDlg::Reset() { if( pMedium ) { aLbTree.SetSelectionMode( MULTIPLE_SELECTION ); aLbTree.Fill( pDoc, pMedium, rName ); } else { Color aColor( COL_WHITE ); Bitmap aBmpText( SdResId( BMP_DOC_TEXT ) ); Image aImgText( aBmpText, aColor ); Bitmap aBmpTextH( SdResId( BMP_DOC_TEXT_H ) ); Image aImgTextH( aBmpTextH, Color( COL_BLACK ) ); SvLBoxEntry* pEntry = aLbTree.InsertEntry( rName, aImgText, aImgText ); aLbTree.SetExpandedEntryBmp( pEntry, aImgTextH, BMP_COLOR_HIGHCONTRAST ); aLbTree.SetCollapsedEntryBmp( pEntry, aImgTextH, BMP_COLOR_HIGHCONTRAST ); } aCbxMasters.Check( TRUE ); } /************************************************************************* |* |* Liefert die Liste zurueck |* nType == 0 -> Seiten |* nType == 1 -> Objekte |* \************************************************************************/ List* SdInsertPagesObjsDlg::GetList( USHORT nType ) { // Bei Draw-Dokumenten muss bei der Selektion des Dokumentes NULL // zurueckgegeben werden if( pMedium ) { // Um zu gewaehrleisten, dass die Bookmarks geoeffnet sind // (Wenn gesamtes Dokument ausgewaehlt wurde) aLbTree.GetBookmarkDoc(); // Wenn das Dokument (mit-)selektiert oder nichst selektiert ist, // wird das gesamte Dokument (und nicht mehr!) eingefuegt. if( aLbTree.GetSelectionCount() == 0 || ( aLbTree.IsSelected( aLbTree.First() ) ) ) //return( aLbTree.GetBookmarkList( nType ) ); return( NULL ); // #37350# } return( aLbTree.GetSelectEntryList( nType ) ); } /************************************************************************* |* |* Ist Verknuepfung gechecked |* \************************************************************************/ BOOL SdInsertPagesObjsDlg::IsLink() { return( aCbxLink.IsChecked() ); } /************************************************************************* |* |* Ist Verknuepfung gechecked |* \************************************************************************/ BOOL SdInsertPagesObjsDlg::IsRemoveUnnessesaryMasterPages() const { return( aCbxMasters.IsChecked() ); } /************************************************************************* |* |* Enabled und selektiert Endfarben-LB |* \************************************************************************/ IMPL_LINK( SdInsertPagesObjsDlg, SelectObjectHdl, void *, p ) { if( aLbTree.IsLinkableSelected() ) aCbxLink.Enable(); else aCbxLink.Disable(); return( 0 ); } <|endoftext|>
<commit_before>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlgctrls.hxx,v $ * * $Revision: 1.5 $ * * last change: $Author: rt $ $Date: 2005-09-09 05:25:51 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_DLGCTRLS_HXX #define SD_DLGCTRLS_HXX #ifndef _SD_TRANSITIONPRESET_HXX #include "TransitionPreset.hxx" #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _SD_SDRESID_HXX #include "sdresid.hxx" #endif #ifndef _SD_FADEDEF_H #include "fadedef.h" #endif #ifndef INCLUDED_SDDLLAPI_H #include "sddllapi.h" #endif /************************************************************************* |* |* FadeEffectLB |* \************************************************************************/ struct FadeEffectLBImpl; class SD_DLLPUBLIC FadeEffectLB : public ListBox { public: FadeEffectLB( Window* pParent, SdResId Id ); FadeEffectLB( Window* pParent, WinBits aWB ); ~FadeEffectLB(); virtual void Fill(); /* void selectEffectFromPage( SdPage* pPage ); */ void applySelected( SdPage* pSlide ) const; private: USHORT GetSelectEntryPos() const { return ListBox::GetSelectEntryPos(); } void SelectEntryPos( USHORT nPos ) { ListBox::SelectEntryPos( nPos ); } FadeEffectLBImpl* mpImpl; }; #endif // SD_DLGCTRLS_HXX <commit_msg>INTEGRATION: CWS sdwarningsbegone (1.5.316); FILE MERGED 2006/11/27 13:48:07 cl 1.5.316.1: #i69285# warning free code changes for sd project<commit_after>/************************************************************************* * * OpenOffice.org - a multi-platform office productivity suite * * $RCSfile: dlgctrls.hxx,v $ * * $Revision: 1.6 $ * * last change: $Author: kz $ $Date: 2006-12-12 17:42:14 $ * * The Contents of this file are made available subject to * the terms of GNU Lesser General Public License Version 2.1. * * * GNU Lesser General Public License Version 2.1 * ============================================= * Copyright 2005 by Sun Microsystems, Inc. * 901 San Antonio Road, Palo Alto, CA 94303, USA * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License version 2.1, as published by the Free Software Foundation. * * 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., 59 Temple Place, Suite 330, Boston, * MA 02111-1307 USA * ************************************************************************/ #ifndef SD_DLGCTRLS_HXX #define SD_DLGCTRLS_HXX #ifndef _SD_TRANSITIONPRESET_HXX #include "TransitionPreset.hxx" #endif #ifndef _SV_LSTBOX_HXX //autogen #include <vcl/lstbox.hxx> #endif #ifndef _SD_SDRESID_HXX #include "sdresid.hxx" #endif #ifndef _SD_FADEDEF_H #include "fadedef.h" #endif #ifndef INCLUDED_SDDLLAPI_H #include "sddllapi.h" #endif /************************************************************************* |* |* FadeEffectLB |* \************************************************************************/ struct FadeEffectLBImpl; class SD_DLLPUBLIC FadeEffectLB : public ListBox { public: FadeEffectLB( Window* pParent, SdResId Id ); FadeEffectLB( Window* pParent, WinBits aWB ); ~FadeEffectLB(); virtual void Fill(); /* void selectEffectFromPage( SdPage* pPage ); */ void applySelected( SdPage* pSlide ) const; FadeEffectLBImpl* mpImpl; }; #endif // SD_DLGCTRLS_HXX <|endoftext|>
<commit_before>//===--- BreakableToken.cpp - Format C++ code -----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Contains implementation of BreakableToken class and classes derived /// from it. /// //===----------------------------------------------------------------------===// #define DEBUG_TYPE "format-token-breaker" #include "BreakableToken.h" #include "clang/Basic/CharInfo.h" #include "clang/Format/Format.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include <algorithm> namespace clang { namespace format { namespace { static const char *Blanks = " \t\v\f"; static bool IsBlank(char C) { switch (C) { case ' ': case '\t': case '\v': case '\f': return true; default: return false; } } BreakableToken::Split getCommentSplit(StringRef Text, unsigned ContentStartColumn, unsigned ColumnLimit, encoding::Encoding Encoding) { if (ColumnLimit <= ContentStartColumn + 1) return BreakableToken::Split(StringRef::npos, 0); unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1; unsigned MaxSplitBytes = 0; for (unsigned NumChars = 0; NumChars < MaxSplit && MaxSplitBytes < Text.size(); ++NumChars) MaxSplitBytes += encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding); StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes); if (SpaceOffset == StringRef::npos || // Don't break at leading whitespace. Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) { // Make sure that we don't break at leading whitespace that // reaches past MaxSplit. StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks); if (FirstNonWhitespace == StringRef::npos) // If the comment is only whitespace, we cannot split. return BreakableToken::Split(StringRef::npos, 0); SpaceOffset = Text.find_first_of( Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace)); } if (SpaceOffset != StringRef::npos && SpaceOffset != 0) { StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks); StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks); return BreakableToken::Split(BeforeCut.size(), AfterCut.begin() - BeforeCut.end()); } return BreakableToken::Split(StringRef::npos, 0); } BreakableToken::Split getStringSplit(StringRef Text, unsigned ContentStartColumn, unsigned ColumnLimit, encoding::Encoding Encoding) { // FIXME: Reduce unit test case. if (Text.empty()) return BreakableToken::Split(StringRef::npos, 0); if (ColumnLimit <= ContentStartColumn) return BreakableToken::Split(StringRef::npos, 0); unsigned MaxSplit = std::min<unsigned>(ColumnLimit - ContentStartColumn, encoding::getCodePointCount(Text, Encoding) - 1); StringRef::size_type SpaceOffset = 0; StringRef::size_type SlashOffset = 0; StringRef::size_type WordStartOffset = 0; StringRef::size_type SplitPoint = 0; for (unsigned Chars = 0;;) { unsigned Advance; if (Text[0] == '\\') { Advance = encoding::getEscapeSequenceLength(Text); Chars += Advance; } else { Advance = encoding::getCodePointNumBytes(Text[0], Encoding); Chars += 1; } if (Chars > MaxSplit) break; if (IsBlank(Text[0])) SpaceOffset = SplitPoint; if (Text[0] == '/') SlashOffset = SplitPoint; if (Advance == 1 && !isAlphanumeric(Text[0])) WordStartOffset = SplitPoint; SplitPoint += Advance; Text = Text.substr(Advance); } if (SpaceOffset != 0) return BreakableToken::Split(SpaceOffset + 1, 0); if (SlashOffset != 0) return BreakableToken::Split(SlashOffset + 1, 0); if (WordStartOffset != 0) return BreakableToken::Split(WordStartOffset + 1, 0); if (SplitPoint != 0) return BreakableToken::Split(SplitPoint, 0); return BreakableToken::Split(StringRef::npos, 0); } } // namespace unsigned BreakableSingleLineToken::getLineCount() const { return 1; } unsigned BreakableSingleLineToken::getLineLengthAfterSplit( unsigned LineIndex, unsigned Offset, StringRef::size_type Length) const { return StartColumn + Prefix.size() + Postfix.size() + encoding::getCodePointCount(Line.substr(Offset, Length), Encoding); } BreakableSingleLineToken::BreakableSingleLineToken( const FormatToken &Tok, unsigned StartColumn, StringRef Prefix, StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding) : BreakableToken(Tok, InPPDirective, Encoding), StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix) { assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix)); Line = Tok.TokenText.substr( Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size()); } BreakableStringLiteral::BreakableStringLiteral(const FormatToken &Tok, unsigned StartColumn, bool InPPDirective, encoding::Encoding Encoding) : BreakableSingleLineToken(Tok, StartColumn, "\"", "\"", InPPDirective, Encoding) {} BreakableToken::Split BreakableStringLiteral::getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit) const { return getStringSplit(Line.substr(TailOffset), StartColumn + 2, ColumnLimit, Encoding); } void BreakableStringLiteral::insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) { Whitespaces.replaceWhitespaceInToken( Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix, Prefix, InPPDirective, 1, StartColumn); } static StringRef getLineCommentPrefix(StringRef Comment) { const char *KnownPrefixes[] = { "/// ", "///", "// ", "//" }; for (size_t i = 0, e = llvm::array_lengthof(KnownPrefixes); i != e; ++i) if (Comment.startswith(KnownPrefixes[i])) return KnownPrefixes[i]; return ""; } BreakableLineComment::BreakableLineComment(const FormatToken &Token, unsigned StartColumn, bool InPPDirective, encoding::Encoding Encoding) : BreakableSingleLineToken(Token, StartColumn, getLineCommentPrefix(Token.TokenText), "", InPPDirective, Encoding) { OriginalPrefix = Prefix; if (Token.TokenText.size() > Prefix.size() && isAlphanumeric(Token.TokenText[Prefix.size()])) { if (Prefix == "//") Prefix = "// "; else if (Prefix == "///") Prefix = "/// "; } } BreakableToken::Split BreakableLineComment::getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit) const { return getCommentSplit(Line.substr(TailOffset), StartColumn + Prefix.size(), ColumnLimit, Encoding); } void BreakableLineComment::insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) { Whitespaces.replaceWhitespaceInToken( Tok, OriginalPrefix.size() + TailOffset + Split.first, Split.second, Postfix, Prefix, InPPDirective, 1, StartColumn); } void BreakableLineComment::replaceWhitespaceBefore(unsigned LineIndex, WhitespaceManager &Whitespaces) { if (OriginalPrefix != Prefix) { Whitespaces.replaceWhitespaceInToken(Tok, OriginalPrefix.size(), 0, "", "", false, 0, 1); } } BreakableBlockComment::BreakableBlockComment( const FormatStyle &Style, const FormatToken &Token, unsigned StartColumn, unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective, encoding::Encoding Encoding) : BreakableToken(Token, InPPDirective, Encoding) { StringRef TokenText(Token.TokenText); assert(TokenText.startswith("/*") && TokenText.endswith("*/")); TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n"); int IndentDelta = StartColumn - OriginalStartColumn; bool NeedsStar = true; LeadingWhitespace.resize(Lines.size()); StartOfLineColumn.resize(Lines.size()); if (Lines.size() == 1 && !FirstInLine) { // Comments for which FirstInLine is false can start on arbitrary column, // and available horizontal space can be too small to align consecutive // lines with the first one. // FIXME: We could, probably, align them to current indentation level, but // now we just wrap them without stars. NeedsStar = false; } StartOfLineColumn[0] = StartColumn + 2; for (size_t i = 1; i < Lines.size(); ++i) { adjustWhitespace(Style, i, IndentDelta); if (Lines[i].empty()) // If the last line is empty, the closing "*/" will have a star. NeedsStar = NeedsStar && i + 1 == Lines.size(); else NeedsStar = NeedsStar && Lines[i][0] == '*'; } Decoration = NeedsStar ? "* " : ""; IndentAtLineBreak = StartOfLineColumn[0] + 1; for (size_t i = 1; i < Lines.size(); ++i) { if (Lines[i].empty()) { if (!NeedsStar && i + 1 != Lines.size()) // For all but the last line (which always ends in */), set the // start column to 0 if they're empty, so we do not insert // trailing whitespace anywhere. StartOfLineColumn[i] = 0; continue; } if (NeedsStar) { // The first line already excludes the star. // For all other lines, adjust the line to exclude the star and // (optionally) the first whitespace. int Offset = Lines[i].startswith("* ") ? 2 : 1; StartOfLineColumn[i] += Offset; Lines[i] = Lines[i].substr(Offset); LeadingWhitespace[i] += Offset; } IndentAtLineBreak = std::min<int>(IndentAtLineBreak, StartOfLineColumn[i]); } IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size()); DEBUG({ for (size_t i = 0; i < Lines.size(); ++i) { llvm::dbgs() << i << " |" << Lines[i] << "| " << LeadingWhitespace[i] << "\n"; } }); } void BreakableBlockComment::adjustWhitespace(const FormatStyle &Style, unsigned LineIndex, int IndentDelta) { // When in a preprocessor directive, the trailing backslash in a block comment // is not needed, but can serve a purpose of uniformity with necessary escaped // newlines outside the comment. In this case we remove it here before // trimming the trailing whitespace. The backslash will be re-added later when // inserting a line break. size_t EndOfPreviousLine = Lines[LineIndex - 1].size(); if (InPPDirective && Lines[LineIndex - 1].endswith("\\")) --EndOfPreviousLine; // Calculate the end of the non-whitespace text in the previous line. EndOfPreviousLine = Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine); if (EndOfPreviousLine == StringRef::npos) EndOfPreviousLine = 0; else ++EndOfPreviousLine; // Calculate the start of the non-whitespace text in the current line. size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks); if (StartOfLine == StringRef::npos) StartOfLine = Lines[LineIndex].size(); // Adjust Lines to only contain relevant text. Lines[LineIndex - 1] = Lines[LineIndex - 1].substr(0, EndOfPreviousLine); Lines[LineIndex] = Lines[LineIndex].substr(StartOfLine); // Adjust LeadingWhitespace to account all whitespace between the lines // to the current line. LeadingWhitespace[LineIndex] = Lines[LineIndex].begin() - Lines[LineIndex - 1].end(); // FIXME: We currently count tabs as 1 character. To solve this, we need to // get the correct indentation width of the start of the comment, which // requires correct counting of the tab expansions before the comment, and // a configurable tab width. Since the current implementation only breaks // if leading tabs are intermixed with spaces, that is not a high priority. // Adjust the start column uniformly accross all lines. StartOfLineColumn[LineIndex] = std::max<int>(0, StartOfLine + IndentDelta); } unsigned BreakableBlockComment::getLineCount() const { return Lines.size(); } unsigned BreakableBlockComment::getLineLengthAfterSplit( unsigned LineIndex, unsigned Offset, StringRef::size_type Length) const { return getContentStartColumn(LineIndex, Offset) + encoding::getCodePointCount(Lines[LineIndex].substr(Offset, Length), Encoding) + // The last line gets a "*/" postfix. (LineIndex + 1 == Lines.size() ? 2 : 0); } BreakableToken::Split BreakableBlockComment::getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit) const { return getCommentSplit(Lines[LineIndex].substr(TailOffset), getContentStartColumn(LineIndex, TailOffset), ColumnLimit, Encoding); } void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) { StringRef Text = Lines[LineIndex].substr(TailOffset); StringRef Prefix = Decoration; if (LineIndex + 1 == Lines.size() && Text.size() == Split.first + Split.second) { // For the last line we need to break before "*/", but not to add "* ". Prefix = ""; } unsigned BreakOffsetInToken = Text.data() - Tok.TokenText.data() + Split.first; unsigned CharsToRemove = Split.second; assert(IndentAtLineBreak >= Decoration.size()); Whitespaces.replaceWhitespaceInToken(Tok, BreakOffsetInToken, CharsToRemove, "", Prefix, InPPDirective, 1, IndentAtLineBreak - Decoration.size()); } void BreakableBlockComment::replaceWhitespaceBefore(unsigned LineIndex, WhitespaceManager &Whitespaces) { if (LineIndex == 0) return; StringRef Prefix = Decoration; if (Lines[LineIndex].empty()) { if (LineIndex + 1 == Lines.size()) { // If the last line is empty, we don't need a prefix, as the */ will line // up with the decoration (if it exists). Prefix = ""; } else if (!Decoration.empty()) { // For other empty lines, if we do have a decoration, adapt it to not // contain a trailing whitespace. Prefix = Prefix.substr(0, 1); } } else { if (StartOfLineColumn[LineIndex] == 1) { // This lines starts immediately after the decorating *. Prefix = Prefix.substr(0, 1); } } unsigned WhitespaceOffsetInToken = Lines[LineIndex].data() - Tok.TokenText.data() - LeadingWhitespace[LineIndex]; assert(StartOfLineColumn[LineIndex] >= Prefix.size()); Whitespaces.replaceWhitespaceInToken( Tok, WhitespaceOffsetInToken, LeadingWhitespace[LineIndex], "", Prefix, InPPDirective, 1, StartOfLineColumn[LineIndex] - Prefix.size()); } unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex, unsigned TailOffset) const { // If we break, we always break at the predefined indent. if (TailOffset != 0) return IndentAtLineBreak; return StartOfLineColumn[LineIndex]; } } // namespace format } // namespace clang <commit_msg>Make string pointer const.<commit_after>//===--- BreakableToken.cpp - Format C++ code -----------------------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// /// /// \file /// \brief Contains implementation of BreakableToken class and classes derived /// from it. /// //===----------------------------------------------------------------------===// #define DEBUG_TYPE "format-token-breaker" #include "BreakableToken.h" #include "clang/Basic/CharInfo.h" #include "clang/Format/Format.h" #include "llvm/ADT/STLExtras.h" #include "llvm/Support/Debug.h" #include <algorithm> namespace clang { namespace format { namespace { static const char *const Blanks = " \t\v\f"; static bool IsBlank(char C) { switch (C) { case ' ': case '\t': case '\v': case '\f': return true; default: return false; } } BreakableToken::Split getCommentSplit(StringRef Text, unsigned ContentStartColumn, unsigned ColumnLimit, encoding::Encoding Encoding) { if (ColumnLimit <= ContentStartColumn + 1) return BreakableToken::Split(StringRef::npos, 0); unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1; unsigned MaxSplitBytes = 0; for (unsigned NumChars = 0; NumChars < MaxSplit && MaxSplitBytes < Text.size(); ++NumChars) MaxSplitBytes += encoding::getCodePointNumBytes(Text[MaxSplitBytes], Encoding); StringRef::size_type SpaceOffset = Text.find_last_of(Blanks, MaxSplitBytes); if (SpaceOffset == StringRef::npos || // Don't break at leading whitespace. Text.find_last_not_of(Blanks, SpaceOffset) == StringRef::npos) { // Make sure that we don't break at leading whitespace that // reaches past MaxSplit. StringRef::size_type FirstNonWhitespace = Text.find_first_not_of(Blanks); if (FirstNonWhitespace == StringRef::npos) // If the comment is only whitespace, we cannot split. return BreakableToken::Split(StringRef::npos, 0); SpaceOffset = Text.find_first_of( Blanks, std::max<unsigned>(MaxSplitBytes, FirstNonWhitespace)); } if (SpaceOffset != StringRef::npos && SpaceOffset != 0) { StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim(Blanks); StringRef AfterCut = Text.substr(SpaceOffset).ltrim(Blanks); return BreakableToken::Split(BeforeCut.size(), AfterCut.begin() - BeforeCut.end()); } return BreakableToken::Split(StringRef::npos, 0); } BreakableToken::Split getStringSplit(StringRef Text, unsigned ContentStartColumn, unsigned ColumnLimit, encoding::Encoding Encoding) { // FIXME: Reduce unit test case. if (Text.empty()) return BreakableToken::Split(StringRef::npos, 0); if (ColumnLimit <= ContentStartColumn) return BreakableToken::Split(StringRef::npos, 0); unsigned MaxSplit = std::min<unsigned>(ColumnLimit - ContentStartColumn, encoding::getCodePointCount(Text, Encoding) - 1); StringRef::size_type SpaceOffset = 0; StringRef::size_type SlashOffset = 0; StringRef::size_type WordStartOffset = 0; StringRef::size_type SplitPoint = 0; for (unsigned Chars = 0;;) { unsigned Advance; if (Text[0] == '\\') { Advance = encoding::getEscapeSequenceLength(Text); Chars += Advance; } else { Advance = encoding::getCodePointNumBytes(Text[0], Encoding); Chars += 1; } if (Chars > MaxSplit) break; if (IsBlank(Text[0])) SpaceOffset = SplitPoint; if (Text[0] == '/') SlashOffset = SplitPoint; if (Advance == 1 && !isAlphanumeric(Text[0])) WordStartOffset = SplitPoint; SplitPoint += Advance; Text = Text.substr(Advance); } if (SpaceOffset != 0) return BreakableToken::Split(SpaceOffset + 1, 0); if (SlashOffset != 0) return BreakableToken::Split(SlashOffset + 1, 0); if (WordStartOffset != 0) return BreakableToken::Split(WordStartOffset + 1, 0); if (SplitPoint != 0) return BreakableToken::Split(SplitPoint, 0); return BreakableToken::Split(StringRef::npos, 0); } } // namespace unsigned BreakableSingleLineToken::getLineCount() const { return 1; } unsigned BreakableSingleLineToken::getLineLengthAfterSplit( unsigned LineIndex, unsigned Offset, StringRef::size_type Length) const { return StartColumn + Prefix.size() + Postfix.size() + encoding::getCodePointCount(Line.substr(Offset, Length), Encoding); } BreakableSingleLineToken::BreakableSingleLineToken( const FormatToken &Tok, unsigned StartColumn, StringRef Prefix, StringRef Postfix, bool InPPDirective, encoding::Encoding Encoding) : BreakableToken(Tok, InPPDirective, Encoding), StartColumn(StartColumn), Prefix(Prefix), Postfix(Postfix) { assert(Tok.TokenText.startswith(Prefix) && Tok.TokenText.endswith(Postfix)); Line = Tok.TokenText.substr( Prefix.size(), Tok.TokenText.size() - Prefix.size() - Postfix.size()); } BreakableStringLiteral::BreakableStringLiteral(const FormatToken &Tok, unsigned StartColumn, bool InPPDirective, encoding::Encoding Encoding) : BreakableSingleLineToken(Tok, StartColumn, "\"", "\"", InPPDirective, Encoding) {} BreakableToken::Split BreakableStringLiteral::getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit) const { return getStringSplit(Line.substr(TailOffset), StartColumn + 2, ColumnLimit, Encoding); } void BreakableStringLiteral::insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) { Whitespaces.replaceWhitespaceInToken( Tok, Prefix.size() + TailOffset + Split.first, Split.second, Postfix, Prefix, InPPDirective, 1, StartColumn); } static StringRef getLineCommentPrefix(StringRef Comment) { const char *KnownPrefixes[] = { "/// ", "///", "// ", "//" }; for (size_t i = 0, e = llvm::array_lengthof(KnownPrefixes); i != e; ++i) if (Comment.startswith(KnownPrefixes[i])) return KnownPrefixes[i]; return ""; } BreakableLineComment::BreakableLineComment(const FormatToken &Token, unsigned StartColumn, bool InPPDirective, encoding::Encoding Encoding) : BreakableSingleLineToken(Token, StartColumn, getLineCommentPrefix(Token.TokenText), "", InPPDirective, Encoding) { OriginalPrefix = Prefix; if (Token.TokenText.size() > Prefix.size() && isAlphanumeric(Token.TokenText[Prefix.size()])) { if (Prefix == "//") Prefix = "// "; else if (Prefix == "///") Prefix = "/// "; } } BreakableToken::Split BreakableLineComment::getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit) const { return getCommentSplit(Line.substr(TailOffset), StartColumn + Prefix.size(), ColumnLimit, Encoding); } void BreakableLineComment::insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) { Whitespaces.replaceWhitespaceInToken( Tok, OriginalPrefix.size() + TailOffset + Split.first, Split.second, Postfix, Prefix, InPPDirective, 1, StartColumn); } void BreakableLineComment::replaceWhitespaceBefore(unsigned LineIndex, WhitespaceManager &Whitespaces) { if (OriginalPrefix != Prefix) { Whitespaces.replaceWhitespaceInToken(Tok, OriginalPrefix.size(), 0, "", "", false, 0, 1); } } BreakableBlockComment::BreakableBlockComment( const FormatStyle &Style, const FormatToken &Token, unsigned StartColumn, unsigned OriginalStartColumn, bool FirstInLine, bool InPPDirective, encoding::Encoding Encoding) : BreakableToken(Token, InPPDirective, Encoding) { StringRef TokenText(Token.TokenText); assert(TokenText.startswith("/*") && TokenText.endswith("*/")); TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n"); int IndentDelta = StartColumn - OriginalStartColumn; bool NeedsStar = true; LeadingWhitespace.resize(Lines.size()); StartOfLineColumn.resize(Lines.size()); if (Lines.size() == 1 && !FirstInLine) { // Comments for which FirstInLine is false can start on arbitrary column, // and available horizontal space can be too small to align consecutive // lines with the first one. // FIXME: We could, probably, align them to current indentation level, but // now we just wrap them without stars. NeedsStar = false; } StartOfLineColumn[0] = StartColumn + 2; for (size_t i = 1; i < Lines.size(); ++i) { adjustWhitespace(Style, i, IndentDelta); if (Lines[i].empty()) // If the last line is empty, the closing "*/" will have a star. NeedsStar = NeedsStar && i + 1 == Lines.size(); else NeedsStar = NeedsStar && Lines[i][0] == '*'; } Decoration = NeedsStar ? "* " : ""; IndentAtLineBreak = StartOfLineColumn[0] + 1; for (size_t i = 1; i < Lines.size(); ++i) { if (Lines[i].empty()) { if (!NeedsStar && i + 1 != Lines.size()) // For all but the last line (which always ends in */), set the // start column to 0 if they're empty, so we do not insert // trailing whitespace anywhere. StartOfLineColumn[i] = 0; continue; } if (NeedsStar) { // The first line already excludes the star. // For all other lines, adjust the line to exclude the star and // (optionally) the first whitespace. int Offset = Lines[i].startswith("* ") ? 2 : 1; StartOfLineColumn[i] += Offset; Lines[i] = Lines[i].substr(Offset); LeadingWhitespace[i] += Offset; } IndentAtLineBreak = std::min<int>(IndentAtLineBreak, StartOfLineColumn[i]); } IndentAtLineBreak = std::max<unsigned>(IndentAtLineBreak, Decoration.size()); DEBUG({ for (size_t i = 0; i < Lines.size(); ++i) { llvm::dbgs() << i << " |" << Lines[i] << "| " << LeadingWhitespace[i] << "\n"; } }); } void BreakableBlockComment::adjustWhitespace(const FormatStyle &Style, unsigned LineIndex, int IndentDelta) { // When in a preprocessor directive, the trailing backslash in a block comment // is not needed, but can serve a purpose of uniformity with necessary escaped // newlines outside the comment. In this case we remove it here before // trimming the trailing whitespace. The backslash will be re-added later when // inserting a line break. size_t EndOfPreviousLine = Lines[LineIndex - 1].size(); if (InPPDirective && Lines[LineIndex - 1].endswith("\\")) --EndOfPreviousLine; // Calculate the end of the non-whitespace text in the previous line. EndOfPreviousLine = Lines[LineIndex - 1].find_last_not_of(Blanks, EndOfPreviousLine); if (EndOfPreviousLine == StringRef::npos) EndOfPreviousLine = 0; else ++EndOfPreviousLine; // Calculate the start of the non-whitespace text in the current line. size_t StartOfLine = Lines[LineIndex].find_first_not_of(Blanks); if (StartOfLine == StringRef::npos) StartOfLine = Lines[LineIndex].size(); // Adjust Lines to only contain relevant text. Lines[LineIndex - 1] = Lines[LineIndex - 1].substr(0, EndOfPreviousLine); Lines[LineIndex] = Lines[LineIndex].substr(StartOfLine); // Adjust LeadingWhitespace to account all whitespace between the lines // to the current line. LeadingWhitespace[LineIndex] = Lines[LineIndex].begin() - Lines[LineIndex - 1].end(); // FIXME: We currently count tabs as 1 character. To solve this, we need to // get the correct indentation width of the start of the comment, which // requires correct counting of the tab expansions before the comment, and // a configurable tab width. Since the current implementation only breaks // if leading tabs are intermixed with spaces, that is not a high priority. // Adjust the start column uniformly accross all lines. StartOfLineColumn[LineIndex] = std::max<int>(0, StartOfLine + IndentDelta); } unsigned BreakableBlockComment::getLineCount() const { return Lines.size(); } unsigned BreakableBlockComment::getLineLengthAfterSplit( unsigned LineIndex, unsigned Offset, StringRef::size_type Length) const { return getContentStartColumn(LineIndex, Offset) + encoding::getCodePointCount(Lines[LineIndex].substr(Offset, Length), Encoding) + // The last line gets a "*/" postfix. (LineIndex + 1 == Lines.size() ? 2 : 0); } BreakableToken::Split BreakableBlockComment::getSplit(unsigned LineIndex, unsigned TailOffset, unsigned ColumnLimit) const { return getCommentSplit(Lines[LineIndex].substr(TailOffset), getContentStartColumn(LineIndex, TailOffset), ColumnLimit, Encoding); } void BreakableBlockComment::insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split, WhitespaceManager &Whitespaces) { StringRef Text = Lines[LineIndex].substr(TailOffset); StringRef Prefix = Decoration; if (LineIndex + 1 == Lines.size() && Text.size() == Split.first + Split.second) { // For the last line we need to break before "*/", but not to add "* ". Prefix = ""; } unsigned BreakOffsetInToken = Text.data() - Tok.TokenText.data() + Split.first; unsigned CharsToRemove = Split.second; assert(IndentAtLineBreak >= Decoration.size()); Whitespaces.replaceWhitespaceInToken(Tok, BreakOffsetInToken, CharsToRemove, "", Prefix, InPPDirective, 1, IndentAtLineBreak - Decoration.size()); } void BreakableBlockComment::replaceWhitespaceBefore(unsigned LineIndex, WhitespaceManager &Whitespaces) { if (LineIndex == 0) return; StringRef Prefix = Decoration; if (Lines[LineIndex].empty()) { if (LineIndex + 1 == Lines.size()) { // If the last line is empty, we don't need a prefix, as the */ will line // up with the decoration (if it exists). Prefix = ""; } else if (!Decoration.empty()) { // For other empty lines, if we do have a decoration, adapt it to not // contain a trailing whitespace. Prefix = Prefix.substr(0, 1); } } else { if (StartOfLineColumn[LineIndex] == 1) { // This lines starts immediately after the decorating *. Prefix = Prefix.substr(0, 1); } } unsigned WhitespaceOffsetInToken = Lines[LineIndex].data() - Tok.TokenText.data() - LeadingWhitespace[LineIndex]; assert(StartOfLineColumn[LineIndex] >= Prefix.size()); Whitespaces.replaceWhitespaceInToken( Tok, WhitespaceOffsetInToken, LeadingWhitespace[LineIndex], "", Prefix, InPPDirective, 1, StartOfLineColumn[LineIndex] - Prefix.size()); } unsigned BreakableBlockComment::getContentStartColumn(unsigned LineIndex, unsigned TailOffset) const { // If we break, we always break at the predefined indent. if (TailOffset != 0) return IndentAtLineBreak; return StartOfLineColumn[LineIndex]; } } // namespace format } // namespace clang <|endoftext|>
<commit_before>/* Copyright (c) 2015, Embedded Adventures All rights reserved. Contact us at source [at] embeddedadventures.com www.embeddedadventures.com 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 Embedded Adventures 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. */ // Test sketch for MOD1023 // Communicating with the BME280 weather multi-sensor and the indoor air quality sensor #include <BME280_MOD-1022.h> #include <iAQ-MOD1023.h> #include <Wire.h> int ledPin = 13; int inPin = 7; int val = 0; bool event = false; unsigned int counter = 0; void setup() { pinMode(ledPin, OUTPUT); pinMode(inPin, INPUT); Serial.begin(115200); Wire.begin(); uns8 chipID = BME280.readChipId(); bme280_forcedSample(); } void loop() { val = digitalRead(inPin); if (val == HIGH && event == false) { event = true; Serial.print("{'event':'button_pressed'}"); Serial.println(); digitalWrite(ledPin, HIGH); } if ( counter % 2000 == 0 ) { if (event) { digitalWrite(ledPin, LOW); event = false; } } if (counter % 5000 == 0) { iaqUpdate(); bme280_indoorSample(); } delay(1); counter++; } //Update and print data from iAQ void iaqUpdate() { String status; int pred, ohm, tvoc; iaq.readRegisters(); status = iaq.getStatus(); pred = iaq.getPrediction(); ohm = iaq.getResistance(); tvoc = iaq.getTVOC(); Serial.print("{"); Serial.print("'event':'measurement'"); Serial.print(","); Serial.print("'sensor':'iAQ'"); Serial.print(","); Serial.print("'status':'"); Serial.print(status); Serial.print("',"); Serial.print("'pred':"); Serial.print(pred); Serial.print(","); Serial.print("'ohm':"); Serial.print(ohm); Serial.print(","); Serial.print("'tvoc':"); Serial.print(tvoc); Serial.print("}"); Serial.println(); } void printCompensatedMeasurements(void) { float temp, humidity, pressure, pressureMoreAccurate; double tempMostAccurate, humidityMostAccurate, pressureMostAccurate; temp = BME280.getTemperature(); humidity = BME280.getHumidity(); pressure = BME280.getPressure(); pressureMoreAccurate = BME280.getPressureMoreAccurate(); tempMostAccurate = BME280.getTemperatureMostAccurate(); humidityMostAccurate = BME280.getHumidityMostAccurate(); pressureMostAccurate = BME280.getPressureMostAccurate(); Serial.print("{"); Serial.print("'event':'measurement'"); Serial.print(","); Serial.print("'sensor':'BME280'"); Serial.print(","); Serial.print("'mode':'compensated'"); Serial.print(","); Serial.print("'temperature':"); Serial.print(temp); Serial.print("'temperature_most_accurate':"); Serial.print(tempMostAccurate); Serial.print(","); Serial.print("'humidity':"); Serial.print(humidity); Serial.print(","); Serial.print("'humidity_most_accurate':"); Serial.print(humidityMostAccurate); Serial.print(","); Serial.print("'pressure':"); Serial.print(pressure); Serial.print(","); Serial.print("'pressure_more_accurate':"); Serial.print(pressureMoreAccurate); Serial.print(","); Serial.print("'pressure_most_accurate':"); Serial.print(pressureMostAccurate); Serial.print("}"); Serial.println(); } // example of a forced sample. After taking the measurement the chip goes back to sleep void bme280_forcedSample() { float temp, humidity, pressure, pressureMoreAccurate; double tempMostAccurate, humidityMostAccurate, pressureMostAccurate; // need to read the NVM compensation parameters BME280.readCompensationParams(); // Need to turn on 1x oversampling, default is os_skipped, which means it doesn't measure anything BME280.writeOversamplingPressure(os1x); // 1x over sampling (ie, just one sample) BME280.writeOversamplingTemperature(os1x); BME280.writeOversamplingHumidity(os1x); BME280.writeMode(smForced); while (BME280.isMeasuring()) { } // read out the data - must do this before calling the getxxxxx routines BME280.readMeasurements(); temp = BME280.getTemperature(); humidity = BME280.getHumidity(); pressure = BME280.getPressure(); pressureMoreAccurate = BME280.getPressureMoreAccurate(); tempMostAccurate = BME280.getTemperatureMostAccurate(); humidityMostAccurate = BME280.getHumidityMostAccurate(); pressureMostAccurate = BME280.getPressureMostAccurate(); Serial.print("{"); Serial.print("'event':'measurement'"); Serial.print(","); Serial.print("'sensor':'BME280'"); Serial.print(","); Serial.print("'mode':'forced'"); Serial.print(","); Serial.print("'temperature':"); Serial.print(temp); Serial.print("'temperature_most_accurate':"); Serial.print(tempMostAccurate); Serial.print(","); Serial.print("'humidity':"); Serial.print(humidity); Serial.print(","); Serial.print("'humidity_most_accurate':"); Serial.print(humidityMostAccurate); Serial.print(","); Serial.print("'pressure':"); Serial.print(pressure); Serial.print(","); Serial.print("'pressure_more_accurate':"); Serial.print(pressureMoreAccurate); Serial.print(","); Serial.print("'pressure_most_accurate':"); Serial.print(pressureMostAccurate); Serial.print("}"); Serial.println(); } // Example for "indoor navigation" // We'll switch into normal mode for regular automatic samples void bme280_indoorSample() { BME280.writeStandbyTime(tsb_0p5ms); // tsb = 0.5ms BME280.writeFilterCoefficient(fc_16); // IIR Filter coefficient 16 BME280.writeOversamplingPressure(os16x); // pressure x16 BME280.writeOversamplingTemperature(os2x); // temperature x2 BME280.writeOversamplingHumidity(os1x); // humidity x1 BME280.writeMode(smNormal); //Do nothing while measuring while (BME280.isMeasuring()) { } // read out the data - must do this before calling the getxxxxx routines BME280.readMeasurements(); printCompensatedMeasurements(); } <commit_msg>Bugfix<commit_after>/* Copyright (c) 2015, Embedded Adventures All rights reserved. Contact us at source [at] embeddedadventures.com www.embeddedadventures.com 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 Embedded Adventures 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. */ // Test sketch for MOD1023 // Communicating with the BME280 weather multi-sensor and the indoor air quality sensor #include <BME280_MOD-1022.h> #include <iAQ-MOD1023.h> #include <Wire.h> int ledPin = 13; int inPin = 7; int val = 0; bool event = false; unsigned int counter = 0; void setup() { pinMode(ledPin, OUTPUT); pinMode(inPin, INPUT); Serial.begin(115200); Wire.begin(); uns8 chipID = BME280.readChipId(); bme280_forcedSample(); } void loop() { val = digitalRead(inPin); if (val == HIGH && event == false) { event = true; Serial.print("{'event':'button_pressed'}"); Serial.println(); digitalWrite(ledPin, HIGH); } if ( counter % 2000 == 0 ) { if (event) { digitalWrite(ledPin, LOW); event = false; } } if (counter % 5000 == 0) { iaqUpdate(); bme280_indoorSample(); } delay(1); counter++; } //Update and print data from iAQ void iaqUpdate() { String status; int pred, ohm, tvoc; iaq.readRegisters(); status = iaq.getStatus(); pred = iaq.getPrediction(); ohm = iaq.getResistance(); tvoc = iaq.getTVOC(); Serial.print("{"); Serial.print("'event':'measurement'"); Serial.print(","); Serial.print("'sensor':'iAQ'"); Serial.print(","); Serial.print("'status':'"); Serial.print(status); Serial.print("',"); Serial.print("'pred':"); Serial.print(pred); Serial.print(","); Serial.print("'ohm':"); Serial.print(ohm); Serial.print(","); Serial.print("'tvoc':"); Serial.print(tvoc); Serial.print("}"); Serial.println(); } void printCompensatedMeasurements(void) { float temp, humidity, pressure, pressureMoreAccurate; double tempMostAccurate, humidityMostAccurate, pressureMostAccurate; temp = BME280.getTemperature(); humidity = BME280.getHumidity(); pressure = BME280.getPressure(); pressureMoreAccurate = BME280.getPressureMoreAccurate(); tempMostAccurate = BME280.getTemperatureMostAccurate(); humidityMostAccurate = BME280.getHumidityMostAccurate(); pressureMostAccurate = BME280.getPressureMostAccurate(); Serial.print("{"); Serial.print("'event':'measurement'"); Serial.print(","); Serial.print("'sensor':'BME280'"); Serial.print(","); Serial.print("'mode':'compensated'"); Serial.print(","); Serial.print("'temperature':"); Serial.print(","); Serial.print(temp); Serial.print("'temperature_most_accurate':"); Serial.print(tempMostAccurate); Serial.print(","); Serial.print("'humidity':"); Serial.print(humidity); Serial.print(","); Serial.print("'humidity_most_accurate':"); Serial.print(humidityMostAccurate); Serial.print(","); Serial.print("'pressure':"); Serial.print(pressure); Serial.print(","); Serial.print("'pressure_more_accurate':"); Serial.print(pressureMoreAccurate); Serial.print(","); Serial.print("'pressure_most_accurate':"); Serial.print(pressureMostAccurate); Serial.print("}"); Serial.println(); } // example of a forced sample. After taking the measurement the chip goes back to sleep void bme280_forcedSample() { float temp, humidity, pressure, pressureMoreAccurate; double tempMostAccurate, humidityMostAccurate, pressureMostAccurate; // need to read the NVM compensation parameters BME280.readCompensationParams(); // Need to turn on 1x oversampling, default is os_skipped, which means it doesn't measure anything BME280.writeOversamplingPressure(os1x); // 1x over sampling (ie, just one sample) BME280.writeOversamplingTemperature(os1x); BME280.writeOversamplingHumidity(os1x); BME280.writeMode(smForced); while (BME280.isMeasuring()) { } // read out the data - must do this before calling the getxxxxx routines BME280.readMeasurements(); temp = BME280.getTemperature(); humidity = BME280.getHumidity(); pressure = BME280.getPressure(); pressureMoreAccurate = BME280.getPressureMoreAccurate(); tempMostAccurate = BME280.getTemperatureMostAccurate(); humidityMostAccurate = BME280.getHumidityMostAccurate(); pressureMostAccurate = BME280.getPressureMostAccurate(); Serial.print("{"); Serial.print("'event':'measurement'"); Serial.print(","); Serial.print("'sensor':'BME280'"); Serial.print(","); Serial.print("'mode':'forced'"); Serial.print(","); Serial.print("'temperature':"); Serial.print(temp); Serial.print(","); Serial.print("'temperature_most_accurate':"); Serial.print(tempMostAccurate); Serial.print(","); Serial.print("'humidity':"); Serial.print(humidity); Serial.print(","); Serial.print("'humidity_most_accurate':"); Serial.print(humidityMostAccurate); Serial.print(","); Serial.print("'pressure':"); Serial.print(pressure); Serial.print(","); Serial.print("'pressure_more_accurate':"); Serial.print(pressureMoreAccurate); Serial.print(","); Serial.print("'pressure_most_accurate':"); Serial.print(pressureMostAccurate); Serial.print("}"); Serial.println(); } // Example for "indoor navigation" // We'll switch into normal mode for regular automatic samples void bme280_indoorSample() { BME280.writeStandbyTime(tsb_0p5ms); // tsb = 0.5ms BME280.writeFilterCoefficient(fc_16); // IIR Filter coefficient 16 BME280.writeOversamplingPressure(os16x); // pressure x16 BME280.writeOversamplingTemperature(os2x); // temperature x2 BME280.writeOversamplingHumidity(os1x); // humidity x1 BME280.writeMode(smNormal); //Do nothing while measuring while (BME280.isMeasuring()) { } // read out the data - must do this before calling the getxxxxx routines BME280.readMeasurements(); printCompensatedMeasurements(); } <|endoftext|>
<commit_before>#include "stdafx.h" #include "PvpPotion.h" #include "../../Common/ETypes.h" #include "../../Common/Helpers/RapidHelper.hpp" #include <ATF/global.hpp> namespace GameServer { namespace Addon { #define CheckEffLimType(x, y) \ (x == y && x != -1 && y != -1) bool CPvpPotion::m_bActivated = false; CPvpPotion::TempEffectFunc_Cont CPvpPotion::g_TempEffectFunc; void CPvpPotion::load() { TempEffectFunc_Ptr* origTempEffectFunc = (TempEffectFunc_Ptr*)0x14096CDF0L; for (int i = 0; i < detail::count_orig_effect_func; ++i) { g_TempEffectFunc[i] = origTempEffectFunc[i]; } ::std::vector<::std::pair<int, TempEffectFunc_Ptr>> vecNewFunc{ { 182, &AlterMoneyPotion<e_money_type::cp> }, { 183, &AlterMoneyPotion<e_money_type::gold> }, { 184, &AlterMoneyPotion<e_money_type::pvp_point> }, { 185, &AlterMoneyPotion<e_money_type::pvp_point_2> }, { 186, &AlterMoneyPotion<e_money_type::processing_point> }, { 187, &AlterMoneyPotion<e_money_type::hunter_point> }, { 188, &AlterMoneyPotion<e_money_type::gold_point> }, { 189, &RecallMonsterPotion }, }; for (auto& kv : vecNewFunc) { g_TempEffectFunc[kv.first] = kv.second; } enable_hook(&ATF::CPotionMgr::ApplyPotion, &CPvpPotion::ApplyPotion); } void CPvpPotion::unload() { cleanup_all_hook(); } Yorozuya::Module::ModuleName_t CPvpPotion::get_name() { static const Yorozuya::Module::ModuleName_t name = "addon.pvp_potion"; return name; } void CPvpPotion::configure(const rapidjson::Value & nodeConfig) { CPvpPotion::m_bActivated = RapidHelper::GetValueOrDefault(nodeConfig, "activated", false); } int WINAPIV CPvpPotion::ApplyPotion( ATF::CPotionMgr* pObj, ATF::CPlayer* pUsePlayer, ATF::CPlayer* pApplyPlayer, ATF::_skill_fld* pEffecFld, ATF::_CheckPotion_fld* pCheckFld, ATF::_PotionItem_fld* pfB, bool bCommonPotion, ATF::Info::CPotionMgrApplyPotion2_ptr next) { if (!CPvpPotion::m_bActivated) return next(pObj, pUsePlayer, pApplyPlayer, pEffecFld, pCheckFld, pfB, bCommonPotion); if (!pUsePlayer || !pApplyPlayer || !pEffecFld) return -1; if (pCheckFld) { for (auto& i : pCheckFld->m_CheckEffectCode) { if (!ATF::Global::_CheckPotionData(&i, pApplyPlayer)) return 19; } } int nContEffectResult = -1; int nResult = -1; if (pEffecFld->m_nContEffectType != -1 && bCommonPotion) { int indxDelBuff = 0; bool bExpiresBuff = false; for (int k = 0; k < _countof(pUsePlayer->m_PotionParam.m_ContCommonPotionData); ++k) { int n = pUsePlayer->m_PotionParam.m_ContCommonPotionData[k].GetEffectIndex(); auto pPotionFld = (ATF::_PotionItem_fld*)ATF::Global::g_MainThread ->m_tblItemData[(int)e_code_item_table::tbl_code_potion].GetRecord(n); auto pCurrFld = (ATF::_skill_fld*)pObj->m_tblPotionEffectData.GetRecord(n); if (!pCurrFld) continue; if (CheckEffLimType(pCurrFld->m_nEffLimType, pEffecFld->m_nEffLimType) || CheckEffLimType(pCurrFld->m_nEffLimType, pEffecFld->m_nEffLimType2) || CheckEffLimType(pCurrFld->m_nEffLimType2, pEffecFld->m_nEffLimType) || CheckEffLimType(pCurrFld->m_nEffLimType2, pEffecFld->m_nEffLimType2)) { if (pPotionFld) { if (pPotionFld->m_nPotionCheck <= pfB->m_nPotionCheck) { bExpiresBuff = true; indxDelBuff = k; } } } } if (pApplyPlayer->m_PotionBufUse.IsExtPotionUse()) { if (!bExpiresBuff) indxDelBuff = pObj->SelectDeleteBuf(pApplyPlayer, true, false); } else { indxDelBuff = pObj->SelectDeleteBuf(pApplyPlayer, false, false); } if (indxDelBuff > _countof(pUsePlayer->m_PotionParam.m_ContCommonPotionData)) return 25; nContEffectResult = pObj->InsertPotionContEffect( pApplyPlayer, &pUsePlayer->m_PotionParam.m_ContCommonPotionData[indxDelBuff], pEffecFld, pEffecFld->m_nContEffectSec[0]); } if (pEffecFld->m_nTempEffectType != -1) { if (pEffecFld->m_nTempEffectType >= 150 && pEffecFld->m_nTempEffectType < detail::count_orig_effect_func || pEffecFld->m_nTempEffectType >= detail::count_new_effect_func) { nResult = -1; } else { float fValue = 0.0; if (ATF::Global::_GetTempEffectValue(pEffecFld, pEffecFld->m_nTempEffectType, &fValue)) { char nRet = -1; auto fnEffect = CPvpPotion::g_TempEffectFunc[pEffecFld->m_nTempEffectType]; if (fnEffect && fnEffect(pUsePlayer, pApplyPlayer, fValue, &nRet)) nResult = 0; else nResult = nRet; } else { nResult = -1; } } } int result; if (nContEffectResult && nResult) result = nContEffectResult; else result = 0; return result; } bool WINAPIV CPvpPotion::RecallMonsterPotion( ATF::CCharacter * pAct, ATF::CCharacter * pTargetChar, float fEffectValue, char * byRet) { ATF::CPlayer *pActChar = (ATF::CPlayer *)pAct; pAct->m_fCurPos; int iMonsterIndx = static_cast<int>(fEffectValue); bool result = false; do { ATF::_monster_fld* pFld = (ATF::_monster_fld*)ATF::Global::g_MainThread ->m_tblMonster.GetRecord(iMonsterIndx); if (!pFld) break; result = pActChar->mgr_recall_mon(pFld->m_strCode, 1); } while (false); return result; } } } <commit_msg>mini refactoring<commit_after>#include "stdafx.h" #include "PvpPotion.h" #include "../../Common/ETypes.h" #include "../../Common/Helpers/RapidHelper.hpp" #include <ATF/global.hpp> namespace GameServer { namespace Addon { #define CheckEffLimType(x, y) \ (x == y && x != -1 && y != -1) bool CPvpPotion::m_bActivated = false; CPvpPotion::TempEffectFunc_Cont CPvpPotion::g_TempEffectFunc; void CPvpPotion::load() { TempEffectFunc_Ptr* origTempEffectFunc = (TempEffectFunc_Ptr*)0x14096CDF0L; for (int i = 0; i < detail::count_orig_effect_func; ++i) { g_TempEffectFunc[i] = origTempEffectFunc[i]; } ::std::vector<::std::pair<int, TempEffectFunc_Ptr>> vecNewFunc{ { 182, &AlterMoneyPotion<e_money_type::cp> }, { 183, &AlterMoneyPotion<e_money_type::gold> }, { 184, &AlterMoneyPotion<e_money_type::pvp_point> }, { 185, &AlterMoneyPotion<e_money_type::pvp_point_2> }, { 186, &AlterMoneyPotion<e_money_type::processing_point> }, { 187, &AlterMoneyPotion<e_money_type::hunter_point> }, { 188, &AlterMoneyPotion<e_money_type::gold_point> }, { 189, &RecallMonsterPotion }, }; for (auto& kv : vecNewFunc) { g_TempEffectFunc[kv.first] = kv.second; } enable_hook(&ATF::CPotionMgr::ApplyPotion, &CPvpPotion::ApplyPotion); } void CPvpPotion::unload() { cleanup_all_hook(); } Yorozuya::Module::ModuleName_t CPvpPotion::get_name() { static const Yorozuya::Module::ModuleName_t name = "addon.pvp_potion"; return name; } void CPvpPotion::configure(const rapidjson::Value & nodeConfig) { CPvpPotion::m_bActivated = RapidHelper::GetValueOrDefault(nodeConfig, "activated", false); } int WINAPIV CPvpPotion::ApplyPotion( ATF::CPotionMgr* pObj, ATF::CPlayer* pUsePlayer, ATF::CPlayer* pApplyPlayer, ATF::_skill_fld* pEffecFld, ATF::_CheckPotion_fld* pCheckFld, ATF::_PotionItem_fld* pfB, bool bCommonPotion, ATF::Info::CPotionMgrApplyPotion2_ptr next) { if (!CPvpPotion::m_bActivated) return next(pObj, pUsePlayer, pApplyPlayer, pEffecFld, pCheckFld, pfB, bCommonPotion); if (!pUsePlayer || !pApplyPlayer || !pEffecFld) return -1; if (pCheckFld) { for (auto& i : pCheckFld->m_CheckEffectCode) { if (!ATF::Global::_CheckPotionData(&i, pApplyPlayer)) return 19; } } int nContEffectResult = -1; int nResult = -1; if (pEffecFld->m_nContEffectType != -1 && bCommonPotion) { int indxDelBuff = 0; bool bExpiresBuff = false; for (int k = 0; k < _countof(pUsePlayer->m_PotionParam.m_ContCommonPotionData); ++k) { int n = pUsePlayer->m_PotionParam.m_ContCommonPotionData[k].GetEffectIndex(); auto pPotionFld = (ATF::_PotionItem_fld*)ATF::Global::g_MainThread ->m_tblItemData[(int)e_code_item_table::tbl_code_potion].GetRecord(n); auto pCurrFld = (ATF::_skill_fld*)pObj->m_tblPotionEffectData.GetRecord(n); if (!pCurrFld) continue; if (CheckEffLimType(pCurrFld->m_nEffLimType, pEffecFld->m_nEffLimType) || CheckEffLimType(pCurrFld->m_nEffLimType, pEffecFld->m_nEffLimType2) || CheckEffLimType(pCurrFld->m_nEffLimType2, pEffecFld->m_nEffLimType) || CheckEffLimType(pCurrFld->m_nEffLimType2, pEffecFld->m_nEffLimType2)) { if (pPotionFld) { if (pPotionFld->m_nPotionCheck <= pfB->m_nPotionCheck) { bExpiresBuff = true; indxDelBuff = k; } } } } if (pApplyPlayer->m_PotionBufUse.IsExtPotionUse()) { if (!bExpiresBuff) indxDelBuff = pObj->SelectDeleteBuf(pApplyPlayer, true, false); } else { indxDelBuff = pObj->SelectDeleteBuf(pApplyPlayer, false, false); } if (indxDelBuff > _countof(pUsePlayer->m_PotionParam.m_ContCommonPotionData)) return 25; nContEffectResult = pObj->InsertPotionContEffect( pApplyPlayer, &pUsePlayer->m_PotionParam.m_ContCommonPotionData[indxDelBuff], pEffecFld, pEffecFld->m_nContEffectSec[0]); } if (pEffecFld->m_nTempEffectType != -1) { if (pEffecFld->m_nTempEffectType >= 150 && pEffecFld->m_nTempEffectType < detail::count_orig_effect_func || pEffecFld->m_nTempEffectType >= detail::count_new_effect_func) { nResult = -1; } else { float fValue = 0.0; if (ATF::Global::_GetTempEffectValue(pEffecFld, pEffecFld->m_nTempEffectType, &fValue)) { char nRet = -1; auto fnEffect = CPvpPotion::g_TempEffectFunc[pEffecFld->m_nTempEffectType]; if (fnEffect && fnEffect(pUsePlayer, pApplyPlayer, fValue, &nRet)) nResult = 0; else nResult = nRet; } else { nResult = -1; } } } int result; if (nContEffectResult && nResult) result = nContEffectResult; else result = 0; return result; } bool WINAPIV CPvpPotion::RecallMonsterPotion( ATF::CCharacter * pAct, ATF::CCharacter * pTargetChar, float fEffectValue, char * byRet) { bool result = false; do { int iMonsterIndx = static_cast<int>(fEffectValue); ATF::CPlayer *pActChar = (ATF::CPlayer *)pAct; ATF::_monster_fld* pFld = (ATF::_monster_fld*)ATF::Global::g_MainThread ->m_tblMonster.GetRecord(iMonsterIndx); if (!pFld) break; result = pActChar->mgr_recall_mon(pFld->m_strCode, 1); } while (false); return result; } } } <|endoftext|>
<commit_before>#include <vector> #include "toml.h" #include <random> #include <iostream> #include <cmath> #include "xoroshiro128plus.h" #include "statistics.h" #include "properties.h" #include <stack> #include <set> inline void metropolis_sweep(std::vector<std::vector<double> >& lattice, xoroshiro128plus& gen, std::uniform_real_distribution<double>& delta_dist, std::uniform_real_distribution<double>& real_dist, double beta){ int L = lattice.size(); int i_plus, j_plus, i_minus, j_minus; std::vector<double> nb_angles = {0.0, 0.0, 0.0, 0.0}; double sigma_old, sigma_new; double delta_E, p_accept; N_ATTEMPTED_FLIPS += L*L; for (int i=0; i<L; i++){ for (int j=0; j<L; j++){ delta_E = 0.0; i_plus = (i != L-1) ? i+1: 0; i_minus = (i != 0 ) ? i-1: L-1; j_plus = (j != L-1) ? j+1: 0; j_minus = (j != 0 ) ? j-1: L-1; //neighboring angles nb_angles[0] = lattice[i_plus][j]; nb_angles[1] = lattice[i_minus][j]; nb_angles[2] = lattice[i][j_plus]; nb_angles[3] = lattice[i][j_minus]; //delta_E = E(sigma_new) - E(sigma) sigma_old = lattice[i][j]; sigma_new = sigma_old - delta_dist(gen); for (int nb=0; nb<4; nb++){ delta_E += cos(sigma_old - nb_angles[nb]) - cos(sigma_new - nb_angles[nb]); } if (delta_E <= 0){ //good change lattice[i][j] = sigma_new; N_ACCEPTED_FLIPS++; }else{ p_accept = exp(-beta*delta_E); if (p_accept > real_dist(gen)){ lattice[i][j] = sigma_new; N_ACCEPTED_FLIPS++; } } } } }; inline void microcanonical_sweep(std::vector<std::vector<double> >& lattice){ int L = lattice.size(); int i_plus, j_plus, i_minus, j_minus; std::vector<double> nb_angles = {0.0, 0.0, 0.0, 0.0}; double Vxx, Vxy, Vx_sq; double x, y, x_new, y_new; double sigma; for (int i=0; i<L; i++){ for (int j=0; j<L; j++){ Vxx = 0.0; Vxy = 0.0; sigma = lattice[i][j]; x = cos(sigma); y = sin(sigma); i_plus = (i != L-1) ? i+1: 0; i_minus = (i != 0 ) ? i-1: L-1; j_plus = (j != L-1) ? j+1: 0; j_minus = (j != 0 ) ? j-1: L-1; //neighboring angles nb_angles[0] = lattice[i_plus][j]; nb_angles[1] = lattice[i_minus][j]; nb_angles[2] = lattice[i][j_plus]; nb_angles[3] = lattice[i][j_minus]; for (int nb=0; nb<4; nb++){ Vxx += cos(nb_angles[nb]); Vxy += sin(nb_angles[nb]); } Vx_sq = Vxx*Vxx + Vxy*Vxy; x_new = 2 * (x * Vxx + y * Vxy) / Vx_sq * Vxx - x; y_new = 2 * (x * Vxx + y * Vxy) / Vx_sq * Vxy - y; lattice[i][j] = atan2(y_new, x_new); } } }; inline void cluster_sweep(std::vector<std::vector<double> >& lattice, xoroshiro128plus& gen, std::uniform_real_distribution<double>& angle_dist, std::uniform_real_distribution<double>& real_dist, std::uniform_int_distribution<int>& L_dist, double beta){ int i_plus, j_plus, i_minus, j_minus; int L = lattice.size(); double p_add, sx, sy; N_ATTEMPTED_FLIPS += L*L; //make stack of neighbor spins std::stack<std::pair<int,int> > cluster_buffer; std::pair<int,int> current_site; //make set of sites currently in the cluster std::set<std::pair<int,int> > cluster_set; //pick random vector r double theta = angle_dist(gen); double rx = cos(theta); double ry = sin(theta); //pick starting seed int i = L_dist(gen); int j = L_dist(gen); //add seed site to accepted spins N_ACCEPTED_FLIPS++; cluster_set.insert(std::make_pair(i, j)); cluster_buffer.push(std::make_pair(i, j)); while(!cluster_buffer.empty()){ std::vector<std::pair<int,int> > neighbors; //look at the top of the stack, and find the neighbors current_site = cluster_buffer.top(); cluster_buffer.pop(); i = current_site.first; j = current_site.second; sx = cos(lattice[i][j])*rx + sin(lattice[i][j])*ry; i_plus = (i != L-1) ? i+1: 0; i_minus = (i != 0 ) ? i-1: L-1; j_plus = (j != L-1) ? j+1: 0; j_minus = (j != 0 ) ? j-1: L-1; neighbors.push_back(std::make_pair(i_minus, j)); neighbors.push_back(std::make_pair(i_plus, j)); neighbors.push_back(std::make_pair(i, j_minus)); neighbors.push_back(std::make_pair(i, j_plus)); for (int n=0; n<(int)neighbors.size(); n++){ i = neighbors[n].first; j = neighbors[n].second; if (cluster_set.count(neighbors[n]) == 0){ // neighbor is *not* in cluster already // check if it should be added sy = cos(lattice[i][j])*rx + sin(lattice[i][j])*ry; p_add = 1.0 - exp(-2*beta*sx*sy); if (real_dist(gen) < p_add){ N_ACCEPTED_FLIPS++; cluster_set.insert(neighbors[n]); cluster_buffer.push(neighbors[n]); } } } } for (auto site : cluster_set){ //flip all spins in the cluster i = site.first; j = site.second; sx = cos(lattice[i][j])*rx + sin(lattice[i][j])*ry; lattice[i][j] = atan2(sin(lattice[i][j]) - 2*sx*ry, cos(lattice[i][j]) - 2*sx*rx); } } //////////////////////////////////////// //Standard metropolis + microcanonical// //////////////////////////////////////// void metropolis(int n_steps_therm, int n_steps_prod, int side_length, double beta, std::string outfile, int outfreq, int conf_outfreq, double delta, int n_mc_sweep){ //store lattice as 2d array std::vector<std::vector<double> > lattice; //Initialize 128 bits of random state std::random_device rd; std::array<uint32_t,4> seed; seed[0] = rd(); seed[1] = rd(); seed[2] = rd(); seed[3] = rd(); xoroshiro128plus gen(seed); std::uniform_real_distribution<double> angle_dist(0.0, 2.0*M_PI); std::uniform_real_distribution<double> delta_dist(-delta/2.0, delta/2.0); std::uniform_real_distribution<double> real_dist(0.0, 1.0); std::vector<double> energies; //setup lattice (hot start) for (int i=0; i<side_length; i++){ std::vector<double> line; for (int j=0; j<side_length; j++){ line.push_back(angle_dist(gen)); } line.shrink_to_fit(); lattice.push_back(line); } lattice.shrink_to_fit(); //thermalize for (int n=0; n<n_steps_therm; n++){ metropolis_sweep(lattice, gen, delta_dist, real_dist, beta); //do n_mc_sweep of microcanonical sweeps for (int mc=0; mc<n_mc_sweep; mc++){microcanonical_sweep(lattice);} if (n%100 == 0){ std::cout << "\rThermalizing, " << std::setprecision(5) << 100 * (double)n / (double)n_steps_therm << "%" << std::flush; } } std::cout << "\rThermalizing, ...Done!"; std::cout << std::endl; //production run for (int n=0; n<n_steps_prod; n++){ metropolis_sweep(lattice, gen, delta_dist, real_dist, beta); for (int mc=0; mc<n_mc_sweep; mc++){microcanonical_sweep(lattice);} if (n%outfreq == 0){ energies.push_back(compute_energy(lattice)); } if (n%conf_outfreq == 0){ write_configuration(lattice, outfile + ".conf" + std::to_string(n)); } if (n%100 == 0){ std::cout << "\rRunning production, " << std::setprecision(5) << 100 * (double)n / (double)n_steps_prod << "%" << std::flush; } } std::cout << "\rRunning production, ...Done!"; std::cout << std::endl; std::cout << "Beta: " << beta << " Acceptance ratio: " << (double) N_ACCEPTED_FLIPS / (double) N_ATTEMPTED_FLIPS << std::endl; //write properties and final configuration to file write_properties(energies, outfile + ".autocorr"); write_energies(energies, outfile + ".energies"); write_configuration(lattice, outfile + ".conf"); }; ///////////////////// //Cluster algorithm// ///////////////////// void cluster(int n_steps_therm, int n_steps_prod, int side_length, double beta, std::string outfile, int outfreq, int conf_outfreq, int n_mc_sweep){ //store lattice as 2d array std::vector<std::vector<double> > lattice; //Initialize 128 bits of random state std::random_device rd; std::array<uint32_t,4> seed; seed[0] = rd(); seed[1] = rd(); seed[2] = rd(); seed[3] = rd(); xoroshiro128plus gen(seed); std::uniform_real_distribution<double> angle_dist(0.0, 2.0*M_PI); std::uniform_real_distribution<double> real_dist(0.0, 1.0); std::uniform_int_distribution<int> L_dist(0, side_length-1); std::vector<double> energies; //setup lattice (hot start) for (int i=0; i<side_length; i++){ std::vector<double> line; for (int j=0; j<side_length; j++){ line.push_back(angle_dist(gen)); } line.shrink_to_fit(); lattice.push_back(line); } lattice.shrink_to_fit(); //thermalize for (int n=0; n<n_steps_therm; n++){ cluster_sweep(lattice, gen, angle_dist, real_dist, L_dist, beta); //do n_mc_sweep of microcanonical sweeps for (int mc=0; mc<n_mc_sweep; mc++){microcanonical_sweep(lattice);} if (n%100 == 0){ std::cout << "\rThermalizing, " << std::setprecision(5) << 100 * (double)n / (double)n_steps_therm << "%" << std::flush; } } std::cout << "\rThermalizing, ...Done!"; std::cout << std::endl; //production run for (int n=0; n<n_steps_prod; n++){ cluster_sweep(lattice, gen, angle_dist, real_dist, L_dist, beta); for (int mc=0; mc<n_mc_sweep; mc++){microcanonical_sweep(lattice);} if (n%outfreq == 0){ energies.push_back(compute_energy(lattice)); } if (n%conf_outfreq == 0){ write_configuration(lattice, outfile + ".conf" + std::to_string(n)); } if (n%100 == 0){ std::cout << "\rRunning production, " << std::setprecision(5) << 100 * (double)n / (double)n_steps_prod << "%" << std::flush; } } std::cout << "\rRunning production, ...Done!"; std::cout << std::endl; std::cout << "Beta: " << beta << " Acceptance ratio: " << (double) N_ACCEPTED_FLIPS / (double) N_ATTEMPTED_FLIPS << std::endl; //write properties and final configuration to file write_properties(energies, outfile + ".autocorr"); write_energies(energies, outfile + ".energies"); write_configuration(lattice, outfile + ".conf"); }; <commit_msg>Way cooler PBC now<commit_after>#include <vector> #include "toml.h" #include <random> #include <iostream> #include <cmath> #include "xoroshiro128plus.h" #include "statistics.h" #include "properties.h" #include <stack> #include <set> inline void metropolis_sweep(std::vector<std::vector<double> >& lattice, xoroshiro128plus& gen, std::uniform_real_distribution<double>& delta_dist, std::uniform_real_distribution<double>& real_dist, double beta){ int L = lattice.size(); int PBC = L - 1; //int i_plus, j_plus, i_minus, j_minus; std::vector<double> nb_angles = {0.0, 0.0, 0.0, 0.0}; double sigma_old, sigma_new; double delta_E, p_accept; N_ATTEMPTED_FLIPS += L*L; for (int i=0; i<L; i++){ for (int j=0; j<L; j++){ delta_E = 0.0; /* i_plus = (i != L-1) ? i+1: 0; i_minus = (i != 0 ) ? i-1: L-1; j_plus = (j != L-1) ? j+1: 0; j_minus = (j != 0 ) ? j-1: L-1; */ //neighboring angles //using bitwise and to do the PBC nb_angles[0] = lattice[(i+1)&PBC][j]; nb_angles[1] = lattice[(i-1)&PBC][j]; nb_angles[2] = lattice[i][(j+1)&PBC]; nb_angles[3] = lattice[i][(j-1)&PBC]; //delta_E = E(sigma_new) - E(sigma) sigma_old = lattice[i][j]; sigma_new = sigma_old - delta_dist(gen); for (int nb=0; nb<4; nb++){ delta_E += cos(sigma_old - nb_angles[nb]) - cos(sigma_new - nb_angles[nb]); } if (delta_E <= 0){ //good change lattice[i][j] = sigma_new; N_ACCEPTED_FLIPS++; }else{ p_accept = exp(-beta*delta_E); if (p_accept > real_dist(gen)){ lattice[i][j] = sigma_new; N_ACCEPTED_FLIPS++; } } } } }; inline void microcanonical_sweep(std::vector<std::vector<double> >& lattice){ int L = lattice.size(); int PBC = L - 1; //int i_plus, j_plus, i_minus, j_minus; std::vector<double> nb_angles = {0.0, 0.0, 0.0, 0.0}; double Vxx, Vxy, Vx_sq; double x, y, x_new, y_new; double sigma; for (int i=0; i<L; i++){ for (int j=0; j<L; j++){ Vxx = 0.0; Vxy = 0.0; sigma = lattice[i][j]; x = cos(sigma); y = sin(sigma); /* i_plus = (i != L-1) ? i+1: 0; i_minus = (i != 0 ) ? i-1: L-1; j_plus = (j != L-1) ? j+1: 0; j_minus = (j != 0 ) ? j-1: L-1; */ //neighboring angles nb_angles[0] = lattice[(i+1)&PBC][j]; nb_angles[1] = lattice[(i-1)&PBC][j]; nb_angles[2] = lattice[i][(j+1)&PBC]; nb_angles[3] = lattice[i][(j-1)&PBC]; for (int nb=0; nb<4; nb++){ Vxx += cos(nb_angles[nb]); Vxy += sin(nb_angles[nb]); } Vx_sq = Vxx*Vxx + Vxy*Vxy; x_new = 2 * (x * Vxx + y * Vxy) / Vx_sq * Vxx - x; y_new = 2 * (x * Vxx + y * Vxy) / Vx_sq * Vxy - y; lattice[i][j] = atan2(y_new, x_new); } } }; inline void cluster_sweep(std::vector<std::vector<double> >& lattice, xoroshiro128plus& gen, std::uniform_real_distribution<double>& angle_dist, std::uniform_real_distribution<double>& real_dist, std::uniform_int_distribution<int>& L_dist, double beta){ //int i_plus, j_plus, i_minus, j_minus; int L = lattice.size(); int PBC = L - 1; double p_add, sx, sy; N_ATTEMPTED_FLIPS += L*L; //make stack of neighbor spins std::stack<std::pair<int,int> > cluster_buffer; std::pair<int,int> current_site; //make set of sites currently in the cluster std::set<std::pair<int,int> > cluster_set; //pick random vector r double theta = angle_dist(gen); double rx = cos(theta); double ry = sin(theta); //pick starting seed int i = L_dist(gen); int j = L_dist(gen); //add seed site to accepted spins N_ACCEPTED_FLIPS++; cluster_set.insert(std::make_pair(i, j)); cluster_buffer.push(std::make_pair(i, j)); while(!cluster_buffer.empty()){ std::vector<std::pair<int,int> > neighbors; //look at the top of the stack, and find the neighbors current_site = cluster_buffer.top(); cluster_buffer.pop(); i = current_site.first; j = current_site.second; sx = cos(lattice[i][j])*rx + sin(lattice[i][j])*ry; /* i_plus = (i != L-1) ? i+1: 0; i_minus = (i != 0 ) ? i-1: L-1; j_plus = (j != L-1) ? j+1: 0; j_minus = (j != 0 ) ? j-1: L-1; */ neighbors.push_back(std::make_pair((i-1)&PBC, j)); neighbors.push_back(std::make_pair((i+1)&PBC, j)); neighbors.push_back(std::make_pair(i, (j-1)&PBC)); neighbors.push_back(std::make_pair(i, (j+1)&PBC)); for (int n=0; n<(int)neighbors.size(); n++){ i = neighbors[n].first; j = neighbors[n].second; if (cluster_set.count(neighbors[n]) == 0){ // neighbor is *not* in cluster already // check if it should be added sy = cos(lattice[i][j])*rx + sin(lattice[i][j])*ry; p_add = 1.0 - exp(-2*beta*sx*sy); if (real_dist(gen) < p_add){ N_ACCEPTED_FLIPS++; cluster_set.insert(neighbors[n]); cluster_buffer.push(neighbors[n]); } } } } for (auto site : cluster_set){ //flip all spins in the cluster i = site.first; j = site.second; sx = cos(lattice[i][j])*rx + sin(lattice[i][j])*ry; lattice[i][j] = atan2(sin(lattice[i][j]) - 2*sx*ry, cos(lattice[i][j]) - 2*sx*rx); } } //////////////////////////////////////// //Standard metropolis + microcanonical// //////////////////////////////////////// void metropolis(int n_steps_therm, int n_steps_prod, int side_length, double beta, std::string outfile, int outfreq, int conf_outfreq, double delta, int n_mc_sweep){ //store lattice as 2d array std::vector<std::vector<double> > lattice; //Initialize 128 bits of random state std::random_device rd; std::array<uint32_t,4> seed; seed[0] = rd(); seed[1] = rd(); seed[2] = rd(); seed[3] = rd(); xoroshiro128plus gen(seed); std::uniform_real_distribution<double> angle_dist(0.0, 2.0*M_PI); std::uniform_real_distribution<double> delta_dist(-delta/2.0, delta/2.0); std::uniform_real_distribution<double> real_dist(0.0, 1.0); std::vector<double> energies; //setup lattice (hot start) for (int i=0; i<side_length; i++){ std::vector<double> line; for (int j=0; j<side_length; j++){ line.push_back(angle_dist(gen)); } line.shrink_to_fit(); lattice.push_back(line); } lattice.shrink_to_fit(); //thermalize for (int n=0; n<n_steps_therm; n++){ metropolis_sweep(lattice, gen, delta_dist, real_dist, beta); //do n_mc_sweep of microcanonical sweeps for (int mc=0; mc<n_mc_sweep; mc++){microcanonical_sweep(lattice);} if (n%100 == 0){ std::cout << "\rThermalizing, " << std::setprecision(5) << 100 * (double)n / (double)n_steps_therm << "%" << std::flush; } } std::cout << "\rThermalizing, ...Done!"; std::cout << std::endl; //production run for (int n=0; n<n_steps_prod; n++){ metropolis_sweep(lattice, gen, delta_dist, real_dist, beta); for (int mc=0; mc<n_mc_sweep; mc++){microcanonical_sweep(lattice);} if (n%outfreq == 0){ energies.push_back(compute_energy(lattice)); } if (n%conf_outfreq == 0){ write_configuration(lattice, outfile + ".conf" + std::to_string(n)); } if (n%100 == 0){ std::cout << "\rRunning production, " << std::setprecision(5) << 100 * (double)n / (double)n_steps_prod << "%" << std::flush; } } std::cout << "\rRunning production, ...Done!"; std::cout << std::endl; std::cout << "Beta: " << beta << " Acceptance ratio: " << (double) N_ACCEPTED_FLIPS / (double) N_ATTEMPTED_FLIPS << std::endl; //write properties and final configuration to file write_properties(energies, outfile + ".autocorr"); write_energies(energies, outfile + ".energies"); write_configuration(lattice, outfile + ".conf"); }; ///////////////////// //Cluster algorithm// ///////////////////// void cluster(int n_steps_therm, int n_steps_prod, int side_length, double beta, std::string outfile, int outfreq, int conf_outfreq, int n_mc_sweep){ //store lattice as 2d array std::vector<std::vector<double> > lattice; //Initialize 128 bits of random state std::random_device rd; std::array<uint32_t,4> seed; seed[0] = rd(); seed[1] = rd(); seed[2] = rd(); seed[3] = rd(); xoroshiro128plus gen(seed); std::uniform_real_distribution<double> angle_dist(0.0, 2.0*M_PI); std::uniform_real_distribution<double> real_dist(0.0, 1.0); std::uniform_int_distribution<int> L_dist(0, side_length-1); std::vector<double> energies; //setup lattice (hot start) for (int i=0; i<side_length; i++){ std::vector<double> line; for (int j=0; j<side_length; j++){ line.push_back(angle_dist(gen)); } line.shrink_to_fit(); lattice.push_back(line); } lattice.shrink_to_fit(); //thermalize for (int n=0; n<n_steps_therm; n++){ cluster_sweep(lattice, gen, angle_dist, real_dist, L_dist, beta); //do n_mc_sweep of microcanonical sweeps for (int mc=0; mc<n_mc_sweep; mc++){microcanonical_sweep(lattice);} if (n%100 == 0){ std::cout << "\rThermalizing, " << std::setprecision(5) << 100 * (double)n / (double)n_steps_therm << "%" << std::flush; } } std::cout << "\rThermalizing, ...Done!"; std::cout << std::endl; //production run for (int n=0; n<n_steps_prod; n++){ cluster_sweep(lattice, gen, angle_dist, real_dist, L_dist, beta); for (int mc=0; mc<n_mc_sweep; mc++){microcanonical_sweep(lattice);} if (n%outfreq == 0){ energies.push_back(compute_energy(lattice)); } if (n%conf_outfreq == 0){ write_configuration(lattice, outfile + ".conf" + std::to_string(n)); } if (n%100 == 0){ std::cout << "\rRunning production, " << std::setprecision(5) << 100 * (double)n / (double)n_steps_prod << "%" << std::flush; } } std::cout << "\rRunning production, ...Done!"; std::cout << std::endl; std::cout << "Beta: " << beta << " Acceptance ratio: " << (double) N_ACCEPTED_FLIPS / (double) N_ATTEMPTED_FLIPS << std::endl; //write properties and final configuration to file write_properties(energies, outfile + ".autocorr"); write_energies(energies, outfile + ".energies"); write_configuration(lattice, outfile + ".conf"); }; <|endoftext|>
<commit_before>/** * @file Cosa/SPI.cpp * @version 1.0 * * @section License * Copyright (C) 2012-2015, Mikael Patel * * 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. * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/SPI.hh" #include "Cosa/Power.hh" // Configuration: Allow SPI transfer interleaving #if !defined(BOARD_ATTINY) #define USE_SPI_PREFETCH #endif SPI spi __attribute__ ((weak)); #if defined(SPDR) SPI::Driver::Driver(Board::DigitalPin cs, Pulse pulse, Clock rate, uint8_t mode, Order order, Interrupt::Handler* irq) : m_next(NULL), m_irq(irq), m_cs(cs, (pulse == 0)), m_pulse(pulse), // SPI Control Register for master mode m_spcr(_BV(SPE) | ((order & 0x1) << DORD) | _BV(MSTR) | ((mode & 0x3) << CPHA) | ((rate & 0x3) << SPR0)), // SPI Clock control in Status Register m_spsr(((rate & 0x04) != 0) << SPI2X) { } SPI::SPI(uint8_t mode, Order order) : m_list(NULL), m_dev(NULL), m_busy(false) { // Initiate the SPI port and control for slave mode synchronized { bit_set(DDRB, Board::MISO); bit_mask_clear(DDRB, _BV(Board::MOSI) | _BV(Board::SCK) | _BV(Board::SS)); SPCR = (_BV(SPIE) | _BV(SPE) | ((order & 0x1) << DORD) | ((mode & 0x3) << CPHA)); } } SPI::SPI() : m_list(NULL), m_dev(NULL), m_busy(false) { // Initiate the SPI data direction for master mode // The SPI/SS pin must be an output pin in master mode synchronized { bit_mask_set(DDRB, _BV(Board::MOSI) | _BV(Board::SCK) | _BV(Board::SS)); bit_clear(DDRB, Board::MISO); bit_mask_clear(PORTB, _BV(Board::SCK) | _BV(Board::MOSI)); bit_set(PORTB, Board::MISO); } // Other the SPI setup is done by the SPI::Driver::begin() } void SPI::Slave::on_interrupt(uint16_t arg) { // Sanity check that a buffer is defined if (m_buf == NULL) return; // Append to buffer and push event when buffer is full m_buf[m_put++] = arg; if (m_put != m_max) return; // Push receive completed to event dispatch Event::push(Event::RECEIVE_COMPLETED_TYPE, this, m_put); m_put = 0; } // Current slave device. Should be a singleton SPI::Slave* SPI::Slave::s_device = NULL; ISR(SPI_STC_vect) { SPI::Slave* device = SPI::Slave::s_device; if (device != NULL) device->on_interrupt(SPDR); } #elif defined(USIDR) // Create mapping to USI data direction register and port for ATtiny variants #if defined(BOARD_ATTINYX4) || defined(BOARD_ATTINYX61) #define DDR DDRA #define PORT PORTA #elif defined(BOARD_ATTINYX5) #define DDR DDRB #define PORT PORTB #endif SPI::Driver::Driver(Board::DigitalPin cs, Pulse pulse, Clock rate, uint8_t mode, Order order, Interrupt::Handler* irq) : m_next(NULL), m_irq(irq), m_cs(cs, (pulse == 0)), m_pulse(pulse), m_cpol(mode) { UNUSED(rate); UNUSED(order); // USI command for hardware supported bit banging m_usicr = (_BV(USIWM0) | _BV(USICS1) | _BV(USICLK) | _BV(USITC)); if (mode == 1 || mode == 2) m_usicr |= _BV(USICS0); // Set ports synchronized { bit_mask_set(DDR, _BV(Board::MOSI) | _BV(Board::SCK)); bit_clear(DDR, Board::MISO); bit_set(PORT, Board::MISO); USICR = m_usicr; } } SPI::SPI(uint8_t mode, Order order) : m_list(NULL), m_dev(NULL), m_busy(false) { UNUSED(order); // Set port data direction. Note ATtiny MOSI/MISO are DI/DO. // Do not confuse with SPI chip programming pins synchronized { bit_mask_set(DDR, _BV(Board::MOSI) | _BV(Board::SCK)); bit_clear(DDR, Board::MISO); bit_set(PORT, Board::MISO); USICR = (_BV(USIWM0) | _BV(USICS1) | _BV(USICLK) | _BV(USITC)); if (mode == 1 || mode == 2) USICR |= _BV(USICS0); } } SPI::SPI() : m_list(NULL), m_dev(NULL), m_busy(false) { // Set port data direction. Note ATtiny MOSI/MISO are DI/DO. // Do not confuse with SPI chip programming pins synchronized { bit_mask_set(DDR, _BV(Board::MOSI) | _BV(Board::SCK)); bit_clear(DDR, Board::MISO); bit_set(PORT, Board::MISO); } } #endif /* * Prefetch optimized variants of the block transfer member functions. * These implementation allow higher transfer speed for block by using * the available cycles while a byte transfer is in progress for data * prefetch and store. There are at least 16 instruction cycles available * (CLOCK_DIV_2). */ #if defined(USE_SPI_PREFETCH) void SPI::transfer(void* buf, size_t count) { if (count == 0) return; uint8_t* dp = (uint8_t*) buf; uint8_t data = *dp; transfer_start(data); while (--count) { uint8_t* tp = dp + 1; data = *tp; *dp = transfer_next(data); dp = tp; } *dp = transfer_await(); } void SPI::transfer(void* dst, const void* src, size_t count) { if (count == 0) return; uint8_t* dp = (uint8_t*) dst; const uint8_t* sp = (const uint8_t*) src; uint8_t data = *sp++; transfer_start(data); while (--count) { uint8_t* tp = dp + 1; data = *sp++; *dp = transfer_next(data); dp = tp; } *dp = transfer_await(); } void SPI::read(void* buf, size_t count) { if (count == 0) return; uint8_t* dp = (uint8_t*) buf; transfer_start(0xff); while (--count) *dp++ = transfer_next(0xff); *dp = transfer_await(); } void SPI::write(const void* buf, size_t count) { if (count == 0) return; const uint8_t* sp = (const uint8_t*) buf; uint8_t data = *sp++; transfer_start(data); while (--count) { data = *sp++; transfer_next(data); } transfer_await(); } void SPI::write_P(const void* buf, size_t count) { if (count == 0) return; const uint8_t* sp = (const uint8_t*) buf; uint8_t data = pgm_read_byte(sp++); transfer_start(data); while (--count) { data = pgm_read_byte(sp++); transfer_next(data); } transfer_await(); } #else void SPI::transfer(void* buf, size_t count) { if (count == 0) return; uint8_t* bp = (uint8_t*) buf; do { *bp = transfer(*bp); bp += 1; } while (--count); } void SPI::transfer(void* dst, const void* src, size_t count) { if (count == 0) return; uint8_t* dp = (uint8_t*) dst; const uint8_t* sp = (const uint8_t*) src; do *dp++ = transfer(*sp++); while (--count); } void SPI::read(void* buf, size_t count) { if (count == 0) return; uint8_t* bp = (uint8_t*) buf; do *bp++ = transfer(0); while (--count); } void SPI::write(const void* buf, size_t count) { if (count == 0) return; const uint8_t* bp = (const uint8_t*) buf; do transfer(*bp++); while (--count); } void SPI::write_P(const void* buf, size_t count) { if (count == 0) return; const uint8_t* bp = (const uint8_t*) buf; do transfer(pgm_read_byte(bp++)); while (--count); } #endif bool SPI::attach(Driver* dev) { if (dev->m_next != NULL) return (false); dev->m_next = m_list; m_list = dev; return (true); } void SPI::acquire(Driver* dev) { // Acquire the device driver. Wait if busy. Synchronized update uint8_t key = lock(); while (m_busy) { unlock(key); yield(); key = lock(); } // Set current device and mark as busy m_busy = true; m_dev = dev; #if defined(SPDR) // Initiate SPI hardware with device settings SPCR = dev->m_spcr; SPSR = dev->m_spsr; #else // Set clock polarity bit_write(dev->m_cpol & 0x02, PORT, Board::SCK); #endif // Disable all interrupt sources on SPI bus for (SPI::Driver* dev = m_list; dev != NULL; dev = dev->m_next) if (dev->m_irq != NULL) dev->m_irq->disable(); unlock(key); } void SPI::release() { // Lock the device driver update uint8_t key = lock(); // Release the device driver m_busy = false; m_dev = NULL; // Enable all interrupt sources on SPI bus for (SPI::Driver* dev = m_list; dev != NULL; dev = dev->m_next) if (dev->m_irq != NULL) dev->m_irq->enable(); unlock(key); } void SPI::Driver::set_clock(Clock rate) { #if defined(SPDR) m_spcr = (m_spcr & ~(0x3 << SPR0)) | ((rate & 0x3) << SPR0); m_spsr = (m_spsr & ~(1 << SPI2X)) | (((rate & 0x04) != 0) << SPI2X); #else UNUSED(rate); #endif } IOStream& operator<<(IOStream& outs, SPI::Clock rate) { switch (rate) { case SPI::DIV2_CLOCK: outs << PSTR("SPI::DIV2_CLOCK(") << F_CPU / 2000000.0; break; case SPI::DIV4_CLOCK: outs << PSTR("SPI::DIV4_CLOCK(") << F_CPU / 4000000.0; break; case SPI::DIV8_CLOCK: outs << PSTR("SPI::DIV8_CLOCK(") << F_CPU / 8000000.0; break; case SPI::DIV16_CLOCK: outs << PSTR("SPI::DIV16_CLOCK(") << F_CPU / 16000000.0; break; case SPI::DIV32_CLOCK: outs << PSTR("SPI::DIV32_CLOCK(") << F_CPU / 32000000.0; break; case SPI::DIV64_CLOCK: outs << PSTR("SPI::DIV64_CLOCK(") << F_CPU / 64000000.0; break; case SPI::DIV128_CLOCK: outs << PSTR("SPI::DIV128_CLOCK(") << F_CPU / 128000000.0; break; }; outs << PSTR(" MHz)"); return (outs); } <commit_msg>Fixed SPI::PULSE_LOW. Improved SPI performance evaluation sketch.<commit_after>/** * @file Cosa/SPI.cpp * @version 1.0 * * @section License * Copyright (C) 2012-2015, Mikael Patel * * 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. * * This file is part of the Arduino Che Cosa project. */ #include "Cosa/SPI.hh" #include "Cosa/Power.hh" // Configuration: Allow SPI transfer interleaving #if !defined(BOARD_ATTINY) #define USE_SPI_PREFETCH #endif SPI spi __attribute__ ((weak)); #if defined(SPDR) SPI::Driver::Driver(Board::DigitalPin cs, Pulse pulse, Clock rate, uint8_t mode, Order order, Interrupt::Handler* irq) : m_next(NULL), m_irq(irq), m_cs(cs, ((pulse & 0x01) == 0)), m_pulse(pulse), // SPI Control Register for master mode m_spcr(_BV(SPE) | ((order & 0x1) << DORD) | _BV(MSTR) | ((mode & 0x3) << CPHA) | ((rate & 0x3) << SPR0)), // SPI Clock control in Status Register m_spsr(((rate & 0x04) != 0) << SPI2X) { } SPI::SPI(uint8_t mode, Order order) : m_list(NULL), m_dev(NULL), m_busy(false) { // Initiate the SPI port and control for slave mode synchronized { bit_set(DDRB, Board::MISO); bit_mask_clear(DDRB, _BV(Board::MOSI) | _BV(Board::SCK) | _BV(Board::SS)); SPCR = (_BV(SPIE) | _BV(SPE) | ((order & 0x1) << DORD) | ((mode & 0x3) << CPHA)); } } SPI::SPI() : m_list(NULL), m_dev(NULL), m_busy(false) { // Initiate the SPI data direction for master mode // The SPI/SS pin must be an output pin in master mode synchronized { bit_mask_set(DDRB, _BV(Board::MOSI) | _BV(Board::SCK) | _BV(Board::SS)); bit_clear(DDRB, Board::MISO); bit_mask_clear(PORTB, _BV(Board::SCK) | _BV(Board::MOSI)); bit_set(PORTB, Board::MISO); } // Other the SPI setup is done by the SPI::Driver::begin() } void SPI::Slave::on_interrupt(uint16_t arg) { // Sanity check that a buffer is defined if (m_buf == NULL) return; // Append to buffer and push event when buffer is full m_buf[m_put++] = arg; if (m_put != m_max) return; // Push receive completed to event dispatch Event::push(Event::RECEIVE_COMPLETED_TYPE, this, m_put); m_put = 0; } // Current slave device. Should be a singleton SPI::Slave* SPI::Slave::s_device = NULL; ISR(SPI_STC_vect) { SPI::Slave* device = SPI::Slave::s_device; if (device != NULL) device->on_interrupt(SPDR); } #elif defined(USIDR) // Create mapping to USI data direction register and port for ATtiny variants #if defined(BOARD_ATTINYX4) || defined(BOARD_ATTINYX61) #define DDR DDRA #define PORT PORTA #elif defined(BOARD_ATTINYX5) #define DDR DDRB #define PORT PORTB #endif SPI::Driver::Driver(Board::DigitalPin cs, Pulse pulse, Clock rate, uint8_t mode, Order order, Interrupt::Handler* irq) : m_next(NULL), m_irq(irq), m_cs(cs, ((pulse & 0x01) == 0)), m_pulse(pulse), m_cpol(mode) { UNUSED(rate); UNUSED(order); // USI command for hardware supported bit banging m_usicr = (_BV(USIWM0) | _BV(USICS1) | _BV(USICLK) | _BV(USITC)); if (mode == 1 || mode == 2) m_usicr |= _BV(USICS0); // Set ports synchronized { bit_mask_set(DDR, _BV(Board::MOSI) | _BV(Board::SCK)); bit_clear(DDR, Board::MISO); bit_set(PORT, Board::MISO); USICR = m_usicr; } } SPI::SPI(uint8_t mode, Order order) : m_list(NULL), m_dev(NULL), m_busy(false) { UNUSED(order); // Set port data direction. Note ATtiny MOSI/MISO are DI/DO. // Do not confuse with SPI chip programming pins synchronized { bit_mask_set(DDR, _BV(Board::MOSI) | _BV(Board::SCK)); bit_clear(DDR, Board::MISO); bit_set(PORT, Board::MISO); USICR = (_BV(USIWM0) | _BV(USICS1) | _BV(USICLK) | _BV(USITC)); if (mode == 1 || mode == 2) USICR |= _BV(USICS0); } } SPI::SPI() : m_list(NULL), m_dev(NULL), m_busy(false) { // Set port data direction. Note ATtiny MOSI/MISO are DI/DO. // Do not confuse with SPI chip programming pins synchronized { bit_mask_set(DDR, _BV(Board::MOSI) | _BV(Board::SCK)); bit_clear(DDR, Board::MISO); bit_set(PORT, Board::MISO); } } #endif /* * Prefetch optimized variants of the block transfer member functions. * These implementation allow higher transfer speed for block by using * the available cycles while a byte transfer is in progress for data * prefetch and store. There are at least 16 instruction cycles available * (CLOCK_DIV_2). */ #if defined(USE_SPI_PREFETCH) void SPI::transfer(void* buf, size_t count) { if (count == 0) return; uint8_t* dp = (uint8_t*) buf; uint8_t data = *dp; transfer_start(data); while (--count) { uint8_t* tp = dp + 1; data = *tp; *dp = transfer_next(data); dp = tp; } *dp = transfer_await(); } void SPI::transfer(void* dst, const void* src, size_t count) { if (count == 0) return; uint8_t* dp = (uint8_t*) dst; const uint8_t* sp = (const uint8_t*) src; uint8_t data = *sp++; transfer_start(data); while (--count) { uint8_t* tp = dp + 1; data = *sp++; *dp = transfer_next(data); dp = tp; } *dp = transfer_await(); } void SPI::read(void* buf, size_t count) { if (count == 0) return; uint8_t* dp = (uint8_t*) buf; transfer_start(0xff); while (--count) *dp++ = transfer_next(0xff); *dp = transfer_await(); } void SPI::write(const void* buf, size_t count) { if (count == 0) return; const uint8_t* sp = (const uint8_t*) buf; uint8_t data = *sp++; transfer_start(data); while (--count) { data = *sp++; transfer_next(data); } transfer_await(); } void SPI::write_P(const void* buf, size_t count) { if (count == 0) return; const uint8_t* sp = (const uint8_t*) buf; uint8_t data = pgm_read_byte(sp++); transfer_start(data); while (--count) { data = pgm_read_byte(sp++); transfer_next(data); } transfer_await(); } #else void SPI::transfer(void* buf, size_t count) { if (count == 0) return; uint8_t* bp = (uint8_t*) buf; do { *bp = transfer(*bp); bp += 1; } while (--count); } void SPI::transfer(void* dst, const void* src, size_t count) { if (count == 0) return; uint8_t* dp = (uint8_t*) dst; const uint8_t* sp = (const uint8_t*) src; do *dp++ = transfer(*sp++); while (--count); } void SPI::read(void* buf, size_t count) { if (count == 0) return; uint8_t* bp = (uint8_t*) buf; do *bp++ = transfer(0); while (--count); } void SPI::write(const void* buf, size_t count) { if (count == 0) return; const uint8_t* bp = (const uint8_t*) buf; do transfer(*bp++); while (--count); } void SPI::write_P(const void* buf, size_t count) { if (count == 0) return; const uint8_t* bp = (const uint8_t*) buf; do transfer(pgm_read_byte(bp++)); while (--count); } #endif bool SPI::attach(Driver* dev) { if (dev->m_next != NULL) return (false); dev->m_next = m_list; m_list = dev; return (true); } void SPI::acquire(Driver* dev) { // Acquire the device driver. Wait if busy. Synchronized update uint8_t key = lock(); while (m_busy) { unlock(key); yield(); key = lock(); } // Set current device and mark as busy m_busy = true; m_dev = dev; #if defined(SPDR) // Initiate SPI hardware with device settings SPCR = dev->m_spcr; SPSR = dev->m_spsr; #else // Set clock polarity bit_write(dev->m_cpol & 0x02, PORT, Board::SCK); #endif // Disable all interrupt sources on SPI bus for (SPI::Driver* dev = m_list; dev != NULL; dev = dev->m_next) if (dev->m_irq != NULL) dev->m_irq->disable(); unlock(key); } void SPI::release() { // Lock the device driver update uint8_t key = lock(); // Release the device driver m_busy = false; m_dev = NULL; // Enable all interrupt sources on SPI bus for (SPI::Driver* dev = m_list; dev != NULL; dev = dev->m_next) if (dev->m_irq != NULL) dev->m_irq->enable(); unlock(key); } void SPI::Driver::set_clock(Clock rate) { #if defined(SPDR) m_spcr = (m_spcr & ~(0x3 << SPR0)) | ((rate & 0x3) << SPR0); m_spsr = (m_spsr & ~(1 << SPI2X)) | (((rate & 0x04) != 0) << SPI2X); #else UNUSED(rate); #endif } IOStream& operator<<(IOStream& outs, SPI::Clock rate) { switch (rate) { case SPI::DIV2_CLOCK: outs << PSTR("SPI::DIV2_CLOCK(") << F_CPU / 2000000.0; break; case SPI::DIV4_CLOCK: outs << PSTR("SPI::DIV4_CLOCK(") << F_CPU / 4000000.0; break; case SPI::DIV8_CLOCK: outs << PSTR("SPI::DIV8_CLOCK(") << F_CPU / 8000000.0; break; case SPI::DIV16_CLOCK: outs << PSTR("SPI::DIV16_CLOCK(") << F_CPU / 16000000.0; break; case SPI::DIV32_CLOCK: outs << PSTR("SPI::DIV32_CLOCK(") << F_CPU / 32000000.0; break; case SPI::DIV64_CLOCK: outs << PSTR("SPI::DIV64_CLOCK(") << F_CPU / 64000000.0; break; case SPI::DIV128_CLOCK: outs << PSTR("SPI::DIV128_CLOCK(") << F_CPU / 128000000.0; break; }; outs << PSTR(" MHz)"); return (outs); } <|endoftext|>
<commit_before>/** * @file * Lists and hashes * */ #include "angort.h" #include "hash.h" #include "opcodes.h" using namespace angort; namespace angort { struct RevStdComparator : public ArrayListComparator<Value> { Angort *ang; RevStdComparator(Angort *a){ ang = a; } virtual int compare(const Value *a, const Value *b){ // binop isn't const, sadly. ang->binop(const_cast<Value *>(b), const_cast<Value *>(a),OP_CMP); return ang->popInt(); } }; struct FuncComparator : public ArrayListComparator<Value> { Value *func; Angort *ang; FuncComparator(Angort *a,Value *f){ ang = a; func = f; } virtual int compare(const Value *a, const Value *b){ ang->pushval()->copy(a); ang->pushval()->copy(b); ang->runValue(func); return ang->popInt(); } }; } %name coll %word dumplist (list --) Dump a list { ArrayList<Value> *list = Types::tList->get(a->popval()); for(int i=0;i<list->count();i++){ const StringBuffer& s = list->get(i)->toString(); printf("%d: %s\n",i,s.get()); } } %word last (coll -- item/none) get last item { Value *c = a->stack.peekptr(); int n = c->t->getCount(c)-1; if(n<0) c->clr(); else { Value v,out; Types::tInteger->set(&v,n); c->t->getValue(c,&v,&out); c->copy(&out); } } inline void getByIndex(Value *c,int idx){ if(idx>=c->t->getCount(c)) c->clr(); else { Value v,out; Types::tInteger->set(&v,idx); c->t->getValue(c,&v,&out); c->copy(&out); } } %word explode ([x,y,z] -- z y x) put all items onto stack { Value *iterable = a->popval(); Iterator<Value *> *iter = iterable->t->makeIterator(iterable); for(iter->first();!iter->isDone();iter->next()){ a->pushval()->copy(iter->current()); } delete iter; } %word fst (coll -- item/none) get first item { getByIndex(a->stack.peekptr(),0); } %word snd (coll -- item/none) get second item { getByIndex(a->stack.peekptr(),1); } %word third (coll -- item/none) get second item { getByIndex(a->stack.peekptr(),2); } %word fourth (coll -- item/none) get second item { getByIndex(a->stack.peekptr(),3); } %word get (key coll --) get an item from a list or hash { Value *c = a->popval(); Value *keyAndResult = a->stack.peekptr(); Value v; c->t->getValue(c,keyAndResult,&v); keyAndResult->copy(&v); // copy into the key's slot } %word set (val key coll --) put an item into a list or hash { Value *c = a->popval(); Value *k = a->popval(); Value *v = a->popval(); c->t->setValue(c,k,v); } %word len (list --) get length of list, hash or string { Value *c = a->stack.peekptr(); int ct = c->t->getCount(c); Types::tInteger->set(c,ct); } %word remove (idx list -- item) remove an item by index, returning it { Value *c = a->popval(); Value *keyAndResult = a->stack.peekptr(); Value v; c->t->removeAndReturn(c,keyAndResult,&v); keyAndResult->copy(&v); // copy into the key's slot } %word shift (list -- item) remove and return the first item of the list { ArrayList<Value> *list = Types::tList->get(a->popval()); Value *v = a->pushval(); v->copy(list->get(0)); list->remove(0); } %word unshift (item list --) prepend an item to a list { ArrayList<Value> *list = Types::tList->get(a->popval()); Value *v = a->popval(); list->insert(0)->copy(v); } %word pop (list -- item) pop an item from the end of the list { ArrayList<Value> *list = Types::tList->get(a->popval()); Value *v = a->pushval(); Value *src = list->get(list->count()-1); v->copy(src); list->remove(list->count()-1); } %word push (item list --) append an item to a list { ArrayList<Value> *list = Types::tList->get(a->popval()); Value *v = a->popval(); list->append()->copy(v); } %word map (iter func -- list) apply a function to an iterable, giving a list { Value func; func.copy(a->popval()); // need a local copy Value *iterable = a->popval(); Iterator<Value *> *iter = iterable->t->makeIterator(iterable); ArrayList<Value> *list = Types::tList->set(a->pushval()); for(iter->first();!iter->isDone();iter->next()){ a->pushval()->copy(iter->current()); a->runValue(&func); Value *v = list->append(); v->copy(a->popval()); } delete iter; } %word reduce (start iter func -- result) perform a (left) fold or reduce on an iterable { Value func; func.copy(a->popval()); // need a local copy Value *iterable = a->popval(); Iterator<Value *> *iter = iterable->t->makeIterator(iterable); // accumulator is already on the stack for(iter->first();!iter->isDone();iter->next()){ a->pushval()->copy(iter->current()); // stack the iterator on top of the accum a->runValue(&func); // run the function, leaving the new accumulator } delete iter; } %word filter (iter func -- list) filter an iterable with a boolean function { Value func; func.copy(a->popval()); // need a local copy Value *iterable = a->popval(); Iterator<Value *> *iter = iterable->t->makeIterator(iterable); ArrayList<Value> *list = Types::tList->set(a->pushval()); for(iter->first();!iter->isDone();iter->next()){ a->pushval()->copy(iter->current()); a->runValue(&func); if(a->popval()->toInt()){ Value *v = list->append(); v->copy(iter->current()); } } delete iter; } %word in (item iterable -- bool) return if item is in list or hash keys { Value *iterable = a->popval(); Value *item = a->popval(); a->pushInt(iterable->t->isIn(iterable,item)?true:false); } %word slice (start len iterable -- iterable) produce a slice of a string or list { Value *iterable = a->popval(); int len = a->popInt(); int start = a->popInt(); Value *res = a->pushval(); iterable->t->slice(res,iterable,start,len); } %word clone (in -- out) construct a shallow copy of a collection { Value *v = a->stack.peekptr(); v->t->clone(v,v,false); } %word deepclone (in -- out) produce a deep copy of a value { Value *v = a->stack.peekptr(); v->t->clone(v,v,true); } struct StdComparator : public ArrayListComparator<Value> { Angort *ang; StdComparator(Angort *a){ ang = a; } virtual int compare(const Value *a, const Value *b){ // binop isn't const, sadly. ang->binop(const_cast<Value *>(a), const_cast<Value *>(b),OP_CMP); return ang->popInt(); } }; %word sort (in --) sort a list in place using default comparator { Value listv; // need copy because comparators use the stack listv.copy(a->popval()); ArrayList<Value> *list = Types::tList->get(&listv); StdComparator cmp(a); list->sort(&cmp); } %word rsort (in --) reverse sort a list in place using default comparator { Value listv; // need copy because comparators use the stack listv.copy(a->popval()); ArrayList<Value> *list = Types::tList->get(&listv); RevStdComparator cmp(a); list->sort(&cmp); } %word fsort (in func --) sort a list in place using function comparator { Value func,listv; // need copies because comparators use the stack func.copy(a->popval()); listv.copy(a->popval()); ArrayList<Value> *list = Types::tList->get(&listv); FuncComparator cmp(a,&func); list->sort(&cmp); } %word all (in func --) true if the function returns true for all items { int rv=1; // true by default Value func; func.copy(a->popval()); // need a local copy Value *iterable = a->popval(); Iterator<Value *> *iter = iterable->t->makeIterator(iterable); for(iter->first();!iter->isDone();iter->next()){ a->pushval()->copy(iter->current()); // stack the iterator on top of the accum a->runValue(&func); // run the function if(!a->popInt()){ rv = 0; break; } } a->pushInt(rv); delete iter; } %word any (in func --) true if the function returns true for all items { int rv=0; // false by default Value func; func.copy(a->popval()); // need a local copy Value *iterable = a->popval(); Iterator<Value *> *iter = iterable->t->makeIterator(iterable); for(iter->first();!iter->isDone();iter->next()){ a->pushval()->copy(iter->current()); // stack the iterator on top of the accum a->runValue(&func); // run the function if(a->popInt()){ rv = 1; break; } } a->pushInt(rv); delete iter; } %word zipWith (in1 in2 func -- out) apply binary func to pairs of items in list { Value *p[3]; a->popParams(p,"llc"); Iterator<Value *> *iter1 = p[0]->t->makeIterator(p[0]); Iterator<Value *> *iter2 = p[1]->t->makeIterator(p[1]); Value func; func.copy(p[2]); // need a local copy ArrayList<Value> *list = Types::tList->set(a->pushval()); for(iter1->first(),iter2->first(); !(iter1->isDone() || iter2->isDone()); iter1->next(),iter2->next()){ a->pushval()->copy(iter1->current()); a->pushval()->copy(iter2->current()); a->runValue(&func); list->append()->copy(a->popval()); } delete iter1; delete iter2; } %word reverse (iter -- list) reverse an iterable to return a list { Value *p = a->popval(); Iterator<Value *> *iter = p->t->makeIterator(p); // new list ArrayList<Value> *list = Types::tList->set(a->pushval()); // quickest thing to do is count the items by hand. This // could be optimised if we knew the input iterable was a list. int n=0; for(iter->first();!iter->isDone();iter->next()){n++;} int i=n; for(iter->first();!iter->isDone();iter->next()){ Value *v = iter->current(); list->set(--i,v); } delete iter; } %word intercalate (iter string -- string) turn elements of collection into string and intercalate with a separator { Value *p[2]; a->popParams(p,"vv"); // can be any type Value *v = p[0]; Iterator<Value *> *iter = v->t->makeIterator(v); const StringBuffer& s = p[1]->toString(); const char *sep = s.get(); int seplen = strlen(sep); int count = v->t->getCount(v); // first pass to get the lengths int len=0; int n=0; for(n=0,iter->first();!iter->isDone();iter->next(),n++){ len += strlen(iter->current()->toString().get()); if(n!=count-1) len += seplen; } // allocate the result in a new string value on the stack char *out = Types::tString->allocate(a->pushval(),len+1,Types::tString); // second pass to write the value *out = 0; for(n=0,iter->first();!iter->isDone();iter->next(),n++){ const StringBuffer& b = iter->current()->toString(); strcpy(out,b.get()); out += strlen(b.get()); if(n!=count-1){ strcpy(out,sep); out+=seplen; } } } <commit_msg>Delete iterator in intercalate.<commit_after>/** * @file * Lists and hashes * */ #include "angort.h" #include "hash.h" #include "opcodes.h" using namespace angort; namespace angort { struct RevStdComparator : public ArrayListComparator<Value> { Angort *ang; RevStdComparator(Angort *a){ ang = a; } virtual int compare(const Value *a, const Value *b){ // binop isn't const, sadly. ang->binop(const_cast<Value *>(b), const_cast<Value *>(a),OP_CMP); return ang->popInt(); } }; struct FuncComparator : public ArrayListComparator<Value> { Value *func; Angort *ang; FuncComparator(Angort *a,Value *f){ ang = a; func = f; } virtual int compare(const Value *a, const Value *b){ ang->pushval()->copy(a); ang->pushval()->copy(b); ang->runValue(func); return ang->popInt(); } }; } %name coll %word dumplist (list --) Dump a list { ArrayList<Value> *list = Types::tList->get(a->popval()); for(int i=0;i<list->count();i++){ const StringBuffer& s = list->get(i)->toString(); printf("%d: %s\n",i,s.get()); } } %word last (coll -- item/none) get last item { Value *c = a->stack.peekptr(); int n = c->t->getCount(c)-1; if(n<0) c->clr(); else { Value v,out; Types::tInteger->set(&v,n); c->t->getValue(c,&v,&out); c->copy(&out); } } inline void getByIndex(Value *c,int idx){ if(idx>=c->t->getCount(c)) c->clr(); else { Value v,out; Types::tInteger->set(&v,idx); c->t->getValue(c,&v,&out); c->copy(&out); } } %word explode ([x,y,z] -- z y x) put all items onto stack { Value *iterable = a->popval(); Iterator<Value *> *iter = iterable->t->makeIterator(iterable); for(iter->first();!iter->isDone();iter->next()){ a->pushval()->copy(iter->current()); } delete iter; } %word fst (coll -- item/none) get first item { getByIndex(a->stack.peekptr(),0); } %word snd (coll -- item/none) get second item { getByIndex(a->stack.peekptr(),1); } %word third (coll -- item/none) get second item { getByIndex(a->stack.peekptr(),2); } %word fourth (coll -- item/none) get second item { getByIndex(a->stack.peekptr(),3); } %word get (key coll --) get an item from a list or hash { Value *c = a->popval(); Value *keyAndResult = a->stack.peekptr(); Value v; c->t->getValue(c,keyAndResult,&v); keyAndResult->copy(&v); // copy into the key's slot } %word set (val key coll --) put an item into a list or hash { Value *c = a->popval(); Value *k = a->popval(); Value *v = a->popval(); c->t->setValue(c,k,v); } %word len (list --) get length of list, hash or string { Value *c = a->stack.peekptr(); int ct = c->t->getCount(c); Types::tInteger->set(c,ct); } %word remove (idx list -- item) remove an item by index, returning it { Value *c = a->popval(); Value *keyAndResult = a->stack.peekptr(); Value v; c->t->removeAndReturn(c,keyAndResult,&v); keyAndResult->copy(&v); // copy into the key's slot } %word shift (list -- item) remove and return the first item of the list { ArrayList<Value> *list = Types::tList->get(a->popval()); Value *v = a->pushval(); v->copy(list->get(0)); list->remove(0); } %word unshift (item list --) prepend an item to a list { ArrayList<Value> *list = Types::tList->get(a->popval()); Value *v = a->popval(); list->insert(0)->copy(v); } %word pop (list -- item) pop an item from the end of the list { ArrayList<Value> *list = Types::tList->get(a->popval()); Value *v = a->pushval(); Value *src = list->get(list->count()-1); v->copy(src); list->remove(list->count()-1); } %word push (item list --) append an item to a list { ArrayList<Value> *list = Types::tList->get(a->popval()); Value *v = a->popval(); list->append()->copy(v); } %word map (iter func -- list) apply a function to an iterable, giving a list { Value func; func.copy(a->popval()); // need a local copy Value *iterable = a->popval(); Iterator<Value *> *iter = iterable->t->makeIterator(iterable); ArrayList<Value> *list = Types::tList->set(a->pushval()); for(iter->first();!iter->isDone();iter->next()){ a->pushval()->copy(iter->current()); a->runValue(&func); Value *v = list->append(); v->copy(a->popval()); } delete iter; } %word reduce (start iter func -- result) perform a (left) fold or reduce on an iterable { Value func; func.copy(a->popval()); // need a local copy Value *iterable = a->popval(); Iterator<Value *> *iter = iterable->t->makeIterator(iterable); // accumulator is already on the stack for(iter->first();!iter->isDone();iter->next()){ a->pushval()->copy(iter->current()); // stack the iterator on top of the accum a->runValue(&func); // run the function, leaving the new accumulator } delete iter; } %word filter (iter func -- list) filter an iterable with a boolean function { Value func; func.copy(a->popval()); // need a local copy Value *iterable = a->popval(); Iterator<Value *> *iter = iterable->t->makeIterator(iterable); ArrayList<Value> *list = Types::tList->set(a->pushval()); for(iter->first();!iter->isDone();iter->next()){ a->pushval()->copy(iter->current()); a->runValue(&func); if(a->popval()->toInt()){ Value *v = list->append(); v->copy(iter->current()); } } delete iter; } %word in (item iterable -- bool) return if item is in list or hash keys { Value *iterable = a->popval(); Value *item = a->popval(); a->pushInt(iterable->t->isIn(iterable,item)?true:false); } %word slice (start len iterable -- iterable) produce a slice of a string or list { Value *iterable = a->popval(); int len = a->popInt(); int start = a->popInt(); Value *res = a->pushval(); iterable->t->slice(res,iterable,start,len); } %word clone (in -- out) construct a shallow copy of a collection { Value *v = a->stack.peekptr(); v->t->clone(v,v,false); } %word deepclone (in -- out) produce a deep copy of a value { Value *v = a->stack.peekptr(); v->t->clone(v,v,true); } struct StdComparator : public ArrayListComparator<Value> { Angort *ang; StdComparator(Angort *a){ ang = a; } virtual int compare(const Value *a, const Value *b){ // binop isn't const, sadly. ang->binop(const_cast<Value *>(a), const_cast<Value *>(b),OP_CMP); return ang->popInt(); } }; %word sort (in --) sort a list in place using default comparator { Value listv; // need copy because comparators use the stack listv.copy(a->popval()); ArrayList<Value> *list = Types::tList->get(&listv); StdComparator cmp(a); list->sort(&cmp); } %word rsort (in --) reverse sort a list in place using default comparator { Value listv; // need copy because comparators use the stack listv.copy(a->popval()); ArrayList<Value> *list = Types::tList->get(&listv); RevStdComparator cmp(a); list->sort(&cmp); } %word fsort (in func --) sort a list in place using function comparator { Value func,listv; // need copies because comparators use the stack func.copy(a->popval()); listv.copy(a->popval()); ArrayList<Value> *list = Types::tList->get(&listv); FuncComparator cmp(a,&func); list->sort(&cmp); } %word all (in func --) true if the function returns true for all items { int rv=1; // true by default Value func; func.copy(a->popval()); // need a local copy Value *iterable = a->popval(); Iterator<Value *> *iter = iterable->t->makeIterator(iterable); for(iter->first();!iter->isDone();iter->next()){ a->pushval()->copy(iter->current()); // stack the iterator on top of the accum a->runValue(&func); // run the function if(!a->popInt()){ rv = 0; break; } } a->pushInt(rv); delete iter; } %word any (in func --) true if the function returns true for all items { int rv=0; // false by default Value func; func.copy(a->popval()); // need a local copy Value *iterable = a->popval(); Iterator<Value *> *iter = iterable->t->makeIterator(iterable); for(iter->first();!iter->isDone();iter->next()){ a->pushval()->copy(iter->current()); // stack the iterator on top of the accum a->runValue(&func); // run the function if(a->popInt()){ rv = 1; break; } } a->pushInt(rv); delete iter; } %word zipWith (in1 in2 func -- out) apply binary func to pairs of items in list { Value *p[3]; a->popParams(p,"llc"); Iterator<Value *> *iter1 = p[0]->t->makeIterator(p[0]); Iterator<Value *> *iter2 = p[1]->t->makeIterator(p[1]); Value func; func.copy(p[2]); // need a local copy ArrayList<Value> *list = Types::tList->set(a->pushval()); for(iter1->first(),iter2->first(); !(iter1->isDone() || iter2->isDone()); iter1->next(),iter2->next()){ a->pushval()->copy(iter1->current()); a->pushval()->copy(iter2->current()); a->runValue(&func); list->append()->copy(a->popval()); } delete iter1; delete iter2; } %word reverse (iter -- list) reverse an iterable to return a list { Value *p = a->popval(); Iterator<Value *> *iter = p->t->makeIterator(p); // new list ArrayList<Value> *list = Types::tList->set(a->pushval()); // quickest thing to do is count the items by hand. This // could be optimised if we knew the input iterable was a list. int n=0; for(iter->first();!iter->isDone();iter->next()){n++;} int i=n; for(iter->first();!iter->isDone();iter->next()){ Value *v = iter->current(); list->set(--i,v); } delete iter; } %word intercalate (iter string -- string) turn elements of collection into string and intercalate with a separator { Value *p[2]; a->popParams(p,"vv"); // can be any type Value *v = p[0]; Iterator<Value *> *iter = v->t->makeIterator(v); const StringBuffer& s = p[1]->toString(); const char *sep = s.get(); int seplen = strlen(sep); int count = v->t->getCount(v); // first pass to get the lengths int len=0; int n=0; for(n=0,iter->first();!iter->isDone();iter->next(),n++){ len += strlen(iter->current()->toString().get()); if(n!=count-1) len += seplen; } // allocate the result in a new string value on the stack char *out = Types::tString->allocate(a->pushval(),len+1,Types::tString); // second pass to write the value *out = 0; for(n=0,iter->first();!iter->isDone();iter->next(),n++){ const StringBuffer& b = iter->current()->toString(); strcpy(out,b.get()); out += strlen(b.get()); if(n!=count-1){ strcpy(out,sep); out+=seplen; } } delete iter; } <|endoftext|>
<commit_before>/*************************************************************************** * Copyright (C) 2006 by Ingo Kloecker <kloecker@kde.org> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "create.h" #include <QtCore/QDebug> #include <QtCore/QStringList> #include "akonadi.h" #include "akonadiconnection.h" #include "storage/datastore.h" #include "storage/entity.h" #include "storage/transaction.h" #include "handlerhelper.h" #include "storage/selectquerybuilder.h" #include "response.h" #include "libs/imapparser_p.h" #include "imapstreamparser.h" using namespace Akonadi; Create::Create( Scope::SelectionScope scope ) : Handler(), m_scope( scope ) { } bool Create::parseStream() { QString name = m_streamParser->readUtf8String(); if ( name.isEmpty() ) return failureResponse( "Invalid collection name" ); bool ok = false; Collection parent; if ( m_scope == Scope::Uid || m_scope == Scope::None ) { qint64 parentId = m_streamParser->readNumber( &ok ); if ( !ok ) { // RFC 3501 compat QString parentPath; int index = name.lastIndexOf( QLatin1Char('/') ); if ( index > 0 ) { parentPath = name.left( index ); name = name.mid( index + 1 ); parent = HandlerHelper::collectionFromIdOrName( parentPath.toUtf8() ); } else parentId = 0; } else { if ( parentId > 0 ) parent = Collection::retrieveById( parentId ); } if ( parentId != 0 && !parent.isValid() ) return failureResponse( "Parent collection not found" ); } else if ( m_scope == Scope::Rid ) { const QString rid = m_streamParser->readUtf8String(); if ( rid.isEmpty() ) throw HandlerException( "Empty parent remote identifier" ); if ( !connection()->resourceContext().isValid() ) throw HandlerException( "Invalid resource context" ); SelectQueryBuilder<Collection> qb; qb.addValueCondition( Collection::remoteIdColumn(), Query::Equals, rid ); qb.addValueCondition( Collection::resourceIdColumn(), Query::Equals, connection()->resourceContext().id() ); if ( !qb.exec() ) throw HandlerException( "Unable to execute collection query" ); const Collection::List cols = qb.result(); if ( cols.size() == 0 ) throw HandlerException( "Parent collection not found" ); else if ( cols.size() > 1 ) throw HandlerException( "Parent collection is not unique" ); parent = cols.first(); } qint64 resourceId = 0; MimeType::List parentContentTypes; if ( parent.isValid() ) { // check if parent can contain a sub-folder parentContentTypes = parent.mimeTypes(); bool found = false; foreach ( const MimeType &mt, parentContentTypes ) { if ( mt.name() == QLatin1String( "inode/directory" ) ) { found = true; break; } } if ( !found ) return failureResponse( "Parent collection can not contain sub-collections" ); // inherit resource resourceId = parent.resourceId(); } else { // deduce owning resource from current session id QString sessionId = QString::fromUtf8( connection()->sessionId() ); Resource res = Resource::retrieveByName( sessionId ); if ( !res.isValid() ) return failureResponse( "Cannot create top-level collection" ); resourceId = res.id(); } Collection collection; if ( parent.isValid() ) collection.setParentId( parent.id() ); collection.setName( name ); collection.setResourceId( resourceId ); // attributes QList<QByteArray> attributes; QList<QByteArray> mimeTypes; QVector< QPair<QByteArray, QByteArray> > userDefAttrs; bool mimeTypesSet = false; attributes = m_streamParser->readParenthesizedList(); for ( int i = 0; i < attributes.count() - 1; i += 2 ) { const QByteArray key = attributes.at( i ); const QByteArray value = attributes.at( i + 1 ); if ( key == "REMOTEID" ) { collection.setRemoteId( QString::fromUtf8( value ) ); } else if ( key == "REMOTEREVISION" ) { collection.setRemoteRevision( QString::fromUtf8( value ) ); } else if ( key == "MIMETYPE" ) { ImapParser::parseParenthesizedList( value, mimeTypes ); mimeTypesSet = true; } else if ( key == "CACHEPOLICY" ) { HandlerHelper::parseCachePolicy( value, collection ); } else { userDefAttrs << qMakePair( key, value ); } } DataStore *db = connection()->storageBackend(); Transaction transaction( db ); if ( !db->appendCollection( collection ) ) return failureResponse( "Could not create collection" ); QStringList effectiveMimeTypes; if ( mimeTypesSet ) { foreach ( const QByteArray &b, mimeTypes ) effectiveMimeTypes << QString::fromUtf8( b ); } else { foreach ( const MimeType &mt, parentContentTypes ) effectiveMimeTypes << mt.name(); } if ( !db->appendMimeTypeForCollection( collection.id(), effectiveMimeTypes ) ) return failureResponse( "Unable to append mimetype for collection." ); // store user defined attributes typedef QPair<QByteArray,QByteArray> QByteArrayPair; foreach ( const QByteArrayPair &attr, userDefAttrs ) { if ( !db->addCollectionAttribute( collection, attr.first, attr.second ) ) return failureResponse( "Unable to add collection attribute." ); } Response response; response.setUntagged(); // write out collection details db->activeCachePolicy( collection ); const QByteArray b = HandlerHelper::collectionToByteArray( collection ); response.setString( b ); emit responseAvailable( response ); if ( !transaction.commit() ) return failureResponse( "Unable to commit transaction." ); return successResponse( "CREATE completed" ); } #include "create.moc" <commit_msg>More precise error messages<commit_after>/*************************************************************************** * Copyright (C) 2006 by Ingo Kloecker <kloecker@kde.org> * * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU Library General Public License as * * published by the Free Software Foundation; either version 2 of the * * License, or (at your option) any later version. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU Library General Public * * License along with this program; if not, write to the * * Free Software Foundation, Inc., * * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #include "create.h" #include <QtCore/QDebug> #include <QtCore/QStringList> #include "akonadi.h" #include "akonadiconnection.h" #include "storage/datastore.h" #include "storage/entity.h" #include "storage/transaction.h" #include "handlerhelper.h" #include "storage/selectquerybuilder.h" #include "response.h" #include "libs/imapparser_p.h" #include "imapstreamparser.h" using namespace Akonadi; Create::Create( Scope::SelectionScope scope ) : Handler(), m_scope( scope ) { } bool Create::parseStream() { QString name = m_streamParser->readUtf8String(); if ( name.isEmpty() ) return failureResponse( "Invalid collection name" ); bool ok = false; Collection parent; if ( m_scope == Scope::Uid || m_scope == Scope::None ) { qint64 parentId = m_streamParser->readNumber( &ok ); if ( !ok ) { // RFC 3501 compat QString parentPath; int index = name.lastIndexOf( QLatin1Char('/') ); if ( index > 0 ) { parentPath = name.left( index ); name = name.mid( index + 1 ); parent = HandlerHelper::collectionFromIdOrName( parentPath.toUtf8() ); } else parentId = 0; } else { if ( parentId > 0 ) parent = Collection::retrieveById( parentId ); } if ( parentId != 0 && !parent.isValid() ) return failureResponse( "Parent collection not found" ); } else if ( m_scope == Scope::Rid ) { const QString rid = m_streamParser->readUtf8String(); if ( rid.isEmpty() ) throw HandlerException( "Empty parent remote identifier" ); if ( !connection()->resourceContext().isValid() ) throw HandlerException( "Invalid resource context" ); SelectQueryBuilder<Collection> qb; qb.addValueCondition( Collection::remoteIdColumn(), Query::Equals, rid ); qb.addValueCondition( Collection::resourceIdColumn(), Query::Equals, connection()->resourceContext().id() ); if ( !qb.exec() ) throw HandlerException( "Unable to execute collection query" ); const Collection::List cols = qb.result(); if ( cols.size() == 0 ) throw HandlerException( "Parent collection not found" ); else if ( cols.size() > 1 ) throw HandlerException( "Parent collection is not unique" ); parent = cols.first(); } qint64 resourceId = 0; MimeType::List parentContentTypes; if ( parent.isValid() ) { // check if parent can contain a sub-folder parentContentTypes = parent.mimeTypes(); bool found = false; foreach ( const MimeType &mt, parentContentTypes ) { if ( mt.name() == QLatin1String( "inode/directory" ) ) { found = true; break; } } if ( !found ) return failureResponse( "Parent collection can not contain sub-collections" ); // inherit resource resourceId = parent.resourceId(); } else { // deduce owning resource from current session id QString sessionId = QString::fromUtf8( connection()->sessionId() ); Resource res = Resource::retrieveByName( sessionId ); if ( !res.isValid() ) return failureResponse( "Cannot create top-level collection" ); resourceId = res.id(); } Collection collection; if ( parent.isValid() ) collection.setParentId( parent.id() ); collection.setName( name ); collection.setResourceId( resourceId ); // attributes QList<QByteArray> attributes; QList<QByteArray> mimeTypes; QVector< QPair<QByteArray, QByteArray> > userDefAttrs; bool mimeTypesSet = false; attributes = m_streamParser->readParenthesizedList(); for ( int i = 0; i < attributes.count() - 1; i += 2 ) { const QByteArray key = attributes.at( i ); const QByteArray value = attributes.at( i + 1 ); if ( key == "REMOTEID" ) { collection.setRemoteId( QString::fromUtf8( value ) ); } else if ( key == "REMOTEREVISION" ) { collection.setRemoteRevision( QString::fromUtf8( value ) ); } else if ( key == "MIMETYPE" ) { ImapParser::parseParenthesizedList( value, mimeTypes ); mimeTypesSet = true; } else if ( key == "CACHEPOLICY" ) { HandlerHelper::parseCachePolicy( value, collection ); } else { userDefAttrs << qMakePair( key, value ); } } DataStore *db = connection()->storageBackend(); Transaction transaction( db ); if ( !db->appendCollection( collection ) ) return failureResponse( "Could not create collection " + name.toLatin1() + " resourceId: " + QByteArray::number(resourceId)); QStringList effectiveMimeTypes; if ( mimeTypesSet ) { foreach ( const QByteArray &b, mimeTypes ) effectiveMimeTypes << QString::fromUtf8( b ); } else { foreach ( const MimeType &mt, parentContentTypes ) effectiveMimeTypes << mt.name(); } if ( !db->appendMimeTypeForCollection( collection.id(), effectiveMimeTypes ) ) return failureResponse( "Unable to append mimetype for collection " + name.toLatin1() + " resourceId: " + QByteArray::number(resourceId) ); // store user defined attributes typedef QPair<QByteArray,QByteArray> QByteArrayPair; foreach ( const QByteArrayPair &attr, userDefAttrs ) { if ( !db->addCollectionAttribute( collection, attr.first, attr.second ) ) return failureResponse( "Unable to add collection attribute." ); } Response response; response.setUntagged(); // write out collection details db->activeCachePolicy( collection ); const QByteArray b = HandlerHelper::collectionToByteArray( collection ); response.setString( b ); emit responseAvailable( response ); if ( !transaction.commit() ) return failureResponse( "Unable to commit transaction." ); return successResponse( "CREATE completed" ); } #include "create.moc" <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2016 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include "meshrenderprocessorgl.h" #include <modules/opengl/geometry/meshgl.h> #include <inviwo/core/datastructures/buffer/bufferramprecision.h> #include <inviwo/core/interaction/trackball.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/rendering/meshdrawerfactory.h> #include <modules/opengl/rendering/meshdrawergl.h> #include <inviwo/core/processors/processor.h> #include <modules/opengl/shader/shader.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/openglutils.h> #include <limits> namespace inviwo { const ProcessorInfo MeshRenderProcessorGL::processorInfo_{ "org.inviwo.GeometryRenderGL", // Class identifier "Mesh Renderer", // Display name "Mesh Rendering", // Category CodeState::Stable, // Code state Tags::GL, // Tags }; const ProcessorInfo MeshRenderProcessorGL::getProcessorInfo() const { return processorInfo_; } MeshRenderProcessorGL::MeshRenderProcessorGL() : Processor() , inport_("geometry") , imageInport_("imageInport") , outport_("image") , camera_("camera", "Camera") , centerViewOnGeometry_("centerView", "Center view on geometry") , setNearFarPlane_("setNearFarPlane", "Calculate Near and Far Plane") , resetViewParams_("resetView", "Reset Camera") , trackball_(&camera_) , overrideColorBuffer_("overrideColorBuffer", "Override Color Buffer", false, InvalidationLevel::InvalidResources) , overrideColor_("overrideColor", "Override Color", vec4(0.75f, 0.75f, 0.75f, 1.0f), vec4(0.0f), vec4(1.0f)) , geomProperties_("geometry", "Geometry Rendering Properties") , cullFace_("cullFace", "Cull Face") , polygonMode_("polygonMode", "Polygon Mode") , renderPointSize_("renderPointSize", "Point Size", 1.0f, 0.001f, 15.0f, 0.001f) , renderLineWidth_("renderLineWidth", "Line Width", 1.0f, 0.001f, 15.0f, 0.001f) , enableDepthTest_("enableDepthTest_","Enable Depth Test" , true) , lightingProperty_("lighting", "Lighting", &camera_) , layers_("layers", "Output Layers") , colorLayer_("colorLayer", "Color", true, InvalidationLevel::InvalidResources) , texCoordLayer_("texCoordLayer", "Texture Coordinates", false, InvalidationLevel::InvalidResources) , normalsLayer_("normalsLayer", "Normals (World Space)", false, InvalidationLevel::InvalidResources) , viewNormalsLayer_("viewNormalsLayer", "Normals (View space)", false, InvalidationLevel::InvalidResources) , shader_("geometryrendering.vert", "geometryrendering.frag", false) { addPort(inport_); addPort(imageInport_); addPort(outport_); imageInport_.setOptional(true); addProperty(camera_); centerViewOnGeometry_.onChange(this, &MeshRenderProcessorGL::centerViewOnGeometry); addProperty(centerViewOnGeometry_); setNearFarPlane_.onChange(this, &MeshRenderProcessorGL::setNearFarPlane); addProperty(setNearFarPlane_); resetViewParams_.onChange([this]() { camera_.resetCamera(); }); addProperty(resetViewParams_); outport_.addResizeEventListener(&camera_); inport_.onChange(this, &MeshRenderProcessorGL::updateDrawers); cullFace_.addOption("culldisable", "Disable", GL_NONE); cullFace_.addOption("cullfront", "Front", GL_FRONT); cullFace_.addOption("cullback", "Back", GL_BACK); cullFace_.addOption("cullfrontback", "Front & Back", GL_FRONT_AND_BACK); cullFace_.set(GL_NONE); polygonMode_.addOption("polypoint", "Points", GL_POINT); polygonMode_.addOption("polyline", "Lines", GL_LINE); polygonMode_.addOption("polyfill", "Fill", GL_FILL); polygonMode_.set(GL_FILL); polygonMode_.onChange(this, &MeshRenderProcessorGL::changeRenderMode); geomProperties_.addProperty(cullFace_); geomProperties_.addProperty(polygonMode_); geomProperties_.addProperty(renderPointSize_); geomProperties_.addProperty(renderLineWidth_); geomProperties_.addProperty(enableDepthTest_); geomProperties_.addProperty(overrideColorBuffer_); geomProperties_.addProperty(overrideColor_); overrideColor_.setSemantics(PropertySemantics::Color); overrideColor_.setVisible(false); overrideColorBuffer_.onChange([&]() { overrideColor_.setVisible(overrideColorBuffer_.get()); }); float lineWidthRange[2]; float increment; glGetFloatv(GL_LINE_WIDTH_RANGE, lineWidthRange); glGetFloatv(GL_LINE_WIDTH_GRANULARITY, &increment); renderLineWidth_.setMinValue(lineWidthRange[0]); renderLineWidth_.setMaxValue(lineWidthRange[1]); renderLineWidth_.setIncrement(increment); renderLineWidth_.setVisible(false); renderPointSize_.setVisible(false); addProperty(geomProperties_); addProperty(lightingProperty_); addProperty(trackball_); addProperty(layers_); layers_.addProperty(colorLayer_); layers_.addProperty(texCoordLayer_); layers_.addProperty(normalsLayer_); layers_.addProperty(viewNormalsLayer_); setAllPropertiesCurrentStateAsDefault(); } MeshRenderProcessorGL::~MeshRenderProcessorGL() {} void MeshRenderProcessorGL::initializeResources() { addCommonShaderDefines(shader_); } void MeshRenderProcessorGL::addCommonShaderDefines(Shader& shader) { // shading defines utilgl::addShaderDefines(shader, lightingProperty_); if (overrideColorBuffer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("OVERRIDE_COLOR_BUFFER"); } else { shader.getFragmentShaderObject()->removeShaderDefine("OVERRIDE_COLOR_BUFFER"); } if (colorLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("COLOR_LAYER"); } else { shader.getFragmentShaderObject()->removeShaderDefine("COLOR_LAYER"); } // first two layers (color and picking) are reserved, but picking buffer will be removed since it is not drawn to int layerID = 1; if (texCoordLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("TEXCOORD_LAYER"); shader.getFragmentShaderObject()->addOutDeclaration("tex_coord_out", layerID); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("TEXCOORD_LAYER"); } if (normalsLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("NORMALS_LAYER"); shader.getFragmentShaderObject()->addOutDeclaration("normals_out", layerID); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("NORMALS_LAYER"); } if (viewNormalsLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("VIEW_NORMALS_LAYER"); shader.getFragmentShaderObject()->addOutDeclaration("view_normals_out", layerID); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("VIEW_NORMALS_LAYER"); } // get a hold of the current output data auto prevData = outport_.getData(); auto numLayers = static_cast<std::size_t>(layerID); if (prevData->getNumberOfColorLayers() != numLayers) { // create new image with matching number of layers auto image = std::make_shared<Image>(prevData->getDimensions(), prevData->getDataFormat()); // update number of layers for (auto i = image->getNumberOfColorLayers(); i < numLayers; ++i) { image->addColorLayer(std::shared_ptr<Layer>(image->getColorLayer(0)->clone())); } outport_.setData(image); } shader.build(); } void MeshRenderProcessorGL::changeRenderMode() { switch (polygonMode_.get()) { case GL_FILL: { renderLineWidth_.setVisible(false); renderPointSize_.setVisible(false); break; } case GL_LINE: { renderLineWidth_.setVisible(true); renderPointSize_.setVisible(false); break; } case GL_POINT: { renderLineWidth_.setVisible(false); renderPointSize_.setVisible(true); break; } } } void MeshRenderProcessorGL::process() { if (imageInport_.isConnected()) { utilgl::activateTargetAndCopySource(outport_, imageInport_); } else { utilgl::activateAndClearTarget(outport_, ImageType::ColorDepth); } shader_.activate(); utilgl::setShaderUniforms(shader_, camera_, "camera_"); utilgl::setShaderUniforms(shader_, lightingProperty_, "light_"); utilgl::setShaderUniforms(shader_, overrideColor_); utilgl::GlBoolState depthTest(GL_DEPTH_TEST, enableDepthTest_.get()); utilgl::CullFaceState culling(cullFace_.get()); utilgl::PolygonModeState polygon(polygonMode_.get(), renderLineWidth_, renderPointSize_); for (auto& drawer : drawers_) { utilgl::setShaderUniforms(shader_, *(drawer.second->getMesh()), "geometry_"); drawer.second->draw(); } shader_.deactivate(); utilgl::deactivateCurrentTarget(); } void MeshRenderProcessorGL::centerViewOnGeometry() { if (!inport_.hasData()) return; vec3 worldMin(std::numeric_limits<float>::max()); vec3 worldMax(std::numeric_limits<float>::lowest()); for (const auto& mesh : inport_) { vec3 minPos(std::numeric_limits<float>::max()); vec3 maxPos(std::numeric_limits<float>::lowest()); for (auto buff : mesh->getBuffers()) { if (buff.first.type == BufferType::PositionAttrib) { const Vec3BufferRAM* posbuff = dynamic_cast<const Vec3BufferRAM*>(buff.second->getRepresentation<BufferRAM>()); if (posbuff) { const std::vector<vec3>* pos = posbuff->getDataContainer(); for (const auto& p : *pos) { minPos = glm::min(minPos, p); maxPos = glm::max(maxPos, p); } } } } mat4 trans = mesh->getCoordinateTransformer().getDataToWorldMatrix(); worldMin = glm::min(worldMin, (trans * vec4(minPos, 1.f)).xyz()); worldMax = glm::max(worldMax, (trans * vec4(maxPos, 1.f)).xyz()); } camera_.setLook(camera_.getLookFrom(), 0.5f * (worldMin + worldMax), camera_.getLookUp()); } void MeshRenderProcessorGL::setNearFarPlane() { if (!inport_.hasData()) return; auto geom = inport_.getData(); auto posBuffer = dynamic_cast<const Vec3BufferRAM*>(geom->getBuffer(0)->getRepresentation<BufferRAM>()); if (posBuffer == nullptr) return; auto pos = posBuffer->getDataContainer(); if (pos->empty()) return; float nearDist, farDist; nearDist = std::numeric_limits<float>::infinity(); farDist = 0; vec3 nearPos, farPos; vec3 camPos = (geom->getCoordinateTransformer().getWorldToModelMatrix() * vec4(camera_.getLookFrom(), 1.0)) .xyz(); for (auto& po : *pos) { auto d = glm::distance2(po, camPos); if (d < nearDist) { nearDist = d; nearPos = po; } if (d > farDist) { farDist = d; farPos = po; } } mat4 m = camera_.viewMatrix() * geom->getCoordinateTransformer().getModelToWorldMatrix(); camera_.setNearPlaneDist(std::max(0.0f, 0.99f * std::abs((m * vec4(nearPos, 1.0f)).z))); camera_.setFarPlaneDist(std::max(0.0f, 1.01f * std::abs((m * vec4(farPos, 1.0f)).z))); } void MeshRenderProcessorGL::updateDrawers() { auto changed = inport_.getChangedOutports(); DrawerMap temp; std::swap(temp, drawers_); std::map<const Outport*, std::vector<std::shared_ptr<const Mesh>>> data; for (auto& elem : inport_.getSourceVectorData()) { data[elem.first].push_back(elem.second); } for (auto elem : data) { auto ibegin = temp.lower_bound(elem.first); auto iend = temp.upper_bound(elem.first); if (util::contains(changed, elem.first) || ibegin == temp.end() || static_cast<long>(elem.second.size()) != std::distance(ibegin, iend)) { // data is changed or new. for (auto geo : elem.second) { auto factory = getNetwork()->getApplication()->getMeshDrawerFactory(); if (auto renderer = factory->create(geo.get())) { drawers_.emplace(std::make_pair(elem.first, std::move(renderer))); } } } else { // reuse the old data. drawers_.insert(std::make_move_iterator(ibegin), std::make_move_iterator(iend)); } } } } // namespace <commit_msg>BaseGL: Associated inport with camera to adjust the view when basis is changed. (Like we do for raycasting in extry exit points)<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2016 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include "meshrenderprocessorgl.h" #include <modules/opengl/geometry/meshgl.h> #include <inviwo/core/datastructures/buffer/bufferramprecision.h> #include <inviwo/core/interaction/trackball.h> #include <inviwo/core/common/inviwoapplication.h> #include <inviwo/core/rendering/meshdrawerfactory.h> #include <modules/opengl/rendering/meshdrawergl.h> #include <inviwo/core/processors/processor.h> #include <modules/opengl/shader/shader.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/openglutils.h> #include <limits> namespace inviwo { const ProcessorInfo MeshRenderProcessorGL::processorInfo_{ "org.inviwo.GeometryRenderGL", // Class identifier "Mesh Renderer", // Display name "Mesh Rendering", // Category CodeState::Stable, // Code state Tags::GL, // Tags }; const ProcessorInfo MeshRenderProcessorGL::getProcessorInfo() const { return processorInfo_; } MeshRenderProcessorGL::MeshRenderProcessorGL() : Processor() , inport_("geometry") , imageInport_("imageInport") , outport_("image") , camera_("camera", "Camera", vec3(0.0f, 0.0f, -2.0f), vec3(0.0f, 0.0f, 0.0f), vec3(0.0f, 1.0f, 0.0f), &inport_) , centerViewOnGeometry_("centerView", "Center view on geometry") , setNearFarPlane_("setNearFarPlane", "Calculate Near and Far Plane") , resetViewParams_("resetView", "Reset Camera") , trackball_(&camera_) , overrideColorBuffer_("overrideColorBuffer", "Override Color Buffer", false, InvalidationLevel::InvalidResources) , overrideColor_("overrideColor", "Override Color", vec4(0.75f, 0.75f, 0.75f, 1.0f), vec4(0.0f), vec4(1.0f)) , geomProperties_("geometry", "Geometry Rendering Properties") , cullFace_("cullFace", "Cull Face") , polygonMode_("polygonMode", "Polygon Mode") , renderPointSize_("renderPointSize", "Point Size", 1.0f, 0.001f, 15.0f, 0.001f) , renderLineWidth_("renderLineWidth", "Line Width", 1.0f, 0.001f, 15.0f, 0.001f) , enableDepthTest_("enableDepthTest_","Enable Depth Test" , true) , lightingProperty_("lighting", "Lighting", &camera_) , layers_("layers", "Output Layers") , colorLayer_("colorLayer", "Color", true, InvalidationLevel::InvalidResources) , texCoordLayer_("texCoordLayer", "Texture Coordinates", false, InvalidationLevel::InvalidResources) , normalsLayer_("normalsLayer", "Normals (World Space)", false, InvalidationLevel::InvalidResources) , viewNormalsLayer_("viewNormalsLayer", "Normals (View space)", false, InvalidationLevel::InvalidResources) , shader_("geometryrendering.vert", "geometryrendering.frag", false) { addPort(inport_); addPort(imageInport_); addPort(outport_); imageInport_.setOptional(true); addProperty(camera_); centerViewOnGeometry_.onChange(this, &MeshRenderProcessorGL::centerViewOnGeometry); addProperty(centerViewOnGeometry_); setNearFarPlane_.onChange(this, &MeshRenderProcessorGL::setNearFarPlane); addProperty(setNearFarPlane_); resetViewParams_.onChange([this]() { camera_.resetCamera(); }); addProperty(resetViewParams_); outport_.addResizeEventListener(&camera_); inport_.onChange(this, &MeshRenderProcessorGL::updateDrawers); cullFace_.addOption("culldisable", "Disable", GL_NONE); cullFace_.addOption("cullfront", "Front", GL_FRONT); cullFace_.addOption("cullback", "Back", GL_BACK); cullFace_.addOption("cullfrontback", "Front & Back", GL_FRONT_AND_BACK); cullFace_.set(GL_NONE); polygonMode_.addOption("polypoint", "Points", GL_POINT); polygonMode_.addOption("polyline", "Lines", GL_LINE); polygonMode_.addOption("polyfill", "Fill", GL_FILL); polygonMode_.set(GL_FILL); polygonMode_.onChange(this, &MeshRenderProcessorGL::changeRenderMode); geomProperties_.addProperty(cullFace_); geomProperties_.addProperty(polygonMode_); geomProperties_.addProperty(renderPointSize_); geomProperties_.addProperty(renderLineWidth_); geomProperties_.addProperty(enableDepthTest_); geomProperties_.addProperty(overrideColorBuffer_); geomProperties_.addProperty(overrideColor_); overrideColor_.setSemantics(PropertySemantics::Color); overrideColor_.setVisible(false); overrideColorBuffer_.onChange([&]() { overrideColor_.setVisible(overrideColorBuffer_.get()); }); float lineWidthRange[2]; float increment; glGetFloatv(GL_LINE_WIDTH_RANGE, lineWidthRange); glGetFloatv(GL_LINE_WIDTH_GRANULARITY, &increment); renderLineWidth_.setMinValue(lineWidthRange[0]); renderLineWidth_.setMaxValue(lineWidthRange[1]); renderLineWidth_.setIncrement(increment); renderLineWidth_.setVisible(false); renderPointSize_.setVisible(false); addProperty(geomProperties_); addProperty(lightingProperty_); addProperty(trackball_); addProperty(layers_); layers_.addProperty(colorLayer_); layers_.addProperty(texCoordLayer_); layers_.addProperty(normalsLayer_); layers_.addProperty(viewNormalsLayer_); setAllPropertiesCurrentStateAsDefault(); } MeshRenderProcessorGL::~MeshRenderProcessorGL() {} void MeshRenderProcessorGL::initializeResources() { addCommonShaderDefines(shader_); } void MeshRenderProcessorGL::addCommonShaderDefines(Shader& shader) { // shading defines utilgl::addShaderDefines(shader, lightingProperty_); if (overrideColorBuffer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("OVERRIDE_COLOR_BUFFER"); } else { shader.getFragmentShaderObject()->removeShaderDefine("OVERRIDE_COLOR_BUFFER"); } if (colorLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("COLOR_LAYER"); } else { shader.getFragmentShaderObject()->removeShaderDefine("COLOR_LAYER"); } // first two layers (color and picking) are reserved, but picking buffer will be removed since it is not drawn to int layerID = 1; if (texCoordLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("TEXCOORD_LAYER"); shader.getFragmentShaderObject()->addOutDeclaration("tex_coord_out", layerID); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("TEXCOORD_LAYER"); } if (normalsLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("NORMALS_LAYER"); shader.getFragmentShaderObject()->addOutDeclaration("normals_out", layerID); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("NORMALS_LAYER"); } if (viewNormalsLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("VIEW_NORMALS_LAYER"); shader.getFragmentShaderObject()->addOutDeclaration("view_normals_out", layerID); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("VIEW_NORMALS_LAYER"); } // get a hold of the current output data auto prevData = outport_.getData(); auto numLayers = static_cast<std::size_t>(layerID); if (prevData->getNumberOfColorLayers() != numLayers) { // create new image with matching number of layers auto image = std::make_shared<Image>(prevData->getDimensions(), prevData->getDataFormat()); // update number of layers for (auto i = image->getNumberOfColorLayers(); i < numLayers; ++i) { image->addColorLayer(std::shared_ptr<Layer>(image->getColorLayer(0)->clone())); } outport_.setData(image); } shader.build(); } void MeshRenderProcessorGL::changeRenderMode() { switch (polygonMode_.get()) { case GL_FILL: { renderLineWidth_.setVisible(false); renderPointSize_.setVisible(false); break; } case GL_LINE: { renderLineWidth_.setVisible(true); renderPointSize_.setVisible(false); break; } case GL_POINT: { renderLineWidth_.setVisible(false); renderPointSize_.setVisible(true); break; } } } void MeshRenderProcessorGL::process() { if (imageInport_.isConnected()) { utilgl::activateTargetAndCopySource(outport_, imageInport_); } else { utilgl::activateAndClearTarget(outport_, ImageType::ColorDepth); } shader_.activate(); utilgl::setShaderUniforms(shader_, camera_, "camera_"); utilgl::setShaderUniforms(shader_, lightingProperty_, "light_"); utilgl::setShaderUniforms(shader_, overrideColor_); utilgl::GlBoolState depthTest(GL_DEPTH_TEST, enableDepthTest_.get()); utilgl::CullFaceState culling(cullFace_.get()); utilgl::PolygonModeState polygon(polygonMode_.get(), renderLineWidth_, renderPointSize_); for (auto& drawer : drawers_) { utilgl::setShaderUniforms(shader_, *(drawer.second->getMesh()), "geometry_"); drawer.second->draw(); } shader_.deactivate(); utilgl::deactivateCurrentTarget(); } void MeshRenderProcessorGL::centerViewOnGeometry() { if (!inport_.hasData()) return; vec3 worldMin(std::numeric_limits<float>::max()); vec3 worldMax(std::numeric_limits<float>::lowest()); for (const auto& mesh : inport_) { vec3 minPos(std::numeric_limits<float>::max()); vec3 maxPos(std::numeric_limits<float>::lowest()); for (auto buff : mesh->getBuffers()) { if (buff.first.type == BufferType::PositionAttrib) { const Vec3BufferRAM* posbuff = dynamic_cast<const Vec3BufferRAM*>(buff.second->getRepresentation<BufferRAM>()); if (posbuff) { const std::vector<vec3>* pos = posbuff->getDataContainer(); for (const auto& p : *pos) { minPos = glm::min(minPos, p); maxPos = glm::max(maxPos, p); } } } } mat4 trans = mesh->getCoordinateTransformer().getDataToWorldMatrix(); worldMin = glm::min(worldMin, (trans * vec4(minPos, 1.f)).xyz()); worldMax = glm::max(worldMax, (trans * vec4(maxPos, 1.f)).xyz()); } camera_.setLook(camera_.getLookFrom(), 0.5f * (worldMin + worldMax), camera_.getLookUp()); } void MeshRenderProcessorGL::setNearFarPlane() { if (!inport_.hasData()) return; auto geom = inport_.getData(); auto posBuffer = dynamic_cast<const Vec3BufferRAM*>(geom->getBuffer(0)->getRepresentation<BufferRAM>()); if (posBuffer == nullptr) return; auto pos = posBuffer->getDataContainer(); if (pos->empty()) return; float nearDist, farDist; nearDist = std::numeric_limits<float>::infinity(); farDist = 0; vec3 nearPos, farPos; vec3 camPos = (geom->getCoordinateTransformer().getWorldToModelMatrix() * vec4(camera_.getLookFrom(), 1.0)) .xyz(); for (auto& po : *pos) { auto d = glm::distance2(po, camPos); if (d < nearDist) { nearDist = d; nearPos = po; } if (d > farDist) { farDist = d; farPos = po; } } mat4 m = camera_.viewMatrix() * geom->getCoordinateTransformer().getModelToWorldMatrix(); camera_.setNearPlaneDist(std::max(0.0f, 0.99f * std::abs((m * vec4(nearPos, 1.0f)).z))); camera_.setFarPlaneDist(std::max(0.0f, 1.01f * std::abs((m * vec4(farPos, 1.0f)).z))); } void MeshRenderProcessorGL::updateDrawers() { auto changed = inport_.getChangedOutports(); DrawerMap temp; std::swap(temp, drawers_); std::map<const Outport*, std::vector<std::shared_ptr<const Mesh>>> data; for (auto& elem : inport_.getSourceVectorData()) { data[elem.first].push_back(elem.second); } for (auto elem : data) { auto ibegin = temp.lower_bound(elem.first); auto iend = temp.upper_bound(elem.first); if (util::contains(changed, elem.first) || ibegin == temp.end() || static_cast<long>(elem.second.size()) != std::distance(ibegin, iend)) { // data is changed or new. for (auto geo : elem.second) { auto factory = getNetwork()->getApplication()->getMeshDrawerFactory(); if (auto renderer = factory->create(geo.get())) { drawers_.emplace(std::make_pair(elem.first, std::move(renderer))); } } } else { // reuse the old data. drawers_.insert(std::make_move_iterator(ibegin), std::make_move_iterator(iend)); } } } } // namespace <|endoftext|>
<commit_before>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include "meshrenderprocessorgl.h" #include <modules/opengl/geometry/meshgl.h> #include <inviwo/core/datastructures/buffer/bufferramprecision.h> #include <inviwo/core/interaction/trackball.h> #include <inviwo/core/rendering/meshdrawerfactory.h> #include <modules/opengl/rendering/meshdrawergl.h> #include <inviwo/core/processors/processor.h> #include <modules/opengl/shader/shader.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/openglutils.h> #include <limits> namespace inviwo { ProcessorClassIdentifier(MeshRenderProcessorGL, "org.inviwo.GeometryRenderGL"); ProcessorDisplayName(MeshRenderProcessorGL, "Mesh Renderer"); ProcessorTags(MeshRenderProcessorGL, Tags::GL); ProcessorCategory(MeshRenderProcessorGL, "Geometry Rendering"); ProcessorCodeState(MeshRenderProcessorGL, CODE_STATE_STABLE); MeshRenderProcessorGL::MeshRenderProcessorGL() : Processor() , inport_("geometry.inport") , imageInport_("imageInport") , outport_("image.outport") , camera_("camera", "Camera") , centerViewOnGeometry_("centerView", "Center view on geometry") , setNearFarPlane_("setNearFarPlane", "Calculate Near and Far Plane") , resetViewParams_("resetView", "Reset Camera") , trackball_(&camera_) , overrideColorBuffer_("overrideColorBuffer", "Override Color Buffer", false , INVALID_RESOURCES) , overrideColor_("overrideColor", "Override Color", vec4(0.75f, 0.75f, 0.75f, 1.0f), vec4(0.0f), vec4(1.0f)) , geomProperties_("geometry", "Geometry Rendering Properties") , cullFace_("cullFace", "Cull Face") , polygonMode_("polygonMode", "Polygon Mode") , renderPointSize_("renderPointSize", "Point Size", 1.0f, 0.001f, 15.0f, 0.001f) , renderLineWidth_("renderLineWidth", "Line Width", 1.0f, 0.001f, 15.0f, 0.001f) , lightingProperty_("lighting", "Lighting", &camera_) , layers_("layers", "Layers") , colorLayer_("colorLayer", "Color", true, INVALID_RESOURCES) , texCoordLayer_("texCoordLayer", "Texture Coordinates", false, INVALID_RESOURCES) , normalsLayer_("normalsLayer", "Normals (World Space)", false, INVALID_RESOURCES) , viewNormalsLayer_("viewNormalsLayer", "Normals (View space)", false, INVALID_RESOURCES) , shader_("geometryrendering.vert", "geometryrendering.frag", false) { addPort(inport_); addPort(imageInport_); addPort(outport_); addProperty(camera_); centerViewOnGeometry_.onChange(this, &MeshRenderProcessorGL::centerViewOnGeometry); addProperty(centerViewOnGeometry_); setNearFarPlane_.onChange(this, &MeshRenderProcessorGL::setNearFarPlane); addProperty(setNearFarPlane_); resetViewParams_.onChange([this]() { camera_.resetCamera(); }); addProperty(resetViewParams_); outport_.addResizeEventListener(&camera_); inport_.onChange(this, &MeshRenderProcessorGL::updateDrawers); cullFace_.addOption("culldisable", "Disable", GL_NONE); cullFace_.addOption("cullfront", "Front", GL_FRONT); cullFace_.addOption("cullback", "Back", GL_BACK); cullFace_.addOption("cullfrontback", "Front & Back", GL_FRONT_AND_BACK); cullFace_.set(GL_NONE); polygonMode_.addOption("polypoint", "Points", GL_POINT); polygonMode_.addOption("polyline", "Lines", GL_LINE); polygonMode_.addOption("polyfill", "Fill", GL_FILL); polygonMode_.set(GL_FILL); polygonMode_.onChange(this, &MeshRenderProcessorGL::changeRenderMode); geomProperties_.addProperty(cullFace_); geomProperties_.addProperty(polygonMode_); geomProperties_.addProperty(renderPointSize_); geomProperties_.addProperty(renderLineWidth_); geomProperties_.addProperty(overrideColorBuffer_); geomProperties_.addProperty(overrideColor_); overrideColor_.setSemantics(PropertySemantics::Color); overrideColor_.setVisible(false); overrideColorBuffer_.onChange([&](){overrideColor_.setVisible(overrideColorBuffer_.get()); }); float lineWidthRange[2]; float increment; glGetFloatv(GL_LINE_WIDTH_RANGE, lineWidthRange); glGetFloatv(GL_LINE_WIDTH_GRANULARITY, &increment); renderLineWidth_.setMinValue(lineWidthRange[0]); renderLineWidth_.setMaxValue(lineWidthRange[1]); renderLineWidth_.setIncrement(increment); renderLineWidth_.setVisible(false); renderPointSize_.setVisible(false); addProperty(geomProperties_); addProperty(lightingProperty_); addProperty(trackball_); addProperty(layers_); layers_.addProperty(colorLayer_); layers_.addProperty(texCoordLayer_); layers_.addProperty(normalsLayer_); layers_.addProperty(viewNormalsLayer_); setAllPropertiesCurrentStateAsDefault(); } MeshRenderProcessorGL::~MeshRenderProcessorGL() {} void MeshRenderProcessorGL::initializeResources() { addCommonShaderDefines(shader_); } void MeshRenderProcessorGL::addCommonShaderDefines(Shader& shader) { // shading defines utilgl::addShaderDefines(shader, lightingProperty_); int layerID = 0; if (overrideColorBuffer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("OVERRIDE_COLOR_BUFFER"); } else { shader.getFragmentShaderObject()->removeShaderDefine("OVERRIDE_COLOR_BUFFER"); } if (colorLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("LayerType::Color"); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("LayerType::Color"); } if (texCoordLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("TEXCOORD_LAYER"); shader.getFragmentShaderObject()->addOutDeclaration("tex_coord_out", layerID); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("TEXCOORD_LAYER"); } if (normalsLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("NORMALS_LAYER"); shader.getFragmentShaderObject()->addOutDeclaration("normals_out", layerID); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("NORMALS_LAYER"); } if (viewNormalsLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("VIEW_NORMALS_LAYER"); shader.getFragmentShaderObject()->addOutDeclaration("view_normals_out", layerID); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("VIEW_NORMALS_LAYER"); } for (std::size_t i = outport_.getData()->getNumberOfColorLayers(); i < static_cast<std::size_t>(layerID); i++) { outport_.getEditableData()->addColorLayer( std::shared_ptr<Layer>(outport_.getData()->getColorLayer(0)->clone())); } shader.build(); } void MeshRenderProcessorGL::changeRenderMode() { switch (polygonMode_.get()) { case GL_FILL: { renderLineWidth_.setVisible(false); renderPointSize_.setVisible(false); break; } case GL_LINE: { renderLineWidth_.setVisible(true); renderPointSize_.setVisible(false); break; } case GL_POINT: { renderLineWidth_.setVisible(false); renderPointSize_.setVisible(true); break; } } } void MeshRenderProcessorGL::process() { if (imageInport_.isConnected()){ utilgl::activateTargetAndCopySource(outport_, imageInport_); } else{ utilgl::activateAndClearTarget(outport_, ImageType::ColorDepth); } shader_.activate(); utilgl::setShaderUniforms(shader_, camera_, "camera_"); utilgl::setShaderUniforms(shader_, lightingProperty_, "light_"); utilgl::setShaderUniforms(shader_, overrideColor_); utilgl::GlBoolState depthTest(GL_DEPTH_TEST, true); utilgl::CullFaceState culling(cullFace_.get()); utilgl::PolygonModeState polygon(polygonMode_.get(), renderLineWidth_, renderPointSize_); for (auto& drawer : drawers_) { utilgl::setShaderUniforms(shader_, *(drawer.second->getGeometry()), "geometry_"); drawer.second->draw(); } shader_.deactivate(); utilgl::deactivateCurrentTarget(); } bool MeshRenderProcessorGL::isReady() const { if (imageInport_.isConnected()) { return Processor::isReady(); } else { return inport_.isReady(); } } void MeshRenderProcessorGL::centerViewOnGeometry() { if (!inport_.hasData()) return; vec3 worldMin(std::numeric_limits<float>::max()); vec3 worldMax(std::numeric_limits<float>::lowest()); for (const auto& mesh : inport_) { vec3 minPos(std::numeric_limits<float>::max()); vec3 maxPos(std::numeric_limits<float>::lowest()); for (auto buff : mesh->getBuffers()) { if (buff.first == BufferType::POSITION_ATTRIB) { const Vec3BufferRAM* posbuff = dynamic_cast<const Vec3BufferRAM*>(buff.second->getRepresentation<BufferRAM>()); if (posbuff) { const std::vector<vec3>* pos = posbuff->getDataContainer(); for (const auto& p : *pos) { minPos = glm::min(minPos, p); maxPos = glm::max(maxPos, p); } } } } mat4 trans = mesh->getCoordinateTransformer().getDataToWorldMatrix(); worldMin = glm::min(worldMin, (trans * vec4(minPos, 1.f)).xyz()); worldMax = glm::max(worldMax, (trans * vec4(maxPos, 1.f)).xyz()); } camera_.setLook(camera_.getLookFrom(), 0.5f * (worldMin + worldMax), camera_.getLookUp()); } void MeshRenderProcessorGL::setNearFarPlane() { if (!inport_.hasData()) return; auto geom = inport_.getData(); auto posBuffer = dynamic_cast<const Vec3BufferRAM*>(geom->getBuffer(0)->getRepresentation<BufferRAM>()); if (posBuffer == nullptr) return; auto pos = posBuffer->getDataContainer(); if (pos->empty()) return; float nearDist, farDist; nearDist = std::numeric_limits<float>::infinity(); farDist = 0; vec3 nearPos, farPos; vec3 camPos = (geom->getCoordinateTransformer().getWorldToModelMatrix() * vec4(camera_.getLookFrom(), 1.0)) .xyz(); for (auto& po : *pos) { auto d = glm::distance2(po, camPos); if (d < nearDist) { nearDist = d; nearPos = po; } if (d > farDist) { farDist = d; farPos = po; } } mat4 m = camera_.viewMatrix() * geom->getCoordinateTransformer().getModelToWorldMatrix(); camera_.setNearPlaneDist(std::max(0.0f, 0.99f * std::abs((m * vec4(nearPos, 1.0f)).z))); camera_.setFarPlaneDist(std::max(0.0f, 1.01f * std::abs((m * vec4(farPos, 1.0f)).z))); } void MeshRenderProcessorGL::updateDrawers() { auto changed = inport_.getChangedOutports(); DrawerMap temp; std::swap(temp, drawers_); std::map<const Outport*, std::vector<std::shared_ptr<const Mesh>>> data; for (auto& elem : inport_.getSourceVectorData()) { data[elem.first].push_back(elem.second); } for (auto elem : data) { auto ibegin = temp.lower_bound(elem.first); auto iend = temp.upper_bound(elem.first); if (util::contains(changed, elem.first) || ibegin == temp.end() || static_cast<long>(elem.second.size()) != std::distance(ibegin, iend)) { // data is changed or new. for (auto geo : elem.second) { if (auto renderer = MeshDrawerFactory::getPtr()->create(geo.get())) { drawers_.emplace(std::make_pair(elem.first, std::move(renderer))); } } } else { // reuse the old data. drawers_.insert(std::make_move_iterator(ibegin), std::make_move_iterator(iend)); } } } } // namespace <commit_msg>MeshRenderingProcessorGL: Added back COLOR_LAYER shader define: Please be careful when using "search and replace" in solution.<commit_after>/********************************************************************************* * * Inviwo - Interactive Visualization Workshop * * Copyright (c) 2013-2015 Inviwo Foundation * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *********************************************************************************/ #include "meshrenderprocessorgl.h" #include <modules/opengl/geometry/meshgl.h> #include <inviwo/core/datastructures/buffer/bufferramprecision.h> #include <inviwo/core/interaction/trackball.h> #include <inviwo/core/rendering/meshdrawerfactory.h> #include <modules/opengl/rendering/meshdrawergl.h> #include <inviwo/core/processors/processor.h> #include <modules/opengl/shader/shader.h> #include <modules/opengl/texture/textureutils.h> #include <modules/opengl/shader/shaderutils.h> #include <modules/opengl/openglutils.h> #include <limits> namespace inviwo { ProcessorClassIdentifier(MeshRenderProcessorGL, "org.inviwo.GeometryRenderGL"); ProcessorDisplayName(MeshRenderProcessorGL, "Mesh Renderer"); ProcessorTags(MeshRenderProcessorGL, Tags::GL); ProcessorCategory(MeshRenderProcessorGL, "Geometry Rendering"); ProcessorCodeState(MeshRenderProcessorGL, CODE_STATE_STABLE); MeshRenderProcessorGL::MeshRenderProcessorGL() : Processor() , inport_("geometry.inport") , imageInport_("imageInport") , outport_("image.outport") , camera_("camera", "Camera") , centerViewOnGeometry_("centerView", "Center view on geometry") , setNearFarPlane_("setNearFarPlane", "Calculate Near and Far Plane") , resetViewParams_("resetView", "Reset Camera") , trackball_(&camera_) , overrideColorBuffer_("overrideColorBuffer", "Override Color Buffer", false , INVALID_RESOURCES) , overrideColor_("overrideColor", "Override Color", vec4(0.75f, 0.75f, 0.75f, 1.0f), vec4(0.0f), vec4(1.0f)) , geomProperties_("geometry", "Geometry Rendering Properties") , cullFace_("cullFace", "Cull Face") , polygonMode_("polygonMode", "Polygon Mode") , renderPointSize_("renderPointSize", "Point Size", 1.0f, 0.001f, 15.0f, 0.001f) , renderLineWidth_("renderLineWidth", "Line Width", 1.0f, 0.001f, 15.0f, 0.001f) , lightingProperty_("lighting", "Lighting", &camera_) , layers_("layers", "Layers") , colorLayer_("colorLayer", "Color", true, INVALID_RESOURCES) , texCoordLayer_("texCoordLayer", "Texture Coordinates", false, INVALID_RESOURCES) , normalsLayer_("normalsLayer", "Normals (World Space)", false, INVALID_RESOURCES) , viewNormalsLayer_("viewNormalsLayer", "Normals (View space)", false, INVALID_RESOURCES) , shader_("geometryrendering.vert", "geometryrendering.frag", false) { addPort(inport_); addPort(imageInport_); addPort(outport_); addProperty(camera_); centerViewOnGeometry_.onChange(this, &MeshRenderProcessorGL::centerViewOnGeometry); addProperty(centerViewOnGeometry_); setNearFarPlane_.onChange(this, &MeshRenderProcessorGL::setNearFarPlane); addProperty(setNearFarPlane_); resetViewParams_.onChange([this]() { camera_.resetCamera(); }); addProperty(resetViewParams_); outport_.addResizeEventListener(&camera_); inport_.onChange(this, &MeshRenderProcessorGL::updateDrawers); cullFace_.addOption("culldisable", "Disable", GL_NONE); cullFace_.addOption("cullfront", "Front", GL_FRONT); cullFace_.addOption("cullback", "Back", GL_BACK); cullFace_.addOption("cullfrontback", "Front & Back", GL_FRONT_AND_BACK); cullFace_.set(GL_NONE); polygonMode_.addOption("polypoint", "Points", GL_POINT); polygonMode_.addOption("polyline", "Lines", GL_LINE); polygonMode_.addOption("polyfill", "Fill", GL_FILL); polygonMode_.set(GL_FILL); polygonMode_.onChange(this, &MeshRenderProcessorGL::changeRenderMode); geomProperties_.addProperty(cullFace_); geomProperties_.addProperty(polygonMode_); geomProperties_.addProperty(renderPointSize_); geomProperties_.addProperty(renderLineWidth_); geomProperties_.addProperty(overrideColorBuffer_); geomProperties_.addProperty(overrideColor_); overrideColor_.setSemantics(PropertySemantics::Color); overrideColor_.setVisible(false); overrideColorBuffer_.onChange([&](){overrideColor_.setVisible(overrideColorBuffer_.get()); }); float lineWidthRange[2]; float increment; glGetFloatv(GL_LINE_WIDTH_RANGE, lineWidthRange); glGetFloatv(GL_LINE_WIDTH_GRANULARITY, &increment); renderLineWidth_.setMinValue(lineWidthRange[0]); renderLineWidth_.setMaxValue(lineWidthRange[1]); renderLineWidth_.setIncrement(increment); renderLineWidth_.setVisible(false); renderPointSize_.setVisible(false); addProperty(geomProperties_); addProperty(lightingProperty_); addProperty(trackball_); addProperty(layers_); layers_.addProperty(colorLayer_); layers_.addProperty(texCoordLayer_); layers_.addProperty(normalsLayer_); layers_.addProperty(viewNormalsLayer_); setAllPropertiesCurrentStateAsDefault(); } MeshRenderProcessorGL::~MeshRenderProcessorGL() {} void MeshRenderProcessorGL::initializeResources() { addCommonShaderDefines(shader_); } void MeshRenderProcessorGL::addCommonShaderDefines(Shader& shader) { // shading defines utilgl::addShaderDefines(shader, lightingProperty_); int layerID = 0; if (overrideColorBuffer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("OVERRIDE_COLOR_BUFFER"); } else { shader.getFragmentShaderObject()->removeShaderDefine("OVERRIDE_COLOR_BUFFER"); } if (colorLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("COLOR_LAYER"); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("COLOR_LAYER"); } if (texCoordLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("TEXCOORD_LAYER"); shader.getFragmentShaderObject()->addOutDeclaration("tex_coord_out", layerID); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("TEXCOORD_LAYER"); } if (normalsLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("NORMALS_LAYER"); shader.getFragmentShaderObject()->addOutDeclaration("normals_out", layerID); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("NORMALS_LAYER"); } if (viewNormalsLayer_.get()) { shader.getFragmentShaderObject()->addShaderDefine("VIEW_NORMALS_LAYER"); shader.getFragmentShaderObject()->addOutDeclaration("view_normals_out", layerID); layerID++; } else { shader.getFragmentShaderObject()->removeShaderDefine("VIEW_NORMALS_LAYER"); } for (std::size_t i = outport_.getData()->getNumberOfColorLayers(); i < static_cast<std::size_t>(layerID); i++) { outport_.getEditableData()->addColorLayer( std::shared_ptr<Layer>(outport_.getData()->getColorLayer(0)->clone())); } shader.build(); } void MeshRenderProcessorGL::changeRenderMode() { switch (polygonMode_.get()) { case GL_FILL: { renderLineWidth_.setVisible(false); renderPointSize_.setVisible(false); break; } case GL_LINE: { renderLineWidth_.setVisible(true); renderPointSize_.setVisible(false); break; } case GL_POINT: { renderLineWidth_.setVisible(false); renderPointSize_.setVisible(true); break; } } } void MeshRenderProcessorGL::process() { if (imageInport_.isConnected()){ utilgl::activateTargetAndCopySource(outport_, imageInport_); } else{ utilgl::activateAndClearTarget(outport_, ImageType::ColorDepth); } shader_.activate(); utilgl::setShaderUniforms(shader_, camera_, "camera_"); utilgl::setShaderUniforms(shader_, lightingProperty_, "light_"); utilgl::setShaderUniforms(shader_, overrideColor_); utilgl::GlBoolState depthTest(GL_DEPTH_TEST, true); utilgl::CullFaceState culling(cullFace_.get()); utilgl::PolygonModeState polygon(polygonMode_.get(), renderLineWidth_, renderPointSize_); for (auto& drawer : drawers_) { utilgl::setShaderUniforms(shader_, *(drawer.second->getGeometry()), "geometry_"); drawer.second->draw(); } shader_.deactivate(); utilgl::deactivateCurrentTarget(); } bool MeshRenderProcessorGL::isReady() const { if (imageInport_.isConnected()) { return Processor::isReady(); } else { return inport_.isReady(); } } void MeshRenderProcessorGL::centerViewOnGeometry() { if (!inport_.hasData()) return; vec3 worldMin(std::numeric_limits<float>::max()); vec3 worldMax(std::numeric_limits<float>::lowest()); for (const auto& mesh : inport_) { vec3 minPos(std::numeric_limits<float>::max()); vec3 maxPos(std::numeric_limits<float>::lowest()); for (auto buff : mesh->getBuffers()) { if (buff.first == BufferType::POSITION_ATTRIB) { const Vec3BufferRAM* posbuff = dynamic_cast<const Vec3BufferRAM*>(buff.second->getRepresentation<BufferRAM>()); if (posbuff) { const std::vector<vec3>* pos = posbuff->getDataContainer(); for (const auto& p : *pos) { minPos = glm::min(minPos, p); maxPos = glm::max(maxPos, p); } } } } mat4 trans = mesh->getCoordinateTransformer().getDataToWorldMatrix(); worldMin = glm::min(worldMin, (trans * vec4(minPos, 1.f)).xyz()); worldMax = glm::max(worldMax, (trans * vec4(maxPos, 1.f)).xyz()); } camera_.setLook(camera_.getLookFrom(), 0.5f * (worldMin + worldMax), camera_.getLookUp()); } void MeshRenderProcessorGL::setNearFarPlane() { if (!inport_.hasData()) return; auto geom = inport_.getData(); auto posBuffer = dynamic_cast<const Vec3BufferRAM*>(geom->getBuffer(0)->getRepresentation<BufferRAM>()); if (posBuffer == nullptr) return; auto pos = posBuffer->getDataContainer(); if (pos->empty()) return; float nearDist, farDist; nearDist = std::numeric_limits<float>::infinity(); farDist = 0; vec3 nearPos, farPos; vec3 camPos = (geom->getCoordinateTransformer().getWorldToModelMatrix() * vec4(camera_.getLookFrom(), 1.0)) .xyz(); for (auto& po : *pos) { auto d = glm::distance2(po, camPos); if (d < nearDist) { nearDist = d; nearPos = po; } if (d > farDist) { farDist = d; farPos = po; } } mat4 m = camera_.viewMatrix() * geom->getCoordinateTransformer().getModelToWorldMatrix(); camera_.setNearPlaneDist(std::max(0.0f, 0.99f * std::abs((m * vec4(nearPos, 1.0f)).z))); camera_.setFarPlaneDist(std::max(0.0f, 1.01f * std::abs((m * vec4(farPos, 1.0f)).z))); } void MeshRenderProcessorGL::updateDrawers() { auto changed = inport_.getChangedOutports(); DrawerMap temp; std::swap(temp, drawers_); std::map<const Outport*, std::vector<std::shared_ptr<const Mesh>>> data; for (auto& elem : inport_.getSourceVectorData()) { data[elem.first].push_back(elem.second); } for (auto elem : data) { auto ibegin = temp.lower_bound(elem.first); auto iend = temp.upper_bound(elem.first); if (util::contains(changed, elem.first) || ibegin == temp.end() || static_cast<long>(elem.second.size()) != std::distance(ibegin, iend)) { // data is changed or new. for (auto geo : elem.second) { if (auto renderer = MeshDrawerFactory::getPtr()->create(geo.get())) { drawers_.emplace(std::make_pair(elem.first, std::move(renderer))); } } } else { // reuse the old data. drawers_.insert(std::make_move_iterator(ibegin), std::make_move_iterator(iend)); } } } } // namespace <|endoftext|>
<commit_before>//===- lib/Support/ErrorHandling.cpp - Callbacks for errors ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an API used to indicate fatal error conditions. Non-fatal // errors (most of them) should be handled through LLVMContext. // //===----------------------------------------------------------------------===// #include "llvm/ADT/Twine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Signals.h" #include "llvm/System/Threading.h" #include <cassert> #include <cstdlib> using namespace llvm; using namespace std; static fatal_error_handler_t ErrorHandler = 0; static void *ErrorHandlerUserData = 0; void llvm::install_fatal_error_handler(fatal_error_handler_t handler, void *user_data) { assert(!llvm_is_multithreaded() && "Cannot register error handlers after starting multithreaded mode!\n"); assert(!ErrorHandler && "Error handler already registered!\n"); ErrorHandler = handler; ErrorHandlerUserData = user_data; } void llvm::remove_fatal_error_handler() { ErrorHandler = 0; } void llvm::report_fatal_error(const char *reason) { report_fatal_error(Twine(reason)); } void llvm::report_fatal_error(const std::string &reason) { report_fatal_error(Twine(reason)); } void llvm::report_fatal_error(const Twine &reason) { if (!ErrorHandler) { errs() << "LLVM ERROR: " << reason << "\n"; } else { ErrorHandler(ErrorHandlerUserData, reason.str()); } // If we reached here, we are failing ungracefully. Run the interrupt handlers // to make sure any special cleanups get done, in particular that we remove // files registered with RemoveFileOnSignal. sys::RunInterruptHandlers(); exit(1); } void llvm::llvm_unreachable_internal(const char *msg, const char *file, unsigned line) { // This code intentionally doesn't call the ErrorHandler callback, because // llvm_unreachable is intended to be used to indicate "impossible" // situations, and not legitimate runtime errors. if (msg) dbgs() << msg << "\n"; dbgs() << "UNREACHABLE executed"; if (file) dbgs() << " at " << file << ":" << line; dbgs() << "!\n"; abort(); } <commit_msg>report_fatal_error can't use errs(), because errs() can call into report_fatal_error. Just blast the string to stderr with write(2) and hope for the best! Part of rdar://8318441<commit_after>//===- lib/Support/ErrorHandling.cpp - Callbacks for errors ---------------===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// // // This file defines an API used to indicate fatal error conditions. Non-fatal // errors (most of them) should be handled through LLVMContext. // //===----------------------------------------------------------------------===// #include "llvm/ADT/Twine.h" #include "llvm/Support/Debug.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/raw_ostream.h" #include "llvm/System/Signals.h" #include "llvm/System/Threading.h" #include "llvm/ADT/SmallVector.h" #include <cassert> #include <cstdlib> #if defined(HAVE_UNISTD_H) # include <unistd.h> #endif #if defined(_MSC_VER) # include <io.h> # include <fcntl.h> #endif using namespace llvm; using namespace std; static fatal_error_handler_t ErrorHandler = 0; static void *ErrorHandlerUserData = 0; void llvm::install_fatal_error_handler(fatal_error_handler_t handler, void *user_data) { assert(!llvm_is_multithreaded() && "Cannot register error handlers after starting multithreaded mode!\n"); assert(!ErrorHandler && "Error handler already registered!\n"); ErrorHandler = handler; ErrorHandlerUserData = user_data; } void llvm::remove_fatal_error_handler() { ErrorHandler = 0; } void llvm::report_fatal_error(const char *Reason) { report_fatal_error(Twine(Reason)); } void llvm::report_fatal_error(const std::string &Reason) { report_fatal_error(Twine(Reason)); } void llvm::report_fatal_error(const Twine &Reason) { if (ErrorHandler) { ErrorHandler(ErrorHandlerUserData, Reason.str()); } else { // Blast the result out to stderr. We don't try hard to make sure this // succeeds (e.g. handling EINTR) and we can't use errs() here because // raw ostreams can call report_fatal_error. SmallVector<char, 64> Buffer; StringRef ReasonStr = Reason.toStringRef(Buffer); ::write(2, "LLVM ERROR: ", 12); ::write(2, ReasonStr.data(), ReasonStr.size()); ::write(2, "\n", 1); } // If we reached here, we are failing ungracefully. Run the interrupt handlers // to make sure any special cleanups get done, in particular that we remove // files registered with RemoveFileOnSignal. sys::RunInterruptHandlers(); exit(1); } void llvm::llvm_unreachable_internal(const char *msg, const char *file, unsigned line) { // This code intentionally doesn't call the ErrorHandler callback, because // llvm_unreachable is intended to be used to indicate "impossible" // situations, and not legitimate runtime errors. if (msg) dbgs() << msg << "\n"; dbgs() << "UNREACHABLE executed"; if (file) dbgs() << " at " << file << ":" << line; dbgs() << "!\n"; abort(); } <|endoftext|>
<commit_before>#include "core/distributionsampler.h" #include "ts/ts.h" #include <opencv2/imgproc.hpp> namespace { TEST(DistrSampler1D, Uniform) { const int SIZE = 10, N = 1e4; const float MEAN = 1.f/static_cast<float>(SIZE); MatF pdf_uniform = MatF::ones(1, SIZE)*MEAN; DistributionSampler1D to; // test object to.pdf(pdf_uniform); MatF hist = MatF::zeros(1, SIZE); for(int i=0; i<N; i++) { int sampled_index = to.Sample(); EXPECT_IN_CLOSED(sampled_index, 0, SIZE-1); hist(sampled_index)++; } EXPECT_EQ(cv::sum(hist)(0), N); MatF hist_normalized = hist/static_cast<float>(N); EXPECT_MAT_NEAR(hist_normalized, pdf_uniform, 0.2f); cv::Mat m, s; cv::meanStdDev(hist_normalized, m, s); EXPECT_NEAR(m.at<double>(0, 0), MEAN, 0.1); EXPECT_NEAR(s.at<double>(0, 0), 0., 0.1); } TEST(DistrSampler1D, Gaussian) { const int SIZE = 10, N=2000; const float MEAN = 5.f, STD_DEV = 2.f; // generate gaussian pdf cv::Mat data(1, N, CV_32FC1); cv::randn(data, MEAN, STD_DEV); float pdf_values[SIZE] = {}; for (int i=0; i<N; i++) { float v = data.at<float>(i); if ( v >= 0.f && v<10.0) { ++pdf_values[static_cast<int>(v)]; } } DistributionSampler1D to; // test object cv::Mat pdf = cv::Mat(1,10, CV_32FC1, pdf_values)/static_cast<float>(N)*SIZE; to.pdf(pdf); MatF hist = MatF::zeros(1, SIZE); for(int i=0; i<N; i++) { int sampled_index = to.Sample(); EXPECT_IN_CLOSED(sampled_index, 0, SIZE-1); hist(sampled_index)++; } EXPECT_EQ(cv::sum(hist)(0), N); MatF hist_normalized = hist/static_cast<float>(N)*SIZE; EXPECT_MAT_NEAR(hist_normalized, pdf, 0.2f); } TEST(DistrSampler2D, Uniform) { const int ROWS = 7, COLS = 10, N = 2e4; const float MEAN = 1.f/static_cast<float>(ROWS*COLS); MatF pdf_uniform = MatF::ones(ROWS, COLS)*MEAN; DistributionSampler2D to; // test object to.pdf(pdf_uniform); MatF hist = MatF::zeros(ROWS, COLS); for(int i=0; i<N; i++) { cv::Point2i sampled_point = to.Sample(); EXPECT_TRUE( sampled_point.inside(cv::Rect(0, 0, COLS, ROWS)) ); hist(sampled_point.y, sampled_point.x)++; } EXPECT_EQ(cv::sum(hist)(0), N); MatF hist_normalized = hist/static_cast<float>(N); EXPECT_MAT_NEAR(hist_normalized, pdf_uniform, 0.2f); cv::Mat m, s; cv::meanStdDev(hist_normalized, m, s); EXPECT_NEAR(m.at<double>(0, 0), MEAN, 0.1); EXPECT_NEAR(s.at<double>(0, 0), 0., 0.1); } class PoissonProcessTest : public testing::Test { protected: PoissonProcessTest() : frequency_(1.f), delta_t_msec_(1000.f), to_(0.f, 0.f) // dummy initialization { } virtual void SetUp() { to_ = PoissonProcess(frequency_, delta_t_msec_); // -ve frequency => inf firing rate, 1 msec time resolution } float frequency_; float delta_t_msec_; PoissonProcess to_; ///< test object }; TEST_F(PoissonProcessTest, PDF) { MatF pdf = to_.pdf(); EXPECT_MAT_DIMS_EQ(pdf, MatF(1, 1)); float lambda = pdf(0, 0); EXPECT_LE(lambda, 0); EXPECT_FLOAT_EQ(lambda, 1.f-frequency_*delta_t_msec_/1000.f); } TEST_F(PoissonProcessTest, Sample) { const int N = 100; for(int i=0; i<N; i++) { EXPECT_EQ(1, to_.Sample()); } } TEST_F(PoissonProcessTest, SampleZeroFreq) { PoissonProcess to(0.f, 1.f); const int N = 100; for(int i=0; i<N; i++) { EXPECT_EQ(0, to.Sample()); } } TEST_F(PoissonProcessTest, SampleZeroDeltaT) { PoissonProcess to(40.f, 0.f); const int N = 100; for(int i=0; i<N; i++) { EXPECT_EQ(0, to.Sample()); } } TEST_F(PoissonProcessTest, SampleZeroFreqAndDeltaT) { PoissonProcess to(0.f, 0.f); const int N = 100; for(int i=0; i<N; i++) { EXPECT_EQ(0, to.Sample()); } } TEST_F(PoissonProcessTest, SampleCoinToss) { PoissonProcess to(50.f, 10.f); const int N = 1e4; int net = 0; for(int i=0; i<N; i++) { net += to.Sample(); } float rate = net/static_cast<float>(N); EXPECT_NEAR(rate, 0.5f, 0.02f); } /** * @brief Compare theoretical pdf for exponential distr. * to pdf generate from 1) pdf sampler 2) randexp() */ TEST(ExponentialPDFTest, Sample) { const double PDF_END=10.; // last x element in pdf function const int SIZE=30, N=2000; // no. of bins, no. of samples to draw const float LAMBDA = 1.f; // generate exponential pdf MatF pdf(1, SIZE); double x = 0.; for (int i=0; i<SIZE; i++, x += PDF_END/static_cast<double>(SIZE)) { double f = exp(-static_cast<double>(LAMBDA)*x); pdf(i) = LAMBDA*static_cast<float>(f); } // add generated pdf to a sampler and draw samples from it DistributionSampler1D to; // test object to.pdf(pdf); // generate a histogram from sampled values // also sample values from randexp() function MatF hist1 = MatF::zeros(1, SIZE); MatF hist2 = MatF::zeros(1, SIZE); for(int i=0; i<N; i++) { // collect samples drawn from pdf into a histogram int sampled_index = to.Sample(); EXPECT_IN_CLOSED(sampled_index, 0, SIZE-1) << "Sample out of bounds."; hist1(sampled_index)++; // collect samples drawn from exp. sampling function into a second histogram float v = sem::randexp(LAMBDA); int bin = static_cast<int>(v*SIZE/PDF_END); // find the right bin for it if(bin < SIZE) { hist2(bin)++; } } EXPECT_EQ(cv::sum(hist1)(0), N); // compare each histogram of drawn samples to original exponential pdf MatF hist1_normalized = hist1/hist1(0); EXPECT_MAT_NEAR(hist1_normalized, pdf, 0.2f); MatF hist2_normalized = hist2/hist2(0); EXPECT_MAT_NEAR(hist2_normalized, pdf, 0.2f); } /** * @brief Compare samples from randexp() with different lambda values */ TEST(ExponentialPDFTest, Lambda) { const float PDF_END=5.; // last x element in pdf function const int SIZE=10, N=2000; // no. of bins, no. of samples to draw const float PDF_SCALE_FACTOR=static_cast<float>(SIZE)/PDF_END; // generate a histogram from sampled values // also sample values from randexp() function std::vector<MatF> hists; // collect samples drawn from exp. sampling function into a second histogram int hist_index=0; for(float lambda=0.5f; lambda<=1.5f; lambda+=0.5f, hist_index++) { hists.push_back(MatF::zeros(1, SIZE)); // initialize histogram counts for(int i=0; i<N; i++) { float v = sem::randexp(lambda); int bin = static_cast<int>(v*PDF_SCALE_FACTOR); // find the right bin for it if(bin < SIZE) { hists[hist_index](bin)++; } } } // compare pdf amplitudes for(int i=1; i<static_cast<int>(hists.size()); i++) { // left part of pdf cv::Mat gt = hists[i] > hists[i-1]; EXPECT_EQ(cv::countNonZero(gt.colRange(0, 2)), 2) << "hist[" << i <<"] <= hist[" << i-1 << "]"; // pdf tail cv::Mat lt = hists[i] < hists[i-1]; EXPECT_EQ(cv::countNonZero(lt.colRange(lt.cols-4, lt.cols-2)), 2) << "hist[" << i <<"] >= hist[" << i-1 << "]"; } } TEST(ExponentialPDFTest, Moments) { const float PDF_END=10.; // last x element in pdf function const int SIZE=50, N=3000; // no. of bins, no. of samples to draw const float PDF_SCALE_FACTOR=static_cast<float>(SIZE)/PDF_END; // generate a histogram from sampled values // also sample values from randexp() function std::vector<MatF> hists; // collect samples drawn from exp. sampling function into a second histogram int hist_index=0; for(float lambda=0.5f; lambda<=1.5f; lambda+=0.5f, hist_index++) { hists.push_back(MatF::zeros(1, SIZE)); // initialize histogram counts for(int i=0; i<N; i++) { float v = sem::randexp(lambda); int bin = static_cast<int>(v*PDF_SCALE_FACTOR); // find the right bin for it if(bin < SIZE) { hists[hist_index](bin)++; } } } // check moments double lambda = 0.5; MatF X(1, SIZE); float x=0.f; for(int i=0; i<SIZE; i++) { X(i) = x; x += 1.f/PDF_SCALE_FACTOR; } for(int i=0; i<static_cast<int>(hists.size()); i++) { MatF pdf; cv::multiply(hists[i], X, pdf); std::cout<<pdf<<std::endl; cv::Mat m, s; cv::meanStdDev(pdf, m, s); std::cout<<"i"<<i<<"m"<<m<<std::endl; EXPECT_NEAR(m.at<double>(0), 1./lambda, 0.01) << lambda; lambda += 0.5; } } } // namespace <commit_msg>add tests around Exponential distribution sampler<commit_after>#include "core/distributionsampler.h" #include <opencv2/imgproc.hpp> #include "core/area.h" #include "ts/ts.h" namespace { TEST(DistrSampler1D, Uniform) { const int SIZE = 10, N = 1e4; const float MEAN = 1.f/static_cast<float>(SIZE); MatF pdf_uniform = MatF::ones(1, SIZE)*MEAN; DistributionSampler1D to; // test object to.pdf(pdf_uniform); MatF hist = MatF::zeros(1, SIZE); for(int i=0; i<N; i++) { int sampled_index = to.Sample(); EXPECT_IN_CLOSED(sampled_index, 0, SIZE-1); hist(sampled_index)++; } EXPECT_EQ(cv::sum(hist)(0), N); MatF hist_normalized = hist/static_cast<float>(N); EXPECT_MAT_NEAR(hist_normalized, pdf_uniform, 0.2f); cv::Mat m, s; cv::meanStdDev(hist_normalized, m, s); EXPECT_NEAR(m.at<double>(0, 0), MEAN, 0.1); EXPECT_NEAR(s.at<double>(0, 0), 0., 0.1); } TEST(DistrSampler1D, Gaussian) { const int SIZE = 10, N=2000; const float MEAN = 5.f, STD_DEV = 2.f; // generate gaussian pdf cv::Mat data(1, N, CV_32FC1); cv::randn(data, MEAN, STD_DEV); float pdf_values[SIZE] = {}; for (int i=0; i<N; i++) { float v = data.at<float>(i); if ( v >= 0.f && v<10.0) { ++pdf_values[static_cast<int>(v)]; } } DistributionSampler1D to; // test object cv::Mat pdf = cv::Mat(1,10, CV_32FC1, pdf_values)/static_cast<float>(N)*SIZE; to.pdf(pdf); MatF hist = MatF::zeros(1, SIZE); for(int i=0; i<N; i++) { int sampled_index = to.Sample(); EXPECT_IN_CLOSED(sampled_index, 0, SIZE-1); hist(sampled_index)++; } EXPECT_EQ(cv::sum(hist)(0), N); MatF hist_normalized = hist/static_cast<float>(N)*SIZE; EXPECT_MAT_NEAR(hist_normalized, pdf, 0.2f); } TEST(DistrSampler2D, Uniform) { const int ROWS = 7, COLS = 10, N = 2e4; const float MEAN = 1.f/static_cast<float>(ROWS*COLS); MatF pdf_uniform = MatF::ones(ROWS, COLS)*MEAN; DistributionSampler2D to; // test object to.pdf(pdf_uniform); MatF hist = MatF::zeros(ROWS, COLS); for(int i=0; i<N; i++) { cv::Point2i sampled_point = to.Sample(); EXPECT_TRUE( sampled_point.inside(cv::Rect(0, 0, COLS, ROWS)) ); hist(sampled_point.y, sampled_point.x)++; } EXPECT_EQ(cv::sum(hist)(0), N); MatF hist_normalized = hist/static_cast<float>(N); EXPECT_MAT_NEAR(hist_normalized, pdf_uniform, 0.2f); cv::Mat m, s; cv::meanStdDev(hist_normalized, m, s); EXPECT_NEAR(m.at<double>(0, 0), MEAN, 0.1); EXPECT_NEAR(s.at<double>(0, 0), 0., 0.1); } class PoissonProcessTest : public testing::Test { protected: PoissonProcessTest() : frequency_(1.f), delta_t_msec_(1000.f), to_(0.f, 0.f) // dummy initialization { } virtual void SetUp() { to_ = PoissonProcess(frequency_, delta_t_msec_); // -ve frequency => inf firing rate, 1 msec time resolution } float frequency_; float delta_t_msec_; PoissonProcess to_; ///< test object }; TEST_F(PoissonProcessTest, PDF) { MatF pdf = to_.pdf(); EXPECT_MAT_DIMS_EQ(pdf, MatF(1, 1)); float lambda = pdf(0, 0); EXPECT_LE(lambda, 0); EXPECT_FLOAT_EQ(lambda, 1.f-frequency_*delta_t_msec_/1000.f); } TEST_F(PoissonProcessTest, Sample) { const int N = 100; for(int i=0; i<N; i++) { EXPECT_EQ(1, to_.Sample()); } } TEST_F(PoissonProcessTest, SampleZeroFreq) { PoissonProcess to(0.f, 1.f); const int N = 100; for(int i=0; i<N; i++) { EXPECT_EQ(0, to.Sample()); } } TEST_F(PoissonProcessTest, SampleZeroDeltaT) { PoissonProcess to(40.f, 0.f); const int N = 100; for(int i=0; i<N; i++) { EXPECT_EQ(0, to.Sample()); } } TEST_F(PoissonProcessTest, SampleZeroFreqAndDeltaT) { PoissonProcess to(0.f, 0.f); const int N = 100; for(int i=0; i<N; i++) { EXPECT_EQ(0, to.Sample()); } } TEST_F(PoissonProcessTest, SampleCoinToss) { PoissonProcess to(50.f, 10.f); const int N = 1e4; int net = 0; for(int i=0; i<N; i++) { net += to.Sample(); } float rate = net/static_cast<float>(N); EXPECT_NEAR(rate, 0.5f, 0.02f); } /** * @brief Compare theoretical pdf for exponential distr. * to pdf generate from 1) pdf sampler 2) randexp() */ TEST(ExponentialPDFTest, Sample) { const double PDF_END=10.; // last x element in pdf function const int SIZE=30, N=2000; // no. of bins, no. of samples to draw const float LAMBDA = 1.f; // generate exponential pdf MatF pdf(1, SIZE); double x = 0.; for (int i=0; i<SIZE; i++, x += PDF_END/static_cast<double>(SIZE)) { double f = exp(-static_cast<double>(LAMBDA)*x); pdf(i) = LAMBDA*static_cast<float>(f); } // add generated pdf to a sampler and draw samples from it DistributionSampler1D to; // test object to.pdf(pdf); // generate a histogram from sampled values // also sample values from randexp() function MatF hist1 = MatF::zeros(1, SIZE); MatF hist2 = MatF::zeros(1, SIZE); for(int i=0; i<N; i++) { // collect samples drawn from pdf into a histogram int sampled_index = to.Sample(); EXPECT_IN_CLOSED(sampled_index, 0, SIZE-1) << "Sample out of bounds."; hist1(sampled_index)++; // collect samples drawn from exp. sampling function into a second histogram float v = sem::randexp(LAMBDA); int bin = static_cast<int>(v*SIZE/PDF_END); // find the right bin for it if(bin < SIZE) { hist2(bin)++; } } EXPECT_EQ(cv::sum(hist1)(0), N); // compare each histogram of drawn samples to original exponential pdf MatF hist1_normalized = hist1/hist1(0); EXPECT_MAT_NEAR(hist1_normalized, pdf, 0.2f); MatF hist2_normalized = hist2/hist2(0); EXPECT_MAT_NEAR(hist2_normalized, pdf, 0.2f); } /** * @brief Compare samples from randexp() with different lambda values */ TEST(ExponentialPDFTest, Lambda) { const float PDF_END=5.; // last x element in pdf function const int SIZE=10, N=2000; // no. of bins, no. of samples to draw const float PDF_SCALE_FACTOR=static_cast<float>(SIZE)/PDF_END; // generate a histogram from sampled values // also sample values from randexp() function std::vector<MatF> hists; // collect samples drawn from exp. sampling function into a second histogram int hist_index=0; for(float lambda=0.5f; lambda<=1.5f; lambda+=0.5f, hist_index++) { hists.push_back(MatF::zeros(1, SIZE)); // initialize histogram counts for(int i=0; i<N; i++) { float v = sem::randexp(lambda); int bin = static_cast<int>(v*PDF_SCALE_FACTOR); // find the right bin for it if(bin < SIZE) { hists[hist_index](bin)++; } } } // compare pdf amplitudes for(int i=1; i<static_cast<int>(hists.size()); i++) { // left part of pdf cv::Mat gt = hists[i] > hists[i-1]; EXPECT_EQ(cv::countNonZero(gt.colRange(0, 2)), 2) << "hist[" << i <<"] <= hist[" << i-1 << "]"; // pdf tail cv::Mat lt = hists[i] < hists[i-1]; EXPECT_EQ(cv::countNonZero(lt.colRange(lt.cols-4, lt.cols-2)), 2) << "hist[" << i <<"] >= hist[" << i-1 << "]"; } } TEST(ExponentialPDFTest, Moments) { const float PDF_END=10.; // last x element in pdf function const int SIZE=50, N=2000; // no. of bins, no. of samples to draw const float PDF_SCALE_FACTOR=static_cast<float>(SIZE)/PDF_END; MatF x(1, SIZE); float x_val = 0.f; for(int i=0; i<SIZE; i++) { x(i) = x_val; x_val += 1.f/PDF_SCALE_FACTOR; } // generate a histogram from sampled values // also sample values from randexp() function std::vector<MatF> hists; // collect samples drawn from exp. sampling function into a second histogram int hist_index=0; for(float lambda=0.5f; lambda<=1.5f; lambda+=0.5f, hist_index++) { hists.push_back(MatF::zeros(1, SIZE)); // initialize histogram counts for(int i=0; i<N; i++) { float v = sem::randexp(lambda); int bin = static_cast<int>(v*PDF_SCALE_FACTOR); // find the right bin for it if(bin < SIZE) { hists[hist_index](bin)++; } } } // check moments double lambda = 0.5; for(int i=0; i<static_cast<int>(hists.size()); i++) { MatF pdf; cv::divide(hists[i], cv::sum(hists[i]/PDF_SCALE_FACTOR)(0), pdf); EXPECT_NEAR(Trapz()(x, pdf), 1.f, 0.2f); lambda += 0.5; } } } // namespace <|endoftext|>
<commit_before>#define LINE_HEADER_SIZE 4096 // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #include "obj_loader.hpp" // Include standard headers #include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc. #include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp #include <iostream> // std::cout, std::cin, std::cerr #include <stdint.h> // uint32_t etc. #include <string> // std::string #include <vector> // std::vector void read_until_newline(std::FILE* file) { while (getc(file) != '\n'); } // Very, VERY simple OBJ loader. // Here is a short list of features a real function would provide : // - Binary files. Reading a model should be just a few memcpy's away, not parsing a file at runtime. In short : OBJ is not very great. // - Animations & bones (includes bones weights) // - Multiple UVs // - All attributes should be optional, not "forced" // - More stable. Change a line in the OBJ file and it crashes. // - More secure. Change another line and you can inject code. // - Loading from memory, stream, etc namespace loaders { bool load_OBJ( const char* path, std::vector<glm::vec3>& out_vertices, std::vector<glm::vec2>& out_UVs, std::vector<glm::vec3>& out_normals) { std::cout << "Loading OBJ file " << path << " ...\n"; std::vector<uint32_t> vertexIndices, uvIndices, normalIndices; std::vector<glm::vec3> temp_vertices; std::vector<glm::vec2> temp_UVs; std::vector<glm::vec3> temp_normals; std::FILE* file = std::fopen(path, "r"); if (file == nullptr) { std::printf("Opening file %s failed!\n", path); return false; } while (true) { char lineHeader[LINE_HEADER_SIZE]; // read the first word of the line int res = fscanf(file, "%s", lineHeader); if (res == EOF) { break; // EOF = End Of File. Quit the loop. } // else : parse lineHeader if (std::strcmp(lineHeader, "#") == 0) { read_until_newline(file); } else if (std::strcmp(lineHeader, "l") == 0) { read_until_newline(file); } else if (std::strcmp(lineHeader, "mtllib") == 0) { // TODO: Add support for `mtllib`! read_until_newline(file); } else if (std::strcmp(lineHeader, "o") == 0) { read_until_newline(file); } else if (std::strcmp(lineHeader, "s") == 0) { read_until_newline(file); } else if (std::strcmp(lineHeader, "usemtl") == 0) { // TODO: Add support for `usemtl`! read_until_newline(file); } else if (std::strcmp(lineHeader, "v") == 0) { // This line specifies a vertex. // Example: // v 1.000000 -1.000000 -1.000000 glm::vec3 vertex; fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z); temp_vertices.push_back(vertex); } else if (std::strcmp(lineHeader, "vt") == 0) { // This line specifies texture coordinate of one vertex. // Example: // vt 0.748573 0.750412 glm::vec2 uv; fscanf(file, "%f %f\n", &uv.x, &uv.y); // uv.y = -uv.y; // Invert V coordinate since we will only use DDS texture, which are inverted. Remove if you want to use TGA or BMP loaders. temp_UVs.push_back(uv); } else if (std::strcmp(lineHeader, "vn") == 0) { // This line specifies the normal of one vertex. // Example: // vn 0.000000 0.000000 -1.000000 glm::vec3 normal; fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z); temp_normals.push_back(normal); } else if (std::strcmp(lineHeader, "f") == 0) { // This line specifies a face. // Example: // f 5/1/1 1/2/1 4/3/1 std::string vertex1, vertex2, vertex3; unsigned int vertexIndex[3], uvIndex[3], normalIndex[3]; int matches = fscanf( file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]); if (matches != 9) { std::printf("File can't be read by our simple parser :-( Try exporting with other options\n"); continue; } vertexIndices.push_back(vertexIndex[0]); vertexIndices.push_back(vertexIndex[1]); vertexIndices.push_back(vertexIndex[2]); uvIndices.push_back(uvIndex[0]); uvIndices.push_back(uvIndex[1]); uvIndices.push_back(uvIndex[2]); normalIndices.push_back(normalIndex[0]); normalIndices.push_back(normalIndex[1]); normalIndices.push_back(normalIndex[2]); } else { // Probably a comment, eat up the rest of the line char stupidBuffer[1000]; fgets(stupidBuffer, 1000, file); } } // For each vertex of each triangle for (unsigned int i = 0; i < vertexIndices.size(); i++) { // Get the indices of its attributes unsigned int vertexIndex = vertexIndices[i]; unsigned int uvIndex = uvIndices[i]; unsigned int normalIndex = normalIndices[i]; // Get the attributes thanks to the index glm::vec3 vertex = temp_vertices[vertexIndex - 1]; glm::vec2 uv = temp_UVs[uvIndex - 1]; glm::vec3 normal = temp_normals[normalIndex - 1]; // Put the attributes in buffers out_vertices.push_back(vertex); out_UVs .push_back(uv); out_normals .push_back(normal); } return true; } } <commit_msg>Bugfix `loaders::load_OBJ`: `std::fclose` before `return true;`.<commit_after>#define LINE_HEADER_SIZE 4096 // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> #endif #include "obj_loader.hpp" // Include standard headers #include <cstdio> // std::FILE, std::fclose, std::fopen, std::fread, std::getchar, std::printf etc. #include <cstring> // std::memcmp, std::strcmp, std::strlen, std::strncmp #include <iostream> // std::cout, std::cin, std::cerr #include <stdint.h> // uint32_t etc. #include <string> // std::string #include <vector> // std::vector void read_until_newline(std::FILE* file) { while (getc(file) != '\n'); } // Very, VERY simple OBJ loader. // Here is a short list of features a real function would provide : // - Binary files. Reading a model should be just a few memcpy's away, not parsing a file at runtime. In short : OBJ is not very great. // - Animations & bones (includes bones weights) // - Multiple UVs // - All attributes should be optional, not "forced" // - More stable. Change a line in the OBJ file and it crashes. // - More secure. Change another line and you can inject code. // - Loading from memory, stream, etc namespace loaders { bool load_OBJ( const char* path, std::vector<glm::vec3>& out_vertices, std::vector<glm::vec2>& out_UVs, std::vector<glm::vec3>& out_normals) { std::cout << "Loading OBJ file " << path << " ...\n"; std::vector<uint32_t> vertexIndices, uvIndices, normalIndices; std::vector<glm::vec3> temp_vertices; std::vector<glm::vec2> temp_UVs; std::vector<glm::vec3> temp_normals; std::FILE* file = std::fopen(path, "r"); if (file == nullptr) { std::printf("Opening file %s failed!\n", path); return false; } while (true) { char lineHeader[LINE_HEADER_SIZE]; // read the first word of the line int res = fscanf(file, "%s", lineHeader); if (res == EOF) { break; // EOF = End Of File. Quit the loop. } // else : parse lineHeader if (std::strcmp(lineHeader, "#") == 0) { read_until_newline(file); } else if (std::strcmp(lineHeader, "l") == 0) { read_until_newline(file); } else if (std::strcmp(lineHeader, "mtllib") == 0) { // TODO: Add support for `mtllib`! read_until_newline(file); } else if (std::strcmp(lineHeader, "o") == 0) { read_until_newline(file); } else if (std::strcmp(lineHeader, "s") == 0) { read_until_newline(file); } else if (std::strcmp(lineHeader, "usemtl") == 0) { // TODO: Add support for `usemtl`! read_until_newline(file); } else if (std::strcmp(lineHeader, "v") == 0) { // This line specifies a vertex. // Example: // v 1.000000 -1.000000 -1.000000 glm::vec3 vertex; fscanf(file, "%f %f %f\n", &vertex.x, &vertex.y, &vertex.z); temp_vertices.push_back(vertex); } else if (std::strcmp(lineHeader, "vt") == 0) { // This line specifies texture coordinate of one vertex. // Example: // vt 0.748573 0.750412 glm::vec2 uv; fscanf(file, "%f %f\n", &uv.x, &uv.y); // uv.y = -uv.y; // Invert V coordinate since we will only use DDS texture, which are inverted. Remove if you want to use TGA or BMP loaders. temp_UVs.push_back(uv); } else if (std::strcmp(lineHeader, "vn") == 0) { // This line specifies the normal of one vertex. // Example: // vn 0.000000 0.000000 -1.000000 glm::vec3 normal; fscanf(file, "%f %f %f\n", &normal.x, &normal.y, &normal.z); temp_normals.push_back(normal); } else if (std::strcmp(lineHeader, "f") == 0) { // This line specifies a face. // Example: // f 5/1/1 1/2/1 4/3/1 std::string vertex1, vertex2, vertex3; unsigned int vertexIndex[3], uvIndex[3], normalIndex[3]; int matches = fscanf( file, "%d/%d/%d %d/%d/%d %d/%d/%d\n", &vertexIndex[0], &uvIndex[0], &normalIndex[0], &vertexIndex[1], &uvIndex[1], &normalIndex[1], &vertexIndex[2], &uvIndex[2], &normalIndex[2]); if (matches != 9) { std::printf("File can't be read by our simple parser :-( Try exporting with other options\n"); continue; } vertexIndices.push_back(vertexIndex[0]); vertexIndices.push_back(vertexIndex[1]); vertexIndices.push_back(vertexIndex[2]); uvIndices.push_back(uvIndex[0]); uvIndices.push_back(uvIndex[1]); uvIndices.push_back(uvIndex[2]); normalIndices.push_back(normalIndex[0]); normalIndices.push_back(normalIndex[1]); normalIndices.push_back(normalIndex[2]); } else { // Probably a comment, eat up the rest of the line char stupidBuffer[1000]; fgets(stupidBuffer, 1000, file); } } // For each vertex of each triangle for (unsigned int i = 0; i < vertexIndices.size(); i++) { // Get the indices of its attributes unsigned int vertexIndex = vertexIndices[i]; unsigned int uvIndex = uvIndices[i]; unsigned int normalIndex = normalIndices[i]; // Get the attributes thanks to the index glm::vec3 vertex = temp_vertices[vertexIndex - 1]; glm::vec2 uv = temp_UVs[uvIndex - 1]; glm::vec3 normal = temp_normals[normalIndex - 1]; // Put the attributes in buffers out_vertices.push_back(vertex); out_UVs .push_back(uv); out_normals .push_back(normal); } std::fclose(file); return true; } } <|endoftext|>
<commit_before>#include "holobiont.hpp" #include "symbiosis.hpp" #include "biont.hpp" #include "entity_templates.hpp" #include "render_templates.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif // Include standard headers #include <iostream> // std::cout, std::cin, std::cerr #include <stdint.h> // uint32_t etc. #include <string> // std::string namespace ontology { class Entity; void Holobiont::bind_biont(ontology::Biont* const biont) { // get `childID` from `Holobiont` and set pointer to `object`. hierarchy::bind_child_to_parent<ontology::Biont*>( biont, this->biont_pointer_vector, this->free_biontID_queue, &this->number_of_bionts); } void Holobiont::unbind_biont(const int32_t childID) { ontology::Biont* dummy_child_pointer = nullptr; hierarchy::set_child_pointer( childID, dummy_child_pointer, this->biont_pointer_vector, this->free_biontID_queue, &this->number_of_bionts); } void Holobiont::bind_to_parent() { // get `childID` from `Symbiosis` and set pointer to this `Holobiont`. this->symbiosis_parent->bind_holobiont(this); } void Holobiont::bind_to_new_parent(ontology::Symbiosis* const new_parent) { // this method sets pointer to this `Object` to nullptr, sets `parent` according to the input, // and requests a new `childID` from the new `Symbiosis`. // unbind from the old parent `Model`. this->symbiosis_parent->unbind_holobiont(this->childID); // get `childID` from `Model` and set pointer to this `Object`. new_parent->bind_holobiont(this); } Holobiont::~Holobiont() { // destructor. // set pointer to this `Holobiont` to nullptr. std::cout << "Holobiont with childID " << std::dec << this->childID << " will be destroyed.\n"; this->symbiosis_parent->set_holobiont_pointer(this->childID, nullptr); } void Holobiont::render() { // render this `Holobiont`. if (this->should_ylikuutio_render_this_holobiont) { this->prerender(); // render this `Scene` by calling `render()` function of each `Biont`. ontology::render_children<ontology::Biont*>(this->biont_pointer_vector); this->postrender(); } } void Holobiont::create_bionts() { std::cout << "Creating bionts for Holobiont located at 0x" << std::hex << (uint64_t) this << std::dec << " ...\n"; // Create `Biont` entities so that // they bind this `Holobiont`. int32_t correct_number_of_bionts = this->symbiosis_parent->get_number_of_symbionts(); std::cout << "Number of bionts to be created: " << correct_number_of_bionts << "\n"; for (int32_t biontID = 0; biontID < correct_number_of_bionts; biontID++) { BiontStruct biont_struct; biont_struct.biontID = biontID; biont_struct.holobiont_parent = this; biont_struct.original_scale_vector = this->original_scale_vector; biont_struct.rotate_angle = this->rotate_angle; biont_struct.rotate_vector = this->rotate_vector; biont_struct.initial_rotate_angle = this->initial_rotate_angle; biont_struct.initial_rotate_vector = this->initial_rotate_vector; biont_struct.quaternions_in_use = this->quaternions_in_use; biont_struct.cartesian_coordinates = this->cartesian_coordinates; biont_struct.translate_vector = this->translate_vector; biont_struct.texture = this->symbiosis_parent->get_texture(biontID); std::cout << "Creating biont with biontID " << biontID << " ...\n"; ontology::Biont* biont = new ontology::Biont(this->universe, biont_struct); } } ontology::Entity* Holobiont::get_parent() const { return this->symbiosis_parent; } int32_t Holobiont::get_number_of_children() const { return this->number_of_bionts; } int32_t Holobiont::get_number_of_descendants() const { return 0; } void Holobiont::set_biont_pointer(const int32_t childID, ontology::Biont* const child_pointer) { hierarchy::set_child_pointer(childID, child_pointer, this->biont_pointer_vector, this->free_biontID_queue, &this->number_of_bionts); } void Holobiont::set_name(const std::string& name) { ontology::set_name(name, this); } } <commit_msg>Bugfix: all `Biont`s of a `Holobiont` have right cartesian coordinates.<commit_after>#include "holobiont.hpp" #include "symbiosis.hpp" #include "biont.hpp" #include "entity_templates.hpp" #include "render_templates.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif // Include standard headers #include <iostream> // std::cout, std::cin, std::cerr #include <stdint.h> // uint32_t etc. #include <string> // std::string namespace ontology { class Entity; void Holobiont::bind_biont(ontology::Biont* const biont) { // get `childID` from `Holobiont` and set pointer to `object`. hierarchy::bind_child_to_parent<ontology::Biont*>( biont, this->biont_pointer_vector, this->free_biontID_queue, &this->number_of_bionts); } void Holobiont::unbind_biont(const int32_t childID) { ontology::Biont* dummy_child_pointer = nullptr; hierarchy::set_child_pointer( childID, dummy_child_pointer, this->biont_pointer_vector, this->free_biontID_queue, &this->number_of_bionts); } void Holobiont::bind_to_parent() { // get `childID` from `Symbiosis` and set pointer to this `Holobiont`. this->symbiosis_parent->bind_holobiont(this); } void Holobiont::bind_to_new_parent(ontology::Symbiosis* const new_parent) { // this method sets pointer to this `Object` to nullptr, sets `parent` according to the input, // and requests a new `childID` from the new `Symbiosis`. // unbind from the old parent `Model`. this->symbiosis_parent->unbind_holobiont(this->childID); // get `childID` from `Model` and set pointer to this `Object`. new_parent->bind_holobiont(this); } Holobiont::~Holobiont() { // destructor. // set pointer to this `Holobiont` to nullptr. std::cout << "Holobiont with childID " << std::dec << this->childID << " will be destroyed.\n"; this->symbiosis_parent->set_holobiont_pointer(this->childID, nullptr); } void Holobiont::render() { // render this `Holobiont`. if (this->should_ylikuutio_render_this_holobiont) { this->prerender(); // render this `Scene` by calling `render()` function of each `Biont`. ontology::render_children<ontology::Biont*>(this->biont_pointer_vector); this->postrender(); } } void Holobiont::create_bionts() { std::cout << "Creating bionts for Holobiont located at 0x" << std::hex << (uint64_t) this << std::dec << " ...\n"; // Create `Biont` entities so that // they bind this `Holobiont`. int32_t correct_number_of_bionts = this->symbiosis_parent->get_number_of_symbionts(); std::cout << "Number of bionts to be created: " << correct_number_of_bionts << "\n"; for (int32_t biontID = 0; biontID < correct_number_of_bionts; biontID++) { BiontStruct biont_struct; biont_struct.biontID = biontID; biont_struct.holobiont_parent = this; biont_struct.original_scale_vector = this->original_scale_vector; biont_struct.rotate_angle = this->rotate_angle; biont_struct.rotate_vector = this->rotate_vector; biont_struct.initial_rotate_angle = this->initial_rotate_angle; biont_struct.initial_rotate_vector = this->initial_rotate_vector; biont_struct.quaternions_in_use = this->quaternions_in_use; biont_struct.cartesian_coordinates = std::make_shared<glm::vec3>(*this->cartesian_coordinates); biont_struct.translate_vector = this->translate_vector; biont_struct.texture = this->symbiosis_parent->get_texture(biontID); std::cout << "Creating biont with biontID " << biontID << " ...\n"; ontology::Biont* biont = new ontology::Biont(this->universe, biont_struct); } } ontology::Entity* Holobiont::get_parent() const { return this->symbiosis_parent; } int32_t Holobiont::get_number_of_children() const { return this->number_of_bionts; } int32_t Holobiont::get_number_of_descendants() const { return 0; } void Holobiont::set_biont_pointer(const int32_t childID, ontology::Biont* const child_pointer) { hierarchy::set_child_pointer(childID, child_pointer, this->biont_pointer_vector, this->free_biontID_queue, &this->number_of_bionts); } void Holobiont::set_name(const std::string& name) { ontology::set_name(name, this); } } <|endoftext|>
<commit_before>#include "symbiosis.hpp" #include "shader.hpp" #include "symbiont_material.hpp" #include "symbiont_species.hpp" #include "holobiont.hpp" #include "material_struct.hpp" #include "render_templates.hpp" #include "family_templates.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" #include <ofbx.h> // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> // GLfloat, GLuint etc. #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <GLFW/glfw3.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif // Include standard headers #include <cstddef> // std::size_t #include <iostream> // std::cout, std::cin, std::cerr #include <stdint.h> // uint32_t etc. #include <string> // std::string #include <vector> // std::vector namespace yli { namespace ontology { class Holobiont; void Symbiosis::bind_symbiont_material(yli::ontology::SymbiontMaterial* const symbiont_material) { // get `childID` from `Symbiosis` and set pointer to `symbiont_material`. yli::hierarchy::bind_child_to_parent<yli::ontology::SymbiontMaterial*>( symbiont_material, this->symbiont_material_pointer_vector, this->free_symbiont_materialID_queue, this->number_of_symbiont_materials); } void Symbiosis::unbind_symbiont_material(const std::size_t childID) { yli::hierarchy::unbind_child_from_parent( childID, this->symbiont_material_pointer_vector, this->free_symbiont_materialID_queue, this->number_of_symbiont_materials); } void Symbiosis::bind_holobiont(yli::ontology::Holobiont* const holobiont) { // get `childID` from `Symbiosis` and set pointer to `holobiont`. yli::hierarchy::bind_child_to_parent<yli::ontology::Holobiont*>( holobiont, this->holobiont_pointer_vector, this->free_holobiontID_queue, this->number_of_holobionts); } void Symbiosis::unbind_holobiont(const std::size_t childID) { yli::hierarchy::unbind_child_from_parent( childID, this->holobiont_pointer_vector, this->free_holobiontID_queue, this->number_of_holobionts); } void Symbiosis::bind_to_parent() { // get `childID` from `Shader` and set pointer to this `Symbiosis`. this->parent->bind_symbiosis(this); } void Symbiosis::bind_to_new_parent(yli::ontology::Shader* const new_shader_pointer) { // unbind from the old parent `Shader`. this->parent->unbind_symbiosis(this->childID); // get `childID` from `Shader` and set pointer to this `Symbiosis`. this->parent = new_shader_pointer; this->parent->bind_symbiosis(this); } Symbiosis::~Symbiosis() { // destructor. std::cout << "Symbiosis with childID " << std::dec << this->childID << " will be destroyed.\n"; // destroy all `Holobiont`s of this `Symbiosis`. std::cout << "All holobionts of this symbiosis will be destroyed.\n"; yli::hierarchy::delete_children<yli::ontology::Holobiont*>(this->holobiont_pointer_vector, this->number_of_holobionts); // destroy all `SymbiontMaterial`s of this `Symbiosis`. std::cout << "All symbiont materials of this symbiosis will be destroyed.\n"; yli::hierarchy::delete_children<yli::ontology::SymbiontMaterial*>(this->symbiont_material_pointer_vector, this->number_of_symbiont_materials); // set pointer to this `Symbiosis` to `nullptr`. this->parent->set_symbiosis_pointer(this->childID, nullptr); } void Symbiosis::render() { if (this->vram_buffer_in_use) { this->prerender(); // render this `Symbiosis` by calling `render()` function of each `Holobiont`. yli::ontology::render_children<yli::ontology::Holobiont*>(this->holobiont_pointer_vector); this->postrender(); } } yli::ontology::Entity* Symbiosis::get_parent() const { return this->parent; } std::size_t Symbiosis::get_number_of_children() const { return this->number_of_symbiont_materials + this->number_of_holobionts; } std::size_t Symbiosis::get_number_of_descendants() const { return yli::ontology::get_number_of_descendants(this->symbiont_material_pointer_vector) + yli::ontology::get_number_of_descendants(this->holobiont_pointer_vector); } const std::string& Symbiosis::get_model_file_format() { return this->model_file_format; } void Symbiosis::set_symbiont_material_pointer(const std::size_t childID, yli::ontology::SymbiontMaterial* const child_pointer) { yli::hierarchy::set_child_pointer( childID, child_pointer, this->symbiont_material_pointer_vector, this->free_symbiont_materialID_queue, this->number_of_symbiont_materials); } void Symbiosis::set_holobiont_pointer(const std::size_t childID, yli::ontology::Holobiont* const child_pointer) { yli::hierarchy::set_child_pointer( childID, child_pointer, this->holobiont_pointer_vector, this->free_holobiontID_queue, this->number_of_holobionts); } void Symbiosis::create_symbionts() { SymbiosisLoaderStruct symbiosis_loader_struct; symbiosis_loader_struct.model_filename = this->model_filename; symbiosis_loader_struct.model_file_format = this->model_file_format; symbiosis_loader_struct.triangulation_type = this->triangulation_type; const bool is_debug_mode = true; if (yli::loaders::load_symbiosis( symbiosis_loader_struct, this->vertices, this->uvs, this->normals, this->indices, this->indexed_vertices, this->indexed_uvs, this->indexed_normals, this->ofbx_diffuse_texture_mesh_map, this->ofbx_meshes, this->ofbx_diffuse_texture_vector, this->ofbx_normal_texture_vector, this->ofbx_count_texture_vector, this->ofbx_mesh_count, this->vram_buffer_in_use, is_debug_mode)) { std::cout << "number of meshes: " << this->ofbx_mesh_count << "\n"; std::vector<const ofbx::Texture*> ofbx_diffuse_texture_pointer_vector; ofbx_diffuse_texture_pointer_vector.reserve(this->ofbx_diffuse_texture_mesh_map.size()); this->biontID_symbiont_material_vector.resize(this->ofbx_mesh_count); this->biontID_symbiont_species_vector.resize(this->ofbx_mesh_count); for (auto key_and_value : this->ofbx_diffuse_texture_mesh_map) { ofbx_diffuse_texture_pointer_vector.push_back(key_and_value.first); // key. } // Create `SymbiontMaterial`s. for (const ofbx::Texture* ofbx_texture : ofbx_diffuse_texture_pointer_vector) { if (ofbx_texture == nullptr) { continue; } std::cout << "Creating yli::ontology::SymbiontMaterial* based on ofbx::Texture* at 0x" << std::hex << (uint64_t) ofbx_texture << std::dec << " ...\n"; MaterialStruct material_struct; material_struct.shader = this->parent; material_struct.symbiosis = this; material_struct.is_symbiont_material = true; material_struct.ofbx_texture = ofbx_texture; yli::ontology::SymbiontMaterial* symbiont_material = new yli::ontology::SymbiontMaterial(this->universe, material_struct); symbiont_material->load_texture(); std::cout << "yli::ontology::SymbiontMaterial* successfully created.\n"; // Create `SymbiontSpecies`s. // Care only about `ofbx::Texture*`s which are DIFFUSE textures. for (std::size_t mesh_i : this->ofbx_diffuse_texture_mesh_map.at(ofbx_texture)) { SpeciesStruct species_struct; species_struct.is_symbiont_species = true; species_struct.scene = static_cast<yli::ontology::Scene*>(this->parent->get_parent()); species_struct.shader = this->parent; species_struct.symbiont_material = symbiont_material; species_struct.vertex_count = mesh_i < this->vertices.size() ? this->vertices.at(mesh_i).size() : 0; species_struct.vertices = mesh_i < this->vertices.size() ? this->vertices.at(mesh_i) : std::vector<glm::vec3>(); species_struct.uvs = mesh_i < this->uvs.size() ? this->uvs.at(mesh_i) : std::vector<glm::vec2>(); species_struct.normals = mesh_i < this->normals.size() ? this->normals.at(mesh_i) : std::vector<glm::vec3>(); species_struct.light_position = this->light_position; std::cout << "Creating yli::ontology::SymbiontSpecies*, mesh index " << mesh_i << "...\n"; yli::ontology::SymbiontSpecies* symbiont_species = new yli::ontology::SymbiontSpecies(this->universe, species_struct); std::cout << "yli::ontology::SymbiontSpecies*, mesh index " << mesh_i << " successfully created.\n"; std::cout << "storing yli::ontology::SymbiontMaterial* symbiont_material into vector with mesh_i " << mesh_i << " ...\n"; this->biontID_symbiont_material_vector.at(mesh_i) = symbiont_material; std::cout << "storing yli::ontology::SymbiontSpecies* symbiont_species into vector with mesh_i " << mesh_i << " ...\n"; this->biontID_symbiont_species_vector.at(mesh_i) = symbiont_species; std::cout << "Success.\n"; // TODO: Compute the graph of each type to enable object vertex modification! } } std::cout << "All symbionts successfully created.\n"; } } yli::ontology::SymbiontSpecies* Symbiosis::get_symbiont_species(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID); } GLuint Symbiosis::get_vertex_position_modelspaceID(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_vertex_position_modelspaceID(); } GLuint Symbiosis::get_vertexUVID(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_vertexUVID(); } GLuint Symbiosis::get_vertex_normal_modelspaceID(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_vertex_normal_modelspaceID(); } GLuint Symbiosis::get_vertexbuffer(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_vertexbuffer(); } GLuint Symbiosis::get_uvbuffer(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_uvbuffer(); } GLuint Symbiosis::get_normalbuffer(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_normalbuffer(); } GLuint Symbiosis::get_elementbuffer(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_elementbuffer(); } std::vector<uint32_t> Symbiosis::get_indices(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_indices(); // return this->indices.at(biontID); } std::size_t Symbiosis::get_indices_size(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_indices_size(); // return this->indices.at(biontID).size(); } std::size_t Symbiosis::get_number_of_symbionts() const { return this->ofbx_mesh_count; } bool Symbiosis::has_texture(const std::size_t biontID) const { if (biontID >= this->biontID_symbiont_material_vector.size()) { return false; } if (this->biontID_symbiont_material_vector.at(biontID) == nullptr) { return false; } return true; } GLuint Symbiosis::get_texture(const std::size_t biontID) const { return this->biontID_symbiont_material_vector.at(biontID)->get_texture(); } GLuint Symbiosis::get_openGL_textureID(const std::size_t biontID) const { return this->biontID_symbiont_material_vector.at(biontID)->get_openGL_textureID(); } GLuint Symbiosis::get_lightID(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_lightID(); } glm::vec3 Symbiosis::get_light_position(const std::size_t biontID) const { return this->light_position; } } } <commit_msg>`Symbiosis::bind_to_parent`: check `this->parent` for `nullptr`.<commit_after>#include "symbiosis.hpp" #include "shader.hpp" #include "symbiont_material.hpp" #include "symbiont_species.hpp" #include "holobiont.hpp" #include "material_struct.hpp" #include "render_templates.hpp" #include "family_templates.hpp" #include "code/ylikuutio/hierarchy/hierarchy_templates.hpp" #include <ofbx.h> // Include GLEW #ifndef __GL_GLEW_H_INCLUDED #define __GL_GLEW_H_INCLUDED #include <GL/glew.h> // GLfloat, GLuint etc. #endif // Include GLFW #ifndef __GLFW3_H_INCLUDED #define __GLFW3_H_INCLUDED #include <GLFW/glfw3.h> #endif // Include GLM #ifndef __GLM_GLM_HPP_INCLUDED #define __GLM_GLM_HPP_INCLUDED #include <glm/glm.hpp> // glm #endif // Include standard headers #include <cstddef> // std::size_t #include <iostream> // std::cout, std::cin, std::cerr #include <stdint.h> // uint32_t etc. #include <string> // std::string #include <vector> // std::vector namespace yli { namespace ontology { class Holobiont; void Symbiosis::bind_symbiont_material(yli::ontology::SymbiontMaterial* const symbiont_material) { // get `childID` from `Symbiosis` and set pointer to `symbiont_material`. yli::hierarchy::bind_child_to_parent<yli::ontology::SymbiontMaterial*>( symbiont_material, this->symbiont_material_pointer_vector, this->free_symbiont_materialID_queue, this->number_of_symbiont_materials); } void Symbiosis::unbind_symbiont_material(const std::size_t childID) { yli::hierarchy::unbind_child_from_parent( childID, this->symbiont_material_pointer_vector, this->free_symbiont_materialID_queue, this->number_of_symbiont_materials); } void Symbiosis::bind_holobiont(yli::ontology::Holobiont* const holobiont) { // get `childID` from `Symbiosis` and set pointer to `holobiont`. yli::hierarchy::bind_child_to_parent<yli::ontology::Holobiont*>( holobiont, this->holobiont_pointer_vector, this->free_holobiontID_queue, this->number_of_holobionts); } void Symbiosis::unbind_holobiont(const std::size_t childID) { yli::hierarchy::unbind_child_from_parent( childID, this->holobiont_pointer_vector, this->free_holobiontID_queue, this->number_of_holobionts); } void Symbiosis::bind_to_parent() { // requirements: // `this->parent` must not be `nullptr`. yli::ontology::Shader* const shader = this->parent; if (shader == nullptr) { std::cerr << "ERROR: `Symbiosis::bind_to_parent`: `shader` is `nullptr`!\n"; return; } // get `childID` from `Shader` and set pointer to this `Symbiosis`. shader->bind_symbiosis(this); } void Symbiosis::bind_to_new_parent(yli::ontology::Shader* const new_shader_pointer) { // unbind from the old parent `Shader`. this->parent->unbind_symbiosis(this->childID); // get `childID` from `Shader` and set pointer to this `Symbiosis`. this->parent = new_shader_pointer; this->parent->bind_symbiosis(this); } Symbiosis::~Symbiosis() { // destructor. std::cout << "Symbiosis with childID " << std::dec << this->childID << " will be destroyed.\n"; // destroy all `Holobiont`s of this `Symbiosis`. std::cout << "All holobionts of this symbiosis will be destroyed.\n"; yli::hierarchy::delete_children<yli::ontology::Holobiont*>(this->holobiont_pointer_vector, this->number_of_holobionts); // destroy all `SymbiontMaterial`s of this `Symbiosis`. std::cout << "All symbiont materials of this symbiosis will be destroyed.\n"; yli::hierarchy::delete_children<yli::ontology::SymbiontMaterial*>(this->symbiont_material_pointer_vector, this->number_of_symbiont_materials); // set pointer to this `Symbiosis` to `nullptr`. this->parent->set_symbiosis_pointer(this->childID, nullptr); } void Symbiosis::render() { if (this->vram_buffer_in_use) { this->prerender(); // render this `Symbiosis` by calling `render()` function of each `Holobiont`. yli::ontology::render_children<yli::ontology::Holobiont*>(this->holobiont_pointer_vector); this->postrender(); } } yli::ontology::Entity* Symbiosis::get_parent() const { return this->parent; } std::size_t Symbiosis::get_number_of_children() const { return this->number_of_symbiont_materials + this->number_of_holobionts; } std::size_t Symbiosis::get_number_of_descendants() const { return yli::ontology::get_number_of_descendants(this->symbiont_material_pointer_vector) + yli::ontology::get_number_of_descendants(this->holobiont_pointer_vector); } const std::string& Symbiosis::get_model_file_format() { return this->model_file_format; } void Symbiosis::set_symbiont_material_pointer(const std::size_t childID, yli::ontology::SymbiontMaterial* const child_pointer) { yli::hierarchy::set_child_pointer( childID, child_pointer, this->symbiont_material_pointer_vector, this->free_symbiont_materialID_queue, this->number_of_symbiont_materials); } void Symbiosis::set_holobiont_pointer(const std::size_t childID, yli::ontology::Holobiont* const child_pointer) { yli::hierarchy::set_child_pointer( childID, child_pointer, this->holobiont_pointer_vector, this->free_holobiontID_queue, this->number_of_holobionts); } void Symbiosis::create_symbionts() { SymbiosisLoaderStruct symbiosis_loader_struct; symbiosis_loader_struct.model_filename = this->model_filename; symbiosis_loader_struct.model_file_format = this->model_file_format; symbiosis_loader_struct.triangulation_type = this->triangulation_type; const bool is_debug_mode = true; if (yli::loaders::load_symbiosis( symbiosis_loader_struct, this->vertices, this->uvs, this->normals, this->indices, this->indexed_vertices, this->indexed_uvs, this->indexed_normals, this->ofbx_diffuse_texture_mesh_map, this->ofbx_meshes, this->ofbx_diffuse_texture_vector, this->ofbx_normal_texture_vector, this->ofbx_count_texture_vector, this->ofbx_mesh_count, this->vram_buffer_in_use, is_debug_mode)) { std::cout << "number of meshes: " << this->ofbx_mesh_count << "\n"; std::vector<const ofbx::Texture*> ofbx_diffuse_texture_pointer_vector; ofbx_diffuse_texture_pointer_vector.reserve(this->ofbx_diffuse_texture_mesh_map.size()); this->biontID_symbiont_material_vector.resize(this->ofbx_mesh_count); this->biontID_symbiont_species_vector.resize(this->ofbx_mesh_count); for (auto key_and_value : this->ofbx_diffuse_texture_mesh_map) { ofbx_diffuse_texture_pointer_vector.push_back(key_and_value.first); // key. } // Create `SymbiontMaterial`s. for (const ofbx::Texture* ofbx_texture : ofbx_diffuse_texture_pointer_vector) { if (ofbx_texture == nullptr) { continue; } std::cout << "Creating yli::ontology::SymbiontMaterial* based on ofbx::Texture* at 0x" << std::hex << (uint64_t) ofbx_texture << std::dec << " ...\n"; MaterialStruct material_struct; material_struct.shader = this->parent; material_struct.symbiosis = this; material_struct.is_symbiont_material = true; material_struct.ofbx_texture = ofbx_texture; yli::ontology::SymbiontMaterial* symbiont_material = new yli::ontology::SymbiontMaterial(this->universe, material_struct); symbiont_material->load_texture(); std::cout << "yli::ontology::SymbiontMaterial* successfully created.\n"; // Create `SymbiontSpecies`s. // Care only about `ofbx::Texture*`s which are DIFFUSE textures. for (std::size_t mesh_i : this->ofbx_diffuse_texture_mesh_map.at(ofbx_texture)) { SpeciesStruct species_struct; species_struct.is_symbiont_species = true; species_struct.scene = static_cast<yli::ontology::Scene*>(this->parent->get_parent()); species_struct.shader = this->parent; species_struct.symbiont_material = symbiont_material; species_struct.vertex_count = mesh_i < this->vertices.size() ? this->vertices.at(mesh_i).size() : 0; species_struct.vertices = mesh_i < this->vertices.size() ? this->vertices.at(mesh_i) : std::vector<glm::vec3>(); species_struct.uvs = mesh_i < this->uvs.size() ? this->uvs.at(mesh_i) : std::vector<glm::vec2>(); species_struct.normals = mesh_i < this->normals.size() ? this->normals.at(mesh_i) : std::vector<glm::vec3>(); species_struct.light_position = this->light_position; std::cout << "Creating yli::ontology::SymbiontSpecies*, mesh index " << mesh_i << "...\n"; yli::ontology::SymbiontSpecies* symbiont_species = new yli::ontology::SymbiontSpecies(this->universe, species_struct); std::cout << "yli::ontology::SymbiontSpecies*, mesh index " << mesh_i << " successfully created.\n"; std::cout << "storing yli::ontology::SymbiontMaterial* symbiont_material into vector with mesh_i " << mesh_i << " ...\n"; this->biontID_symbiont_material_vector.at(mesh_i) = symbiont_material; std::cout << "storing yli::ontology::SymbiontSpecies* symbiont_species into vector with mesh_i " << mesh_i << " ...\n"; this->biontID_symbiont_species_vector.at(mesh_i) = symbiont_species; std::cout << "Success.\n"; // TODO: Compute the graph of each type to enable object vertex modification! } } std::cout << "All symbionts successfully created.\n"; } } yli::ontology::SymbiontSpecies* Symbiosis::get_symbiont_species(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID); } GLuint Symbiosis::get_vertex_position_modelspaceID(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_vertex_position_modelspaceID(); } GLuint Symbiosis::get_vertexUVID(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_vertexUVID(); } GLuint Symbiosis::get_vertex_normal_modelspaceID(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_vertex_normal_modelspaceID(); } GLuint Symbiosis::get_vertexbuffer(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_vertexbuffer(); } GLuint Symbiosis::get_uvbuffer(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_uvbuffer(); } GLuint Symbiosis::get_normalbuffer(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_normalbuffer(); } GLuint Symbiosis::get_elementbuffer(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_elementbuffer(); } std::vector<uint32_t> Symbiosis::get_indices(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_indices(); // return this->indices.at(biontID); } std::size_t Symbiosis::get_indices_size(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_indices_size(); // return this->indices.at(biontID).size(); } std::size_t Symbiosis::get_number_of_symbionts() const { return this->ofbx_mesh_count; } bool Symbiosis::has_texture(const std::size_t biontID) const { if (biontID >= this->biontID_symbiont_material_vector.size()) { return false; } if (this->biontID_symbiont_material_vector.at(biontID) == nullptr) { return false; } return true; } GLuint Symbiosis::get_texture(const std::size_t biontID) const { return this->biontID_symbiont_material_vector.at(biontID)->get_texture(); } GLuint Symbiosis::get_openGL_textureID(const std::size_t biontID) const { return this->biontID_symbiont_material_vector.at(biontID)->get_openGL_textureID(); } GLuint Symbiosis::get_lightID(const std::size_t biontID) const { return this->biontID_symbiont_species_vector.at(biontID)->get_lightID(); } glm::vec3 Symbiosis::get_light_position(const std::size_t biontID) const { return this->light_position; } } } <|endoftext|>
<commit_before>#include <iostream> #include <map> #include <execinfo.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <chrono> #include "fscore.h" using namespace fs; using namespace std; using namespace chrono; using SdlArena = MemoryArena<Allocator<HeapAllocator, AllocationHeaderU32>, MultiThread<MutexPrimitive>, SimpleBoundsChecking, FullMemoryTracking, MemoryTagging>; template<class Allocator> void allocator_ManySmallAllocations_InOrder_NoFree(const char* allocatorType) { FS_PRINT(allocatorType); const size_t allocationSize = 64; const size_t allocationAlignment = 8; HeapArea area(FS_SIZE_OF_MB * 8); Allocator allocator(area.getStart(), area.getEnd()); auto start = steady_clock::now(); for(i32 i = FS_SIZE_OF_MB * 7 / allocationSize; i > 0; --i) { allocator.allocate(allocationSize, allocationAlignment, 0); } auto end = steady_clock::now(); auto allocatorTime = duration<double, milli>(end - start).count(); FS_PRINT(allocatorTime << " ms"); FS_PRINT(""); } int main( int, char **) { //Logger::init("content/logger.xml"); FS_PRINT("allocator_ManySmallAllocations_InOrder_NoFree"); allocator_ManySmallAllocations_InOrder_NoFree<LinearAllocator>("LinearAllocator"); allocator_ManySmallAllocations_InOrder_NoFree<StackAllocatorBottom>("StackAllocatorBottom"); allocator_ManySmallAllocations_InOrder_NoFree<StackAllocatorTop>("StackAllocatorTop"); allocator_ManySmallAllocations_InOrder_NoFree<HeapAllocator>("HeapAllocator"); allocator_ManySmallAllocations_InOrder_NoFree<PoolAllocatorNonGrowable<64, 8>>("PoolAllocator"); allocator_ManySmallAllocations_InOrder_NoFree<MallocAllocator>("MallocAllocator"); //Logger::destroy(); return 0; } <commit_msg>WIP on allocator benchmarks<commit_after>#include <iostream> #include <map> #include <execinfo.h> #include <stdio.h> #include <stdlib.h> #include <iostream> #include <chrono> #include <thread> #include <cstdlib> #include "fscore.h" using namespace fs; using namespace std; using namespace chrono; using SdlArena = MemoryArena<Allocator<HeapAllocator, AllocationHeaderU32>, MultiThread<MutexPrimitive>, SimpleBoundsChecking, FullMemoryTracking, MemoryTagging>; template<class Allocator> void allocator_ManySmallAllocations_InOrder_NoFree(const char* allocatorType) { FS_PRINT(allocatorType); const size_t allocationSize = 32; const size_t allocationAlignment = 8; HeapArea area(FS_SIZE_OF_MB * 5); Allocator allocator(area.getStart(), area.getEnd()); auto start = steady_clock::now(); for(i32 i = FS_SIZE_OF_MB * 3 / allocationSize; i > 0; --i) { allocator.allocate(allocationSize, allocationAlignment, 0); } auto end = steady_clock::now(); auto allocatorTime = duration<double, milli>(end - start).count(); FS_PRINT(allocatorTime << " ms"); FS_PRINT(""); } int main( int, char **) { //Logger::init("content/logger.xml"); FS_PRINT("allocator_ManySmallAllocations_InOrder_NoFree"); allocator_ManySmallAllocations_InOrder_NoFree<LinearAllocator>("LinearAllocator"); allocator_ManySmallAllocations_InOrder_NoFree<StackAllocatorBottom>("StackAllocatorBottom"); allocator_ManySmallAllocations_InOrder_NoFree<StackAllocatorTop>("StackAllocatorTop"); allocator_ManySmallAllocations_InOrder_NoFree<HeapAllocator>("HeapAllocator"); allocator_ManySmallAllocations_InOrder_NoFree<PoolAllocatorNonGrowable<32, 8>>("PoolAllocator"); allocator_ManySmallAllocations_InOrder_NoFree<MallocAllocator>("MallocAllocator"); //Logger::destroy(); return 0; } <|endoftext|>
<commit_before>#include "PFCTradMaterial.h" template<> InputParameters validParams<PFCTradMaterial>() { InputParameters params = validParams<Material>(); return params; } PFCTradMaterial::PFCTradMaterial(const std::string & name, InputParameters parameters) :Material(name, parameters), _M(declareProperty<Real>("M")), _a(declareProperty<Real>("a")), _b(declareProperty<Real>("b")), _C0(declareProperty<Real>("C0")), _C2(declareProperty<Real>("C2")), _C4(declareProperty<Real>("C4")) { } void PFCTradMaterial::computeQpProperties() { Real invSkm = 0.332; Real u_s = 0.72; _M[_qp] = 1.0; _a[_qp] = 3.0/(2.0*u_s)*invSkm; _b[_qp] = 4.0/(30.0*u_s*u_s)*invSkm; _C0[_qp] = -10.9153; _C2[_qp] = 2.6; //Angstrom^2 _C4[_qp] = -0.1459; //Angstrom^4 } <commit_msg>Fixed bug in PFCTradMaterial and updated test<commit_after>#include "PFCTradMaterial.h" template<> InputParameters validParams<PFCTradMaterial>() { InputParameters params = validParams<Material>(); return params; } PFCTradMaterial::PFCTradMaterial(const std::string & name, InputParameters parameters) :Material(name, parameters), _M(declareProperty<Real>("M")), _a(declareProperty<Real>("a")), _b(declareProperty<Real>("b")), _C0(declareProperty<Real>("C0")), _C2(declareProperty<Real>("C2")), _C4(declareProperty<Real>("C4")) { } void PFCTradMaterial::computeQpProperties() { Real invSkm = 0.332; Real u_s = 0.72; _M[_qp] = 1.0; _a[_qp] = 3.0/(2.0*u_s)*invSkm; _b[_qp] = 4.0/(30.0*u_s*u_s)*invSkm; _C0[_qp] = -10.9153; _C2[_qp] = 2.6; //Angstrom^2 _C4[_qp] = 0.1459; //Angstrom^4, would be negative but coefficient term is negative } <|endoftext|>
<commit_before>/* Copyright (C) 2010 Jelle Hellemans This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "demo.h" #include "csutil/custom_new_disable.h" #include <CEGUI.h> #include <CEGUIWindowManager.h> #include <CEGUILogger.h> #include "csutil/custom_new_enable.h" CS_IMPLEMENT_APPLICATION Demo::Demo() { SetApplicationName ("Demo"); do_freelook = true; } Demo::~Demo() { } void Demo::Frame() { // Tell 3D driver we're going to display 3D things. if (!g3d->BeginDraw(engine->GetBeginDrawFlags() | CSDRAW_3DGRAPHICS)) { ReportError("BeginDraw Failed!"); return; } // Tell the camera to render into the frame buffer. view->Draw (); if (!do_freelook) cegui->Render (); } bool Demo::OnInitialize(int /*argc*/, char* /*argv*/ []) { if (!csInitializer::RequestPlugins(GetObjectRegistry(), CS_REQUEST_VFS, CS_REQUEST_OPENGL3D, CS_REQUEST_ENGINE, CS_REQUEST_FONTSERVER, CS_REQUEST_IMAGELOADER, CS_REQUEST_LEVELLOADER, CS_REQUEST_REPORTER, CS_REQUEST_REPORTERLISTENER, CS_REQUEST_PLUGIN ("crystalspace.cegui.wrapper", iCEGUI), CS_REQUEST_END)) return ReportError("Failed to initialize plugins!"); csBaseEventHandler::Initialize(GetObjectRegistry()); if (!RegisterQueue(GetObjectRegistry(), csevAllEvents(GetObjectRegistry()))) return ReportError("Failed to set up event handler!"); return true; } void Demo::OnExit() { printer.Invalidate (); } bool Demo::Application() { if (!OpenApplication(GetObjectRegistry())) return ReportError("Error opening system!"); vfs = csQueryRegistry<iVFS> (GetObjectRegistry()); if (!vfs) return ReportError("Failed to locate VFS!"); g3d = csQueryRegistry<iGraphics3D> (GetObjectRegistry()); if (!g3d) return ReportError("Failed to locate 3D renderer!"); engine = csQueryRegistry<iEngine> (GetObjectRegistry()); if (!engine) return ReportError("Failed to locate 3D engine!"); vc = csQueryRegistry<iVirtualClock> (GetObjectRegistry()); if (!vc) return ReportError("Failed to locate Virtual Clock!"); kbd = csQueryRegistry<iKeyboardDriver> (GetObjectRegistry()); if (!kbd) return ReportError("Failed to locate Keyboard Driver!"); loader = csQueryRegistry<iLoader> (GetObjectRegistry()); if (!loader) return ReportError("Failed to locate Loader!"); cegui = csQueryRegistry<iCEGUI> (GetObjectRegistry()); if (!cegui) return ReportError("Failed to locate CEGUI plugin"); iNativeWindow* nw = g3d->GetDriver2D()->GetNativeWindow (); if (nw) nw->SetTitle ("Peragro Tempus: Project Bias"); // Initialize CEGUI wrapper cegui->Initialize (); // Set the logging level cegui->GetLoggerPtr ()->setLoggingLevel(CEGUI::Informative); vfs->ChDir ("/cegui/"); // Load the ice skin (which uses Falagard skinning system) cegui->GetSchemeManagerPtr ()->create("ice.scheme"); cegui->GetSystemPtr ()->setDefaultMouseCursor("ice", "MouseArrow"); cegui->GetFontManagerPtr ()->createFreeTypeFont("DejaVuSans", 10, true, "/fonts/ttf/DejaVuSans.ttf"); CEGUI::WindowManager* winMgr = cegui->GetWindowManagerPtr (); // Load layout and set as root vfs->ChDir ("/data/bias/"); cegui->GetSystemPtr ()->setGUISheet(winMgr->loadWindowLayout("bias.layout")); // Subscribe to the clicked event for the exit button CEGUI::Window* btn = winMgr->getWindow("Bias/Inventory/Quit"); btn->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&Demo::OnExitButtonClicked, this)); // These are used store the current orientation of the camera. rotY = rotX = 0; view.AttachNew(new csView (engine, g3d)); iGraphics2D* g2d = g3d->GetDriver2D (); view->SetRectangle(0, 0, g2d->GetWidth(), g2d->GetHeight ()); object_reg->Register(view, "iView"); printer.AttachNew (new FramePrinter (object_reg)); CreateRoom(); csRef<iPluginManager> plugin_mgr; csRef<iCollideSystem> collide_system; plugin_mgr = csQueryRegistry<iPluginManager> (object_reg); const char* p = "crystalspace.collisiondetection.opcode"; collide_system = csLoadPlugin<iCollideSystem> (plugin_mgr, p); if (!collide_system) return ReportError ("No Collision Detection plugin found!"); object_reg->Register (collide_system, "iCollideSystem"); csColliderHelper::InitializeCollisionWrappers (collide_system, engine); player.AttachNew(new Player(object_reg)); Run(); return true; } bool Demo::OnExitButtonClicked (const CEGUI::EventArgs&) { csRef<iEventQueue> q = csQueryRegistry<iEventQueue> (GetObjectRegistry()); if (q.IsValid()) q->GetEventOutlet()->Broadcast(csevQuit(GetObjectRegistry())); return true; } bool Demo::OnKeyboard(iEvent& ev) { csKeyEventType eventtype = csKeyEventHelper::GetEventType(&ev); utf32_char code = csKeyEventHelper::GetCookedCode(&ev); if (eventtype == csKeyEventTypeDown) { if (code == CSKEY_ESC) { csRef<iEventQueue> q = csQueryRegistry<iEventQueue> (GetObjectRegistry()); if (q.IsValid()) q->GetEventOutlet()->Broadcast(csevQuit(GetObjectRegistry())); } else if (code == CSKEY_UP) { player->Step(1); } else if (code == CSKEY_DOWN) { player->Step(-1); } else if (code == CSKEY_LEFT) { player->Strafe(-1); } else if (code == CSKEY_RIGHT) { player->Strafe(1); } else if (code == CSKEY_SPACE) { player->Jump(); } else if (code == 'i') { if (do_freelook) { cegui->EnableMouseCapture(); //cegui->GetMouseCursorPtr()->show(); TODO: Why doesn't this work? do_freelook = false; } else { cegui->DisableMouseCapture(); //cegui->GetMouseCursorPtr()->hide(); TODO: Why doesn't this work? do_freelook = true; } } else if (code == 't') { csVector3 pos(-48.0f,13.0f,-260.0f); iSector* sector = engine->FindSector("outside"); if (sector) { view->GetCamera()->SetSector(sector); view->GetCamera()->GetTransform ().SetOrigin(pos); } } } else if (eventtype == csKeyEventTypeUp) { if (code == CSKEY_UP || code == CSKEY_DOWN) { player->Step(0); } else if (code == CSKEY_LEFT || code == CSKEY_RIGHT) { player->Strafe(0); } } return false; } bool Demo::OnMouseDown(iEvent& ev) { int last_x, last_y; last_x = csMouseEventHelper::GetX(&ev); last_y = csMouseEventHelper::GetY(&ev); player->Fire(last_x, last_y); return false; } bool Demo::OnMouseMove(iEvent& ev) { if (do_freelook) { int last_x, last_y; last_x = csMouseEventHelper::GetX(&ev); last_y = csMouseEventHelper::GetY(&ev); float speed = 6.0f; int FRAME_HEIGHT = g3d->GetDriver2D()->GetHeight(); int FRAME_WIDTH = g3d->GetDriver2D()->GetWidth(); g3d->GetDriver2D()->SetMousePosition (FRAME_WIDTH / 2, FRAME_HEIGHT / 2); player->RotateCam ( speed * (-((float)(last_y - (FRAME_HEIGHT / 2) )) / (FRAME_HEIGHT*2)), speed * (((float)(last_x - (FRAME_WIDTH / 2) )) / (FRAME_WIDTH*2))); } return true; } void Demo::CreateRoom () { room = engine->CreateSector ("room"); bool succ= vfs->Mount("/bias/", "$@data$/bias$/world.zip"); vfs->ChDir("/bias/"); bool suc = loader->LoadMapFile("/bias/world", false); if (engine->GetCameraPositions ()->GetCount () > 0) { iCameraPosition *cp = engine->GetCameraPositions ()->Get (0); cp->Load(view->GetCamera (), engine); } engine->Prepare (); } /*---------------* * Main function *---------------*/ int main (int argc, char* argv[]) { return csApplicationRunner<Demo>::Run (argc, argv); } <commit_msg>Hack in WASD controls<commit_after>/* Copyright (C) 2010 Jelle Hellemans This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "demo.h" #include "csutil/custom_new_disable.h" #include <CEGUI.h> #include <CEGUIWindowManager.h> #include <CEGUILogger.h> #include "csutil/custom_new_enable.h" CS_IMPLEMENT_APPLICATION Demo::Demo() { SetApplicationName ("Demo"); do_freelook = true; } Demo::~Demo() { } void Demo::Frame() { // Tell 3D driver we're going to display 3D things. if (!g3d->BeginDraw(engine->GetBeginDrawFlags() | CSDRAW_3DGRAPHICS)) { ReportError("BeginDraw Failed!"); return; } // Tell the camera to render into the frame buffer. view->Draw (); if (!do_freelook) cegui->Render (); } bool Demo::OnInitialize(int /*argc*/, char* /*argv*/ []) { if (!csInitializer::RequestPlugins(GetObjectRegistry(), CS_REQUEST_VFS, CS_REQUEST_OPENGL3D, CS_REQUEST_ENGINE, CS_REQUEST_FONTSERVER, CS_REQUEST_IMAGELOADER, CS_REQUEST_LEVELLOADER, CS_REQUEST_REPORTER, CS_REQUEST_REPORTERLISTENER, CS_REQUEST_PLUGIN ("crystalspace.cegui.wrapper", iCEGUI), CS_REQUEST_END)) return ReportError("Failed to initialize plugins!"); csBaseEventHandler::Initialize(GetObjectRegistry()); if (!RegisterQueue(GetObjectRegistry(), csevAllEvents(GetObjectRegistry()))) return ReportError("Failed to set up event handler!"); return true; } void Demo::OnExit() { printer.Invalidate (); } bool Demo::Application() { if (!OpenApplication(GetObjectRegistry())) return ReportError("Error opening system!"); vfs = csQueryRegistry<iVFS> (GetObjectRegistry()); if (!vfs) return ReportError("Failed to locate VFS!"); g3d = csQueryRegistry<iGraphics3D> (GetObjectRegistry()); if (!g3d) return ReportError("Failed to locate 3D renderer!"); engine = csQueryRegistry<iEngine> (GetObjectRegistry()); if (!engine) return ReportError("Failed to locate 3D engine!"); vc = csQueryRegistry<iVirtualClock> (GetObjectRegistry()); if (!vc) return ReportError("Failed to locate Virtual Clock!"); kbd = csQueryRegistry<iKeyboardDriver> (GetObjectRegistry()); if (!kbd) return ReportError("Failed to locate Keyboard Driver!"); loader = csQueryRegistry<iLoader> (GetObjectRegistry()); if (!loader) return ReportError("Failed to locate Loader!"); cegui = csQueryRegistry<iCEGUI> (GetObjectRegistry()); if (!cegui) return ReportError("Failed to locate CEGUI plugin"); iNativeWindow* nw = g3d->GetDriver2D()->GetNativeWindow (); if (nw) nw->SetTitle ("Peragro Tempus: Project Bias"); // Initialize CEGUI wrapper cegui->Initialize (); // Set the logging level cegui->GetLoggerPtr ()->setLoggingLevel(CEGUI::Informative); vfs->ChDir ("/cegui/"); // Load the ice skin (which uses Falagard skinning system) cegui->GetSchemeManagerPtr ()->create("ice.scheme"); cegui->GetSystemPtr ()->setDefaultMouseCursor("ice", "MouseArrow"); cegui->GetFontManagerPtr ()->createFreeTypeFont("DejaVuSans", 10, true, "/fonts/ttf/DejaVuSans.ttf"); CEGUI::WindowManager* winMgr = cegui->GetWindowManagerPtr (); // Load layout and set as root vfs->ChDir ("/data/bias/"); cegui->GetSystemPtr ()->setGUISheet(winMgr->loadWindowLayout("bias.layout")); // Subscribe to the clicked event for the exit button CEGUI::Window* btn = winMgr->getWindow("Bias/Inventory/Quit"); btn->subscribeEvent(CEGUI::PushButton::EventClicked, CEGUI::Event::Subscriber(&Demo::OnExitButtonClicked, this)); // These are used store the current orientation of the camera. rotY = rotX = 0; view.AttachNew(new csView (engine, g3d)); iGraphics2D* g2d = g3d->GetDriver2D (); view->SetRectangle(0, 0, g2d->GetWidth(), g2d->GetHeight ()); object_reg->Register(view, "iView"); printer.AttachNew (new FramePrinter (object_reg)); CreateRoom(); csRef<iPluginManager> plugin_mgr; csRef<iCollideSystem> collide_system; plugin_mgr = csQueryRegistry<iPluginManager> (object_reg); const char* p = "crystalspace.collisiondetection.opcode"; collide_system = csLoadPlugin<iCollideSystem> (plugin_mgr, p); if (!collide_system) return ReportError ("No Collision Detection plugin found!"); object_reg->Register (collide_system, "iCollideSystem"); csColliderHelper::InitializeCollisionWrappers (collide_system, engine); player.AttachNew(new Player(object_reg)); Run(); return true; } bool Demo::OnExitButtonClicked (const CEGUI::EventArgs&) { csRef<iEventQueue> q = csQueryRegistry<iEventQueue> (GetObjectRegistry()); if (q.IsValid()) q->GetEventOutlet()->Broadcast(csevQuit(GetObjectRegistry())); return true; } bool Demo::OnKeyboard(iEvent& ev) { csKeyEventType eventtype = csKeyEventHelper::GetEventType(&ev); utf32_char code = csKeyEventHelper::GetCookedCode(&ev); if (eventtype == csKeyEventTypeDown) { if (code == CSKEY_ESC) { csRef<iEventQueue> q = csQueryRegistry<iEventQueue> (GetObjectRegistry()); if (q.IsValid()) q->GetEventOutlet()->Broadcast(csevQuit(GetObjectRegistry())); } else if ((code == CSKEY_UP) || (code == 'w')) { player->Step(1); } else if ((code == CSKEY_DOWN) || (code == 's')) { player->Step(-1); } else if ((code == CSKEY_LEFT) || (code == 'a')) { player->Strafe(-1); } else if ((code == CSKEY_RIGHT) || (code == 'd')) { player->Strafe(1); } else if (code == CSKEY_SPACE) { player->Jump(); } else if (code == 'i') { if (do_freelook) { cegui->EnableMouseCapture(); //cegui->GetMouseCursorPtr()->show(); TODO: Why doesn't this work? do_freelook = false; } else { cegui->DisableMouseCapture(); //cegui->GetMouseCursorPtr()->hide(); TODO: Why doesn't this work? do_freelook = true; } } else if (code == 't') { csVector3 pos(-48.0f,13.0f,-260.0f); iSector* sector = engine->FindSector("outside"); if (sector) { view->GetCamera()->SetSector(sector); view->GetCamera()->GetTransform ().SetOrigin(pos); } } } else if (eventtype == csKeyEventTypeUp) { if (code == CSKEY_UP || code == CSKEY_DOWN || (code == 'w') || (code == 's')) { player->Step(0); } else if (code == CSKEY_LEFT || code == CSKEY_RIGHT || (code == 'a') || (code == 'd')) { player->Strafe(0); } } return false; } bool Demo::OnMouseDown(iEvent& ev) { int last_x, last_y; last_x = csMouseEventHelper::GetX(&ev); last_y = csMouseEventHelper::GetY(&ev); player->Fire(last_x, last_y); return false; } bool Demo::OnMouseMove(iEvent& ev) { if (do_freelook) { int last_x, last_y; last_x = csMouseEventHelper::GetX(&ev); last_y = csMouseEventHelper::GetY(&ev); float speed = 6.0f; int FRAME_HEIGHT = g3d->GetDriver2D()->GetHeight(); int FRAME_WIDTH = g3d->GetDriver2D()->GetWidth(); g3d->GetDriver2D()->SetMousePosition (FRAME_WIDTH / 2, FRAME_HEIGHT / 2); player->RotateCam ( speed * (-((float)(last_y - (FRAME_HEIGHT / 2) )) / (FRAME_HEIGHT*2)), speed * (((float)(last_x - (FRAME_WIDTH / 2) )) / (FRAME_WIDTH*2))); } return true; } void Demo::CreateRoom () { room = engine->CreateSector ("room"); bool succ= vfs->Mount("/bias/", "$@data$/bias$/world.zip"); vfs->ChDir("/bias/"); bool suc = loader->LoadMapFile("/bias/world", false); if (engine->GetCameraPositions ()->GetCount () > 0) { iCameraPosition *cp = engine->GetCameraPositions ()->Get (0); cp->Load(view->GetCamera (), engine); } engine->Prepare (); } /*---------------* * Main function *---------------*/ int main (int argc, char* argv[]) { return csApplicationRunner<Demo>::Run (argc, argv); } <|endoftext|>
<commit_before>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/path_decider/path_decider.h" #include <string> #include <utility> #include <vector> #include "modules/planning/proto/decision.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; namespace { const double kTimeSampleInterval = 0.1; } PathDecider::PathDecider() : Task("PathDecider") {} apollo::common::Status PathDecider::Execute( Frame *, ReferenceLineInfo *reference_line_info) { reference_line_ = &reference_line_info->reference_line(); speed_data_ = &reference_line_info->speed_data(); return Process(reference_line_info->path_data(), reference_line_info->path_decision()); } Status PathDecider::Process(const PathData &path_data, PathDecision *const path_decision) { CHECK_NOTNULL(path_decision); if (!MakeObjectDecision(path_data, path_decision)) { AERROR << "Failed to make decision based on tunnel"; return Status(ErrorCode::PLANNING_ERROR, "dp_road_graph decision "); } return Status::OK(); } bool PathDecider::MakeObjectDecision(const PathData &path_data, PathDecision *const path_decision) { DCHECK_NOTNULL(path_decision); if (!MakeStaticObstacleDecision(path_data, path_decision)) { AERROR << "Failed to make decisions for static obstacles"; return false; } return true; } bool PathDecider::MakeStaticObstacleDecision( const PathData &path_data, PathDecision *const path_decision) { if (!FLAGS_enable_nudge_decision) { return true; } DCHECK_NOTNULL(path_decision); std::vector<common::SLPoint> adc_sl_points; std::vector<common::math::Box2d> adc_bounding_box; const auto &vehicle_param = common::VehicleConfigHelper::instance()->GetConfig().vehicle_param(); const double adc_length = vehicle_param.length(); const double adc_width = vehicle_param.length(); const double adc_max_edge_to_center_dist = std::hypot(std::max(vehicle_param.front_edge_to_center(), vehicle_param.back_edge_to_center()), std::max(vehicle_param.left_edge_to_center(), vehicle_param.right_edge_to_center())); for (const common::PathPoint &path_point : path_data.discretized_path().path_points()) { adc_bounding_box.emplace_back( common::math::Vec2d{path_point.x(), path_point.y()}, path_point.theta(), adc_length, adc_width); common::SLPoint adc_sl; if (!reference_line_->XYToSL({path_point.x(), path_point.y()}, &adc_sl)) { AERROR << "get_point_in_Frenet_frame error for ego vehicle " << path_point.x() << " " << path_point.y(); return false; } else { adc_sl_points.push_back(std::move(adc_sl)); } } for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto *obstacle = path_obstacle->Obstacle(); if (obstacle->IsVirtual()) { continue; } if (!obstacle->IsStatic()) { continue; } // IGNORE by default ObjectDecisionType object_decision; object_decision.mutable_ignore(); const auto &sl_boundary = path_obstacle->perception_sl_boundary(); bool has_stop = false; for (std::size_t j = 0; j < adc_sl_points.size(); ++j) { const auto &adc_sl = adc_sl_points[j]; if (adc_sl.s() + adc_max_edge_to_center_dist + FLAGS_static_decision_ignore_s_range < sl_boundary.start_s() || adc_sl.s() - adc_max_edge_to_center_dist - FLAGS_static_decision_ignore_s_range > sl_boundary.end_s()) { // ignore: no overlap in s direction continue; } if (adc_sl.l() + adc_max_edge_to_center_dist + FLAGS_static_decision_nudge_l_buffer < sl_boundary.start_l() || adc_sl.l() - adc_max_edge_to_center_dist - FLAGS_static_decision_nudge_l_buffer > sl_boundary.end_l()) { // ignore: no overlap in l direction continue; } // check STOP/NUDGE double left_width; double right_width; if (!reference_line_->get_lane_width(adc_sl.s(), &left_width, &right_width)) { left_width = right_width = FLAGS_default_reference_line_width / 2; } double driving_width; bool left_nudgable = false; bool right_nudgable = false; if (sl_boundary.start_l() >= 0) { // obstacle on the left, check RIGHT_NUDGE driving_width = sl_boundary.start_l() - FLAGS_static_decision_nudge_l_buffer + right_width; right_nudgable = (driving_width >= FLAGS_min_driving_width) ? true : false; } else if (sl_boundary.end_l() <= 0) { // obstacle on the right, check LEFT_NUDGE driving_width = std::fabs(sl_boundary.end_l()) - FLAGS_static_decision_nudge_l_buffer + left_width; left_nudgable = (driving_width >= FLAGS_min_driving_width) ? true : false; } else { // obstacle across the central line, decide RIGHT_NUDGE/LEFT_NUDGE double driving_width_left = left_width - sl_boundary.end_l() - FLAGS_static_decision_nudge_l_buffer; double driving_width_right = right_width - std::fabs(sl_boundary.start_l()) - FLAGS_static_decision_nudge_l_buffer; if (std::max(driving_width_right, driving_width_left) >= FLAGS_min_driving_width) { // nudgable left_nudgable = driving_width_left > driving_width_right ? true : false; right_nudgable = !left_nudgable; } } if (!left_nudgable && !right_nudgable) { // STOP: and break ObjectDecisionType stop_decision; ObjectStop *object_stop_ptr = stop_decision.mutable_stop(); object_stop_ptr->set_distance_s(-FLAGS_stop_distance_obstacle); object_stop_ptr->set_reason_code(StopReasonCode::STOP_REASON_OBSTACLE); auto stop_ref_s = sl_boundary.start_s() - FLAGS_stop_distance_obstacle; auto stop_ref_point = reference_line_->get_reference_point(stop_ref_s); object_stop_ptr->mutable_stop_point()->set_x(stop_ref_point.x()); object_stop_ptr->mutable_stop_point()->set_y(stop_ref_point.y()); object_stop_ptr->set_stop_heading(stop_ref_point.heading()); path_decision->AddLongitudinalDecision("DpRoadGraph", obstacle->Id(), stop_decision); has_stop = true; break; } else { // NUDGE: and continue to check potential STOP along the ref line if (!object_decision.has_nudge()) { ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); if (left_nudgable) { // LEFT_NUDGE object_nudge_ptr->set_type(ObjectNudge::LEFT_NUDGE); object_nudge_ptr->set_distance_l(FLAGS_nudge_distance_obstacle); } else { // RIGHT_NUDGE object_nudge_ptr->set_type(ObjectNudge::RIGHT_NUDGE); object_nudge_ptr->set_distance_l(-FLAGS_nudge_distance_obstacle); } } } } if (!has_stop) { path_decision->AddLateralDecision("DpRoadGraph", obstacle->Id(), object_decision); } } return true; } bool PathDecider::MakeDynamicObstcleDecision( const PathData &path_data, PathDecision *const path_decision) { // Compute dynamic obstacle decision const double interval = kTimeSampleInterval; const double total_time = std::min(speed_data_->TotalTime(), FLAGS_prediction_total_time); std::size_t evaluate_time_slots = static_cast<std::size_t>(std::floor(total_time / interval)); // list of Box2d for adc given speed profile std::vector<common::math::Box2d> adc_by_time; if (!ComputeBoundingBoxesForAdc(path_data.frenet_frame_path(), evaluate_time_slots, &adc_by_time)) { AERROR << "fill adc_by_time error"; return false; } for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto *obstacle = path_obstacle->Obstacle(); if (obstacle->IsVirtual()) { continue; } if (obstacle->IsStatic()) { continue; } double timestamp = 0.0; for (std::size_t k = 0; k < evaluate_time_slots; ++k, timestamp += interval) { // TODO(all) make nudge decision for dynamic obstacles. // const auto obstacle_by_time = // obstacle->GetBoundingBox(obstacle->GetPointAtTime(timestamp)); } } return true; } bool PathDecider::ComputeBoundingBoxesForAdc( const FrenetFramePath &frenet_frame_path, const std::size_t evaluate_time_slots, std::vector<common::math::Box2d> *adc_boxes) { CHECK(adc_boxes != nullptr); const auto &vehicle_config = common::VehicleConfigHelper::instance()->GetConfig(); double adc_length = vehicle_config.vehicle_param().length(); double adc_width = vehicle_config.vehicle_param().length(); double time_stamp = 0.0; const double interval = kTimeSampleInterval; for (std::size_t i = 0; i < evaluate_time_slots; ++i, time_stamp += interval) { common::SpeedPoint speed_point; if (!speed_data_->EvaluateByTime(time_stamp, &speed_point)) { AINFO << "get_speed_point_with_time for time_stamp[" << time_stamp << "]"; return false; } const common::FrenetFramePoint &interpolated_frenet_point = frenet_frame_path.EvaluateByS(speed_point.s()); double s = interpolated_frenet_point.s(); double l = interpolated_frenet_point.l(); double dl = interpolated_frenet_point.dl(); common::math::Vec2d adc_position_cartesian; common::SLPoint sl_point; sl_point.set_s(s); sl_point.set_l(l); reference_line_->SLToXY(sl_point, &adc_position_cartesian); ReferencePoint reference_point = reference_line_->get_reference_point(s); double one_minus_kappa_r_d = 1 - reference_point.kappa() * l; double delta_theta = std::atan2(dl, one_minus_kappa_r_d); double theta = ::apollo::common::math::NormalizeAngle( delta_theta + reference_point.heading()); adc_boxes->emplace_back(adc_position_cartesian, theta, adc_length, adc_width); } return true; } } // namespace planning } // namespace apollo <commit_msg>Planning: fixed stop decision s position bug. Use adc front s if the stop s is behind it.<commit_after>/****************************************************************************** * Copyright 2017 The Apollo Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ /** * @file **/ #include "modules/planning/tasks/path_decider/path_decider.h" #include <string> #include <utility> #include <vector> #include "modules/planning/proto/decision.pb.h" #include "modules/common/configs/vehicle_config_helper.h" #include "modules/planning/common/planning_gflags.h" namespace apollo { namespace planning { using apollo::common::ErrorCode; using apollo::common::Status; namespace { const double kTimeSampleInterval = 0.1; } PathDecider::PathDecider() : Task("PathDecider") {} apollo::common::Status PathDecider::Execute( Frame *, ReferenceLineInfo *reference_line_info) { reference_line_ = &reference_line_info->reference_line(); speed_data_ = &reference_line_info->speed_data(); return Process(reference_line_info->path_data(), reference_line_info->path_decision()); } Status PathDecider::Process(const PathData &path_data, PathDecision *const path_decision) { CHECK_NOTNULL(path_decision); if (!MakeObjectDecision(path_data, path_decision)) { AERROR << "Failed to make decision based on tunnel"; return Status(ErrorCode::PLANNING_ERROR, "dp_road_graph decision "); } return Status::OK(); } bool PathDecider::MakeObjectDecision(const PathData &path_data, PathDecision *const path_decision) { DCHECK_NOTNULL(path_decision); if (!MakeStaticObstacleDecision(path_data, path_decision)) { AERROR << "Failed to make decisions for static obstacles"; return false; } return true; } bool PathDecider::MakeStaticObstacleDecision( const PathData &path_data, PathDecision *const path_decision) { if (!FLAGS_enable_nudge_decision) { return true; } DCHECK_NOTNULL(path_decision); std::vector<common::SLPoint> adc_sl_points; std::vector<common::math::Box2d> adc_bounding_box; const auto &vehicle_param = common::VehicleConfigHelper::instance()->GetConfig().vehicle_param(); const double adc_length = vehicle_param.length(); const double adc_width = vehicle_param.length(); const double adc_max_edge_to_center_dist = std::hypot(std::max(vehicle_param.front_edge_to_center(), vehicle_param.back_edge_to_center()), std::max(vehicle_param.left_edge_to_center(), vehicle_param.right_edge_to_center())); for (const common::PathPoint &path_point : path_data.discretized_path().path_points()) { adc_bounding_box.emplace_back( common::math::Vec2d{path_point.x(), path_point.y()}, path_point.theta(), adc_length, adc_width); common::SLPoint adc_sl; if (!reference_line_->XYToSL({path_point.x(), path_point.y()}, &adc_sl)) { AERROR << "get_point_in_Frenet_frame error for ego vehicle " << path_point.x() << " " << path_point.y(); return false; } else { adc_sl_points.push_back(std::move(adc_sl)); } } for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto *obstacle = path_obstacle->Obstacle(); if (obstacle->IsVirtual()) { continue; } if (!obstacle->IsStatic()) { continue; } // IGNORE by default ObjectDecisionType object_decision; object_decision.mutable_ignore(); const auto &sl_boundary = path_obstacle->perception_sl_boundary(); bool has_stop = false; for (std::size_t j = 0; j < adc_sl_points.size(); ++j) { const auto &adc_sl = adc_sl_points[j]; if (adc_sl.s() + adc_max_edge_to_center_dist + FLAGS_static_decision_ignore_s_range < sl_boundary.start_s() || adc_sl.s() - adc_max_edge_to_center_dist - FLAGS_static_decision_ignore_s_range > sl_boundary.end_s()) { // ignore: no overlap in s direction continue; } if (adc_sl.l() + adc_max_edge_to_center_dist + FLAGS_static_decision_nudge_l_buffer < sl_boundary.start_l() || adc_sl.l() - adc_max_edge_to_center_dist - FLAGS_static_decision_nudge_l_buffer > sl_boundary.end_l()) { // ignore: no overlap in l direction continue; } // check STOP/NUDGE double left_width; double right_width; if (!reference_line_->get_lane_width(adc_sl.s(), &left_width, &right_width)) { left_width = right_width = FLAGS_default_reference_line_width / 2; } double driving_width; bool left_nudgable = false; bool right_nudgable = false; if (sl_boundary.start_l() >= 0) { // obstacle on the left, check RIGHT_NUDGE driving_width = sl_boundary.start_l() - FLAGS_static_decision_nudge_l_buffer + right_width; right_nudgable = (driving_width >= FLAGS_min_driving_width) ? true : false; } else if (sl_boundary.end_l() <= 0) { // obstacle on the right, check LEFT_NUDGE driving_width = std::fabs(sl_boundary.end_l()) - FLAGS_static_decision_nudge_l_buffer + left_width; left_nudgable = (driving_width >= FLAGS_min_driving_width) ? true : false; } else { // obstacle across the central line, decide RIGHT_NUDGE/LEFT_NUDGE double driving_width_left = left_width - sl_boundary.end_l() - FLAGS_static_decision_nudge_l_buffer; double driving_width_right = right_width - std::fabs(sl_boundary.start_l()) - FLAGS_static_decision_nudge_l_buffer; if (std::max(driving_width_right, driving_width_left) >= FLAGS_min_driving_width) { // nudgable left_nudgable = driving_width_left > driving_width_right ? true : false; right_nudgable = !left_nudgable; } } if (!left_nudgable && !right_nudgable) { // STOP: and break ObjectDecisionType stop_decision; ObjectStop *object_stop_ptr = stop_decision.mutable_stop(); object_stop_ptr->set_reason_code(StopReasonCode::STOP_REASON_OBSTACLE); const auto &vehicle_param = common::VehicleConfigHelper::instance() ->GetConfig() .vehicle_param(); constexpr double kStopBuffer = 1.0e-6; auto stop_ref_s = std::fmax(adc_sl_points[0].s() + vehicle_param.front_edge_to_center() + kStopBuffer, sl_boundary.start_s() - FLAGS_stop_distance_obstacle); object_stop_ptr->set_distance_s(stop_ref_s - sl_boundary.start_s()); auto stop_ref_point = reference_line_->get_reference_point(stop_ref_s); object_stop_ptr->mutable_stop_point()->set_x(stop_ref_point.x()); object_stop_ptr->mutable_stop_point()->set_y(stop_ref_point.y()); object_stop_ptr->set_stop_heading(stop_ref_point.heading()); path_decision->AddLongitudinalDecision("DpRoadGraph", obstacle->Id(), stop_decision); has_stop = true; break; } else { // NUDGE: and continue to check potential STOP along the ref line if (!object_decision.has_nudge()) { ObjectNudge *object_nudge_ptr = object_decision.mutable_nudge(); if (left_nudgable) { // LEFT_NUDGE object_nudge_ptr->set_type(ObjectNudge::LEFT_NUDGE); object_nudge_ptr->set_distance_l(FLAGS_nudge_distance_obstacle); } else { // RIGHT_NUDGE object_nudge_ptr->set_type(ObjectNudge::RIGHT_NUDGE); object_nudge_ptr->set_distance_l(-FLAGS_nudge_distance_obstacle); } } } } if (!has_stop) { path_decision->AddLateralDecision("DpRoadGraph", obstacle->Id(), object_decision); } } return true; } bool PathDecider::MakeDynamicObstcleDecision( const PathData &path_data, PathDecision *const path_decision) { // Compute dynamic obstacle decision const double interval = kTimeSampleInterval; const double total_time = std::min(speed_data_->TotalTime(), FLAGS_prediction_total_time); std::size_t evaluate_time_slots = static_cast<std::size_t>(std::floor(total_time / interval)); // list of Box2d for adc given speed profile std::vector<common::math::Box2d> adc_by_time; if (!ComputeBoundingBoxesForAdc(path_data.frenet_frame_path(), evaluate_time_slots, &adc_by_time)) { AERROR << "fill adc_by_time error"; return false; } for (const auto *path_obstacle : path_decision->path_obstacles().Items()) { const auto *obstacle = path_obstacle->Obstacle(); if (obstacle->IsVirtual()) { continue; } if (obstacle->IsStatic()) { continue; } double timestamp = 0.0; for (std::size_t k = 0; k < evaluate_time_slots; ++k, timestamp += interval) { // TODO(all) make nudge decision for dynamic obstacles. // const auto obstacle_by_time = // obstacle->GetBoundingBox(obstacle->GetPointAtTime(timestamp)); } } return true; } bool PathDecider::ComputeBoundingBoxesForAdc( const FrenetFramePath &frenet_frame_path, const std::size_t evaluate_time_slots, std::vector<common::math::Box2d> *adc_boxes) { CHECK(adc_boxes != nullptr); const auto &vehicle_config = common::VehicleConfigHelper::instance()->GetConfig(); double adc_length = vehicle_config.vehicle_param().length(); double adc_width = vehicle_config.vehicle_param().length(); double time_stamp = 0.0; const double interval = kTimeSampleInterval; for (std::size_t i = 0; i < evaluate_time_slots; ++i, time_stamp += interval) { common::SpeedPoint speed_point; if (!speed_data_->EvaluateByTime(time_stamp, &speed_point)) { AINFO << "get_speed_point_with_time for time_stamp[" << time_stamp << "]"; return false; } const common::FrenetFramePoint &interpolated_frenet_point = frenet_frame_path.EvaluateByS(speed_point.s()); double s = interpolated_frenet_point.s(); double l = interpolated_frenet_point.l(); double dl = interpolated_frenet_point.dl(); common::math::Vec2d adc_position_cartesian; common::SLPoint sl_point; sl_point.set_s(s); sl_point.set_l(l); reference_line_->SLToXY(sl_point, &adc_position_cartesian); ReferencePoint reference_point = reference_line_->get_reference_point(s); double one_minus_kappa_r_d = 1 - reference_point.kappa() * l; double delta_theta = std::atan2(dl, one_minus_kappa_r_d); double theta = ::apollo::common::math::NormalizeAngle( delta_theta + reference_point.heading()); adc_boxes->emplace_back(adc_position_cartesian, theta, adc_length, adc_width); } return true; } } // namespace planning } // namespace apollo <|endoftext|>
<commit_before>#if defined(USE_QT4) #include <QWidget> #include <QFont> #include <QKeyEvent> #include <QTimer> #include <QColor> #include <QPainter> #elif defined(USE_QTOPIA) #include <qwidget.h> #include <qtimer.h> #include <qpainter.h> #endif #include "termwidget.h" #include <pty.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> /* term */ #define COLS 80 #define ROWS 24 struct t_cell { char c; }; struct t_cell cell[ROWS][COLS]; int dirty[ROWS]; int cursor_x, cursor_y; int cursor_state; int esc; void treset(void); void tputc(char c); /* screen */ void draw(QWidget *w); void xdraws(QPainter &painter, QString str, int x, int y, int len); /* widget */ pid_t g_pid; int g_fd; int cell_width = 16; int cell_height = 16; void sigchld(int) { int stat = 0; if(waitpid(g_pid, &stat, 0) < 0) { printf("Waiting for pid failed.\n"); } if(WIFEXITED(stat)) exit(WEXITSTATUS(stat)); else exit(EXIT_FAILURE); } void ttyread(void) { char buf[256]; int count; char c; int i; count = read(g_fd, buf, sizeof(buf)); if(count > 0) { // qDebug("read %d", count); } #if 0 // dump for(i = 0; i < count; i++) { if(i % 16 == 0 && i != 0) printf("\n"); printf("%.2x ", buf[i]); } printf("\n"); #endif for(i = 0; i < count; i++) { c = buf[i]; tputc(c); } } TermWidget::TermWidget() { pid_t pid; int fd; // QFont font("Terminus"); // QFont font("Ubuntu Mono"); // cell_font = font; // font.setPixelSize(12); QFont font("Bitstream Vera Sans Mono", 15); // font.setPixelSize(20); // font.setFixedPitch(true); // font.setKerning(false); setCellFont(font); QFontInfo info(font); QString family = info.family(); // qDebug("family = %s", family.toStdString().c_str()); setGeometry(600, 200, cell_width * COLS + 2, cell_height * ROWS); if((pid = forkpty(&fd, NULL, NULL, NULL)) < 0) { perror("forkpty"); return; } if (pid == 0) { static const char *argv[] = { "bash", 0 }; execve("/bin/bash", (char * const *)argv, NULL); } // qDebug("father"); g_pid = pid; g_fd = fd; signal(SIGCHLD, sigchld); readTimer = new QTimer(this); connect(readTimer, SIGNAL(timeout()), this, SLOT(doRead())); readTimer->start(1000); treset(); } bool TermWidget::setCellFont(QFont &font) { cell_font = font; cell_font.setFixedPitch(true); cell_font.setKerning(false); cell_font.setStyleHint(QFont::TypeWriter); QFontMetrics fm(font); cell_width = fm.width('X'); cell_height = fm.height(); // qDebug("cell_width = %d", cell_width); // qDebug("cell_height = %d", cell_height); QFontMetrics qm(font); // qDebug("%d", qm.width("Hello")); // qDebug("%d", qm.width("I")); return true; } void TermWidget::doRead() { // qDebug("doRead"); fd_set rfd; FD_ZERO(&rfd); FD_SET(g_fd, &rfd); struct timeval timeout = {0,0}; timeout.tv_sec = 0; timeout.tv_usec = 20 * 1000; // 20 ms // bool stuff_to_print = 0; if(select(g_fd + 1, &rfd, NULL, NULL, &timeout) < 0) { return; } if(FD_ISSET(g_fd, &rfd)) { ttyread(); // stuff_to_print = 1; } draw(this); } void TermWidget::paintEvent(QPaintEvent *) { // qDebug("paintEvent"); #if defined(USE_QT4) QPainter painter(this); // QString str = "01234567890123456789"; // QString str2 = "testtesttesttesttesb"; painter.setFont(cell_font); // QRect rect(0, 0, 16 * 40, 16); // painter.drawText(rect, Qt::TextSingleLine, str); // QRect rect2(0, 16, 16 * 40, 16 * 2); // painter.drawText(rect2, Qt::TextSingleLine, str2); int x, y; for(y = 0; y < ROWS; y++) { QString str; for(x = 0; x < COLS; x++) { str += QChar(cell[y][x].c); } // if(y == 0) { // qDebug("str = %s", str.toStdString().c_str()); // } xdraws(painter, str, 0, y, COLS); } #elif defined(USE_QTOPIA) QPainter painter(this); QString str = "test"; QRect rect(0, 0, 16 * 4, 16); painter.drawText(rect, Qt::SingleLine, str); QRect rect2(0, 16, 16 * 4, 16); painter.drawText(rect2, Qt::SingleLine, str); #endif } void TermWidget::keyPressEvent(QKeyEvent *k) { #if defined(USE_QT4) // qDebug("<keyPressEvent> - %d, %s", // k->key(), // k->text().toStdString().c_str()); #elif defined(USE_QTOPIA) // qDebug("<keyPressEvent> - %d", k->key()); #endif if(k->text().isEmpty()) { // qDebug("text empty"); } else { // qDebug("text not empty"); } switch(k->key()) { case Qt::Key_Return: // qDebug("<keyPressEvent>: Key_Return"); break; default: break; } if(k->text().isEmpty()) { return; } #if defined(USE_QT4) QByteArray data = k->text().toLocal8Bit(); int n = write(g_fd, data.constData(), data.count()); #elif defined(USE_QTOPIA) QByteArray data = k->text().local8Bit(); int n = write(g_fd, data.data(), data.count()); #endif // qDebug("write: %d", n); } /* term */ #define ESC_BUF_SIZ 256 #define ESC_ARG_SIZ 16 #define CURSOR_DEFAULT 0 #define CURSOR_WRAPNEXT 1 #define ESC_START 1 #define ESC_CSI 2 /* CSI Escape sequence structs */ /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */ typedef struct { char buf[ESC_BUF_SIZ]; /* raw string */ int len; /* raw string length */ char priv; int arg[ESC_ARG_SIZ]; int narg; /* nb of args */ char mode; } CSIEscape; static CSIEscape escseq; void tsetchar(char c); void tmoveto(int x, int y); void tnewline(int first_col); void csireset(void); void csiparse(void); void csihandle(void); void csidump(void); void treset(void) { int i, j; for(i = 0; i < ROWS; i++) { for(j = 0; j < COLS; j++) { // if(j == 0) { // cell[i][j].c = 'a'; // } else if (j == 2) { // cell[i][j].c = (i + 1) / 10 + '0'; // } else if (j == 3) { // cell[i][j].c = (i + 1) % 10 + '0'; // } else if (j == COLS-1) { // cell[i][j].c = 'b'; // } else { cell[i][j].c = ' '; // } } dirty[i] = 1; } cursor_x = 0, cursor_y = 0; cursor_state = CURSOR_DEFAULT; esc = 0; } void tputc(char c) { if(esc & ESC_START) { if(esc & ESC_CSI) { escseq.buf[escseq.len++] = c; if((c >= 0x40 && c <= 0x7E) || escseq.len >= ESC_BUF_SIZ) { esc = 0; csiparse(); csihandle(); } } else { switch(c) { case '[': esc |= ESC_CSI; break; default: printf("unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)? c : '.'); esc = 0; break; } } } else { switch(c) { case '\r': tmoveto(0, cursor_y); break; case '\n': tnewline(0); break; case '\033': csireset(); esc = ESC_START; break; default: if(cursor_state & CURSOR_WRAPNEXT) { tnewline(1); } tsetchar(c); if(cursor_x + 1 < COLS) { tmoveto(cursor_x + 1, cursor_y); } else { cursor_state |= CURSOR_WRAPNEXT; } break; } } } void tsetchar(char c) { cell[cursor_y][cursor_x].c = c; dirty[cursor_y] = 1; } void tmoveto(int x, int y) { if(x < 0) x = 0; if(x > COLS - 1) x = COLS - 1; if(y < 0) y = 0; if(y > ROWS - 1) y = ROWS - 1; cursor_x = x; cursor_y = y; cursor_state &= ~CURSOR_WRAPNEXT; } void tnewline(int first_col) { int y = cursor_y; y++; tmoveto(first_col ? 0 : cursor_x, y); } void csireset(void) { memset(&escseq, 0, sizeof(escseq)); } void csiparse(void) { /* int noarg = 1; */ char *p = escseq.buf; escseq.narg = 0; if(*p == '?') escseq.priv = 1, p++; while(p < escseq.buf + escseq.len) { while(isdigit(*p)) { escseq.arg[escseq.narg] *= 10; escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */; } if(*p == ';' && escseq.narg+1 < ESC_ARG_SIZ) escseq.narg++, p++; else { escseq.mode = *p; escseq.narg++; return; } } } void csihandle(void) { switch(escseq.mode) { default: printf("unknown csi "); csidump(); break; } } void csidump(void) { int i; printf("ESC["); for(i = 0; i < escseq.len; i++) { uint c = escseq.buf[i] & 0xff; if(isprint(c)) putchar(c); else if(c == '\n') printf("(\\n)"); else if(c == '\r') printf("(\\r)"); else if(c == 0x1b) printf("(\\e)"); else printf("(%02x)", c); } putchar('\n'); } /* screen */ void draw(QWidget *w) { w->update(); } void xdraws(QPainter &painter, QString str, int x, int y, int len) { // QString str; // str += "aaa "; // str += QChar((y + 1) / 10 + '0'); // str += QChar((y + 1) % 10 + '0'); QRect rect(x * cell_width, y * cell_height, cell_width * len, cell_height); painter.drawText(rect, Qt::TextSingleLine, str); } <commit_msg>qtopia: merge<commit_after>#if defined(USE_QT4) #include <QWidget> #include <QFont> #include <QKeyEvent> #include <QTimer> #include <QColor> #include <QPainter> #elif defined(USE_QTOPIA) #include <qwidget.h> #include <qfont.h> #include <qtimer.h> #include <qpainter.h> #endif #include "termwidget.h" #include <pty.h> #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include <unistd.h> #include <sys/types.h> #include <sys/wait.h> /* term */ #define COLS 80 #define ROWS 24 struct t_cell { char c; }; struct t_cell cell[ROWS][COLS]; int dirty[ROWS]; int cursor_x, cursor_y; int cursor_state; int esc; void treset(void); void tputc(char c); /* screen */ void draw(QWidget *w); void xdraws(QPainter &painter, QString str, int x, int y, int len); /* widget */ pid_t g_pid; int g_fd; int cell_width = 16; int cell_height = 16; void sigchld(int) { int stat = 0; if(waitpid(g_pid, &stat, 0) < 0) { printf("Waiting for pid failed.\n"); } if(WIFEXITED(stat)) exit(WEXITSTATUS(stat)); else exit(EXIT_FAILURE); } void ttyread(void) { char buf[256]; int count; char c; int i; count = read(g_fd, buf, sizeof(buf)); if(count > 0) { // qDebug("read %d", count); } #if 0 // dump for(i = 0; i < count; i++) { if(i % 16 == 0 && i != 0) printf("\n"); printf("%.2x ", buf[i]); } printf("\n"); #endif for(i = 0; i < count; i++) { c = buf[i]; tputc(c); } } TermWidget::TermWidget() { pid_t pid; int fd; // QFont font("Terminus"); // QFont font("Ubuntu Mono"); // cell_font = font; // font.setPixelSize(12); QFont font("Bitstream Vera Sans Mono", 15); // font.setPixelSize(20); // font.setFixedPitch(true); // font.setKerning(false); setCellFont(font); QFontInfo info(font); QString family = info.family(); // qDebug("family = %s", family.toStdString().c_str()); #if defined(USE_QT4) setGeometry(600, 200, cell_width * COLS + 2, cell_height * ROWS); #elif defined(USE_QTOPIA) setGeometry(10, 30, cell_width * COLS + 2, cell_height * ROWS); #endif if((pid = forkpty(&fd, NULL, NULL, NULL)) < 0) { perror("forkpty"); return; } if (pid == 0) { static const char *argv[] = { "bash", 0 }; execve("/bin/bash", (char * const *)argv, NULL); } // qDebug("father"); g_pid = pid; g_fd = fd; signal(SIGCHLD, sigchld); readTimer = new QTimer(this); connect(readTimer, SIGNAL(timeout()), this, SLOT(doRead())); readTimer->start(1000); treset(); } bool TermWidget::setCellFont(QFont &font) { cell_font = font; cell_font.setFixedPitch(true); #if defined(USE_QT4) cell_font.setKerning(false); #endif cell_font.setStyleHint(QFont::TypeWriter); QFontMetrics fm(font); cell_width = fm.width('X'); cell_height = fm.height(); // qDebug("cell_width = %d", cell_width); // qDebug("cell_height = %d", cell_height); QFontMetrics qm(font); // qDebug("%d", qm.width("Hello")); // qDebug("%d", qm.width("I")); return true; } void TermWidget::doRead() { // qDebug("doRead"); fd_set rfd; FD_ZERO(&rfd); FD_SET(g_fd, &rfd); struct timeval timeout = {0,0}; timeout.tv_sec = 0; timeout.tv_usec = 20 * 1000; // 20 ms // bool stuff_to_print = 0; if(select(g_fd + 1, &rfd, NULL, NULL, &timeout) < 0) { return; } if(FD_ISSET(g_fd, &rfd)) { ttyread(); // stuff_to_print = 1; } draw(this); } void TermWidget::paintEvent(QPaintEvent *) { // qDebug("paintEvent"); QPainter painter(this); painter.setFont(cell_font); int x, y; for(y = 0; y < ROWS; y++) { QString str; for(x = 0; x < COLS; x++) { str += QChar(cell[y][x].c); } // if(y == 0) { // qDebug("str = %s", str.toStdString().c_str()); // } xdraws(painter, str, 0, y, COLS); } } void TermWidget::keyPressEvent(QKeyEvent *k) { #if defined(USE_QT4) // qDebug("<keyPressEvent> - %d, %s", // k->key(), // k->text().toStdString().c_str()); #elif defined(USE_QTOPIA) // qDebug("<keyPressEvent> - %d", k->key()); #endif if(k->text().isEmpty()) { // qDebug("text empty"); } else { // qDebug("text not empty"); } switch(k->key()) { case Qt::Key_Return: // qDebug("<keyPressEvent>: Key_Return"); break; default: break; } if(k->text().isEmpty()) { return; } #if defined(USE_QT4) QByteArray data = k->text().toLocal8Bit(); int n = write(g_fd, data.constData(), data.count()); #elif defined(USE_QTOPIA) QByteArray data = k->text().local8Bit(); int n = write(g_fd, data.data(), data.count()); #endif // qDebug("write: %d", n); } /* term */ #define ESC_BUF_SIZ 256 #define ESC_ARG_SIZ 16 #define CURSOR_DEFAULT 0 #define CURSOR_WRAPNEXT 1 #define ESC_START 1 #define ESC_CSI 2 /* CSI Escape sequence structs */ /* ESC '[' [[ [<priv>] <arg> [;]] <mode>] */ typedef struct { char buf[ESC_BUF_SIZ]; /* raw string */ int len; /* raw string length */ char priv; int arg[ESC_ARG_SIZ]; int narg; /* nb of args */ char mode; } CSIEscape; static CSIEscape escseq; void tsetchar(char c); void tmoveto(int x, int y); void tnewline(int first_col); void csireset(void); void csiparse(void); void csihandle(void); void csidump(void); void treset(void) { int i, j; for(i = 0; i < ROWS; i++) { for(j = 0; j < COLS; j++) { // if(j == 0) { // cell[i][j].c = 'a'; // } else if (j == 2) { // cell[i][j].c = (i + 1) / 10 + '0'; // } else if (j == 3) { // cell[i][j].c = (i + 1) % 10 + '0'; // } else if (j == COLS-1) { // cell[i][j].c = 'b'; // } else { cell[i][j].c = ' '; // } } dirty[i] = 1; } cursor_x = 0, cursor_y = 0; cursor_state = CURSOR_DEFAULT; esc = 0; } void tputc(char c) { if(esc & ESC_START) { if(esc & ESC_CSI) { escseq.buf[escseq.len++] = c; if((c >= 0x40 && c <= 0x7E) || escseq.len >= ESC_BUF_SIZ) { esc = 0; csiparse(); csihandle(); } } else { switch(c) { case '[': esc |= ESC_CSI; break; default: printf("unknown sequence ESC 0x%02X '%c'\n", c, isprint(c)? c : '.'); esc = 0; break; } } } else { switch(c) { case '\r': tmoveto(0, cursor_y); break; case '\n': tnewline(0); break; case '\033': csireset(); esc = ESC_START; break; default: if(cursor_state & CURSOR_WRAPNEXT) { tnewline(1); } tsetchar(c); if(cursor_x + 1 < COLS) { tmoveto(cursor_x + 1, cursor_y); } else { cursor_state |= CURSOR_WRAPNEXT; } break; } } } void tsetchar(char c) { cell[cursor_y][cursor_x].c = c; dirty[cursor_y] = 1; } void tmoveto(int x, int y) { if(x < 0) x = 0; if(x > COLS - 1) x = COLS - 1; if(y < 0) y = 0; if(y > ROWS - 1) y = ROWS - 1; cursor_x = x; cursor_y = y; cursor_state &= ~CURSOR_WRAPNEXT; } void tnewline(int first_col) { int y = cursor_y; y++; tmoveto(first_col ? 0 : cursor_x, y); } void csireset(void) { memset(&escseq, 0, sizeof(escseq)); } void csiparse(void) { /* int noarg = 1; */ char *p = escseq.buf; escseq.narg = 0; if(*p == '?') escseq.priv = 1, p++; while(p < escseq.buf + escseq.len) { while(isdigit(*p)) { escseq.arg[escseq.narg] *= 10; escseq.arg[escseq.narg] += *p++ - '0'/*, noarg = 0 */; } if(*p == ';' && escseq.narg+1 < ESC_ARG_SIZ) escseq.narg++, p++; else { escseq.mode = *p; escseq.narg++; return; } } } void csihandle(void) { switch(escseq.mode) { default: printf("unknown csi "); csidump(); break; } } void csidump(void) { int i; printf("ESC["); for(i = 0; i < escseq.len; i++) { uint c = escseq.buf[i] & 0xff; if(isprint(c)) putchar(c); else if(c == '\n') printf("(\\n)"); else if(c == '\r') printf("(\\r)"); else if(c == 0x1b) printf("(\\e)"); else printf("(%02x)", c); } putchar('\n'); } /* screen */ void draw(QWidget *w) { w->update(); } void xdraws(QPainter &painter, QString str, int x, int y, int len) { // QString str; // str += "aaa "; // str += QChar((y + 1) / 10 + '0'); // str += QChar((y + 1) % 10 + '0'); QRect rect(x * cell_width, y * cell_height, cell_width * len, cell_height); #if defined(USE_QT4) painter.drawText(rect, Qt::TextSingleLine, str); #elif defined(USE_QTOPIA) painter.drawText(rect, Qt::SingleLine, str); #endif } <|endoftext|>
<commit_before>// Copyright 2016 AUV-IITK #include <ros/ros.h> #include <std_msgs/Float32.h> #include <std_msgs/Float64.h> #include <std_msgs/Int32.h> #include <actionlib/server/simple_action_server.h> #include <motion_commons/ForwardAction.h> #include <dynamic_reconfigure/server.h> #include <motion_forward/pidConfig.h> #include <string> using std::string; typedef actionlib::SimpleActionServer<motion_commons::ForwardAction> Server; // defining the Client type float presentForwardPosition = 0; float previousForwardPosition = 0; float finalForwardPosition, error, output; bool initData = false; std_msgs::Int32 pwm; // pwm to be send to arduino // new inner class, to encapsulate the interaction with actionclient class innerActionClass { private: ros::NodeHandle nh_; Server forwardServer_; std::string action_name_; motion_commons::ForwardFeedback feedback_; motion_commons::ForwardResult result_; ros::Publisher PWM; float p, i, d; public: // Constructor, called when new instance of class declared explicit innerActionClass(string name) : // Defining the server, third argument is optional forwardServer_(nh_, name, boost::bind(&innerActionClass::analysisCB, this, _1), false) , action_name_(name) { // Add preempt callback forwardServer_.registerPreemptCallback(boost::bind(&innerActionClass::preemptCB, this)); // Declaring publisher for PWM PWM = nh_.advertise<std_msgs::Int32>("/pwm/forward", 1000); // Starting new Action Server forwardServer_.start(); } // default contructor ~innerActionClass(void) { } // callback for goal cancelled void preemptCB(void) { pwm.data = 0; PWM.publish(pwm); ROS_INFO("pwm send to arduino %d", pwm.data); // this command cancels the previous goal forwardServer_.setPreempted(); } // called when new goal recieved; Start motion and finish it, if not interupted void analysisCB(const motion_commons::ForwardGoalConstPtr goal) { ROS_INFO("Inside analysisCB"); int count = 0; int loopRate = 10; ros::Rate loop_rate(loopRate); // waiting till we recieve the first value from Camera else it's useless to any calculations while (!initData) { ROS_INFO("Waiting to get first input from Camera"); loop_rate.sleep(); } if (goal->Goal == 1) finalForwardPosition = 0; float derivative = 0, integral = 0, dt = 1.0 / loopRate; bool reached = false; pwm.data = 0; if (!forwardServer_.isActive()) return; while (!forwardServer_.isPreemptRequested() && ros::ok() && count < goal->loop) { error = finalForwardPosition - presentForwardPosition; integral += (error * dt); derivative = (presentForwardPosition - previousForwardPosition) / dt; output = (p * error) + (i * integral) + (d * derivative); forwardOutputPWMMapping(output); if (pwm.data < 2 && pwm.data > -2) { reached = true; pwm.data = 0; PWM.publish(pwm); ROS_INFO("thrusters stopped"); count++; } else { reached = false; count = 0; } if (forwardServer_.isPreemptRequested() || !ros::ok()) { ROS_INFO("%s: Preempted", action_name_.c_str()); // set the action state to preempted forwardServer_.setPreempted(); reached = false; break; } feedback_.DistanceRemaining = error; forwardServer_.publishFeedback(feedback_); PWM.publish(pwm); ROS_INFO("pwm send to arduino %d", pwm.data); ros::spinOnce(); loop_rate.sleep(); } if (reached) { result_.Result = reached; ROS_INFO("%s: Succeeded", action_name_.c_str()); // set the action state to succeeded forwardServer_.setSucceeded(result_); } } void forwardOutputPWMMapping(float output) { float maxOutput = 1000, minOutput = -maxOutput; float scale = 255 / maxOutput; if (output > maxOutput) output = maxOutput; if (output < minOutput) output = minOutput; float temp = output * scale; pwm.data = static_cast<int>(temp); } void setPID(float new_p, float new_i, float new_d) { p = new_p; i = new_i; d = new_d; } }; innerActionClass *object; // dynamic reconfig void callback(motion_forward::pidConfig &config, double level) { ROS_INFO("ForwardServer: Reconfigure Request: p= %f i= %f d=%f", config.p, config.i, config.d); object->setPID(config.p, config.i, config.d); } void distanceCb(std_msgs::Float64 msg) { // this is used to set the final angle after getting the value of first intial position if (initData == false) { presentForwardPosition = msg.data; previousForwardPosition = presentForwardPosition; initData = true; } else { previousForwardPosition = presentForwardPosition; presentForwardPosition = msg.data; } } int main(int argc, char **argv) { ros::init(argc, argv, "forward"); ros::NodeHandle n; double p_param, i_param, d_param; n.getParam("forward/p_param", p_param); n.getParam("forward/i_param", i_param); n.getParam("forward/d_param", d_param); ros::Subscriber xDistance = n.subscribe<std_msgs::Float64>("/varun/motion/x_distance", 1000, &distanceCb); ROS_INFO("Waiting for Goal"); object = new innerActionClass(ros::this_node::getName()); // register dynamic reconfig server. dynamic_reconfigure::Server<motion_forward::pidConfig> server; dynamic_reconfigure::Server<motion_forward::pidConfig>::CallbackType f; f = boost::bind(&callback, _1, _2); server.setCallback(f); // set launch file pid motion_forward::pidConfig config; config.p = p_param; config.i = i_param; config.d = d_param; callback(config, 0); ros::spin(); return 0; } <commit_msg>changed sign convention for forward motion<commit_after>// Copyright 2016 AUV-IITK #include <ros/ros.h> #include <std_msgs/Float32.h> #include <std_msgs/Float64.h> #include <std_msgs/Int32.h> #include <actionlib/server/simple_action_server.h> #include <motion_commons/ForwardAction.h> #include <dynamic_reconfigure/server.h> #include <motion_forward/pidConfig.h> #include <string> using std::string; typedef actionlib::SimpleActionServer<motion_commons::ForwardAction> Server; // defining the Client type float presentForwardPosition = 0; float previousForwardPosition = 0; float finalForwardPosition, error, output; bool initData = false; std_msgs::Int32 pwm; // pwm to be send to arduino // new inner class, to encapsulate the interaction with actionclient class innerActionClass { private: ros::NodeHandle nh_; Server forwardServer_; std::string action_name_; motion_commons::ForwardFeedback feedback_; motion_commons::ForwardResult result_; ros::Publisher PWM; float p, i, d; public: // Constructor, called when new instance of class declared explicit innerActionClass(string name) : // Defining the server, third argument is optional forwardServer_(nh_, name, boost::bind(&innerActionClass::analysisCB, this, _1), false) , action_name_(name) { // Add preempt callback forwardServer_.registerPreemptCallback(boost::bind(&innerActionClass::preemptCB, this)); // Declaring publisher for PWM PWM = nh_.advertise<std_msgs::Int32>("/pwm/forward", 1000); // Starting new Action Server forwardServer_.start(); } // default contructor ~innerActionClass(void) { } // callback for goal cancelled void preemptCB(void) { pwm.data = 0; PWM.publish(pwm); ROS_INFO("pwm send to arduino %d", pwm.data); // this command cancels the previous goal forwardServer_.setPreempted(); } // called when new goal recieved; Start motion and finish it, if not interupted void analysisCB(const motion_commons::ForwardGoalConstPtr goal) { ROS_INFO("Inside analysisCB"); int count = 0; int loopRate = 10; ros::Rate loop_rate(loopRate); // waiting till we recieve the first value from Camera else it's useless to any calculations while (!initData) { ROS_INFO("Waiting to get first input from Camera"); loop_rate.sleep(); } if (goal->Goal == 1) finalForwardPosition = 0; float derivative = 0, integral = 0, dt = 1.0 / loopRate; bool reached = false; pwm.data = 0; if (!forwardServer_.isActive()) return; while (!forwardServer_.isPreemptRequested() && ros::ok() && count < goal->loop) { error = presentForwardPosition - finalForwardPosition; integral += (error * dt); derivative = (presentForwardPosition - previousForwardPosition) / dt; output = (p * error) + (i * integral) + (d * derivative); forwardOutputPWMMapping(output); if (pwm.data < 2 && pwm.data > -2) { reached = true; pwm.data = 0; PWM.publish(pwm); ROS_INFO("thrusters stopped"); count++; } else { reached = false; count = 0; } if (forwardServer_.isPreemptRequested() || !ros::ok()) { ROS_INFO("%s: Preempted", action_name_.c_str()); // set the action state to preempted forwardServer_.setPreempted(); reached = false; break; } feedback_.DistanceRemaining = error; forwardServer_.publishFeedback(feedback_); PWM.publish(pwm); ROS_INFO("pwm send to arduino %d", pwm.data); ros::spinOnce(); loop_rate.sleep(); } if (reached) { result_.Result = reached; ROS_INFO("%s: Succeeded", action_name_.c_str()); // set the action state to succeeded forwardServer_.setSucceeded(result_); } } void forwardOutputPWMMapping(float output) { float maxOutput = 1000, minOutput = -maxOutput; float scale = 255 / maxOutput; if (output > maxOutput) output = maxOutput; if (output < minOutput) output = minOutput; float temp = output * scale; pwm.data = static_cast<int>(temp); } void setPID(float new_p, float new_i, float new_d) { p = new_p; i = new_i; d = new_d; } }; innerActionClass *object; // dynamic reconfig void callback(motion_forward::pidConfig &config, double level) { ROS_INFO("ForwardServer: Reconfigure Request: p= %f i= %f d=%f", config.p, config.i, config.d); object->setPID(config.p, config.i, config.d); } void distanceCb(std_msgs::Float64 msg) { // this is used to set the final angle after getting the value of first intial position if (initData == false) { presentForwardPosition = msg.data; previousForwardPosition = presentForwardPosition; initData = true; } else { previousForwardPosition = presentForwardPosition; presentForwardPosition = msg.data; } } int main(int argc, char **argv) { ros::init(argc, argv, "forward"); ros::NodeHandle n; double p_param, i_param, d_param; n.getParam("forward/p_param", p_param); n.getParam("forward/i_param", i_param); n.getParam("forward/d_param", d_param); ros::Subscriber xDistance = n.subscribe<std_msgs::Float64>("/varun/motion/x_distance", 1000, &distanceCb); ROS_INFO("Waiting for Goal"); object = new innerActionClass(ros::this_node::getName()); // register dynamic reconfig server. dynamic_reconfigure::Server<motion_forward::pidConfig> server; dynamic_reconfigure::Server<motion_forward::pidConfig>::CallbackType f; f = boost::bind(&callback, _1, _2); server.setCallback(f); // set launch file pid motion_forward::pidConfig config; config.p = p_param; config.i = i_param; config.d = d_param; callback(config, 0); ros::spin(); return 0; } <|endoftext|>
<commit_before>// $Id$ // // Copyright (C) 2003-2006 Rational Discovery LLC // // @@ All Rights Reserved @@ // #define NO_IMPORT_ARRAY #include <boost/python.hpp> #include <string> #include <GraphMol/RDKitBase.h> #include <GraphMol/QueryAtom.h> #include <RDGeneral/types.h> #include <Geometry/point.h> #include <GraphMol/SmilesParse/SmilesWrite.h> #include <GraphMol/SmilesParse/SmartsWrite.h> #include "seqs.hpp" #include <algorithm> namespace python = boost::python; namespace RDKit{ void AtomSetProp(const Atom *atom, const char *key,std::string val) { //std::cerr<<"asp: "<<atom<<" " << key<<" - " << val << std::endl; atom->setProp(key, val); } int AtomHasProp(const Atom *atom, const char *key) { //std::cerr<<"ahp: "<<atom<<" " << key<< std::endl; int res = atom->hasProp(key); return res; } std::string AtomGetProp(const Atom *atom, const char *key) { if (!atom->hasProp(key)) { PyErr_SetString(PyExc_KeyError,key); throw python::error_already_set(); } std::string res; atom->getProp(key, res); return res; } python::tuple AtomGetNeighbors(Atom *atom){ python::list res; const ROMol *parent = &atom->getOwningMol(); ROMol::ADJ_ITER begin,end; boost::tie(begin,end) = parent->getAtomNeighbors(atom); while(begin!=end){ res.append(python::ptr(parent->getAtomWithIdx(*begin))); begin++; } return python::tuple(res); } python::tuple AtomGetBonds(Atom *atom){ python::list res; const ROMol *parent = &atom->getOwningMol(); ROMol::OEDGE_ITER begin,end; ROMol::GRAPH_MOL_BOND_PMAP::const_type pMap = parent->getBondPMap(); boost::tie(begin,end) = parent->getAtomBonds(atom); while(begin!=end){ Bond *tmpB = pMap[*begin]; res.append(python::ptr(tmpB)); begin++; } return python::tuple(res); } bool AtomIsInRing(const Atom *atom){ if(!atom->getOwningMol().getRingInfo()->isInitialized()){ MolOps::findSSSR(atom->getOwningMol()); } return atom->getOwningMol().getRingInfo()->numAtomRings(atom->getIdx())!=0; } bool AtomIsInRingSize(const Atom *atom,int size){ if(!atom->getOwningMol().getRingInfo()->isInitialized()){ MolOps::findSSSR(atom->getOwningMol()); } return atom->getOwningMol().getRingInfo()->isAtomInRingOfSize(atom->getIdx(),size); } std::string AtomGetSmarts(const Atom *atom){ std::string res; if(atom->hasQuery()){ res=SmartsWrite::GetAtomSmarts(static_cast<const QueryAtom *>(atom)); } else { res = SmilesWrite::GetAtomSmiles(atom); } return res; } BOOST_PYTHON_MEMBER_FUNCTION_OVERLOADS(getTotalNumHs_ol, getTotalNumHs, 0, 1) // FIX: is there any reason at all to not just prevent the construction of Atoms? std::string atomClassDoc="The class to store Atoms.\n\ Note that, though it is possible to create one, having an Atom on its own\n\ (i.e not associated with a molecule) is not particularly useful.\n"; struct atom_wrapper { static void wrap(){ python::class_<Atom>("Atom",atomClassDoc.c_str(),python::init<std::string>()) .def(python::init<unsigned int>("Constructor, takes either an int (atomic number) or a string (atomic symbol).\n")) .def("GetAtomicNum",&Atom::getAtomicNum, "Returns the atomic number.") .def("SetAtomicNum",&Atom::setAtomicNum, "Sets the atomic number, takes an integer value as an argument") .def("GetSymbol",&Atom::getSymbol, "Returns the atomic number (a string)\n") .def("GetIdx",&Atom::getIdx, "Returns the atom's index (ordering in the molecule)\n") .def("GetDegree",&Atom::getDegree, "Returns the degree of the atom in the molecule.\n\n" " The degree of an atom is defined to be its number of\n" " directly-bonded neighbors.\n" " The degree is independent of bond orders.\n") .def("GetTotalNumHs",&Atom::getTotalNumHs, getTotalNumHs_ol(python::args("includeNeighbors"), "Returns the total number of Hs (explicit and implicit) on the atom.\n\n" " ARGUMENTS:\n\n" " - includeNeighbors: (optional) toggles inclusion of neighboring H atoms in the sum.\n" " Defaults to 0.\n")) .def("GetNumImplicitHs",&Atom::getNumImplicitHs, "Returns the total number of implicit Hs on the atom.\n") .def("GetExplicitValence",&Atom::getExplicitValence, "Returns the number of explicit Hs on the atom.\n") .def("GetImplicitValence",&Atom::getImplicitValence, "Returns the number of implicit Hs on the atom.\n") .def("GetFormalCharge",&Atom::getFormalCharge) .def("SetFormalCharge",&Atom::setFormalCharge) .def("SetNoImplicit",&Atom::setNoImplicit, "Sets a marker on the atom that *disallows* implicit Hs.\n" " This holds even if the atom would otherwise have implicit Hs added.\n") .def("GetNoImplicit",&Atom::getNoImplicit, "Returns whether or not the atom is *allowed* to have implicit Hs.\n") .def("SetNumExplicitHs",&Atom::setNumExplicitHs) .def("GetNumExplicitHs",&Atom::getNumExplicitHs) .def("SetIsAromatic",&Atom::setIsAromatic) .def("GetIsAromatic",&Atom::getIsAromatic) .def("SetMass",&Atom::setMass) .def("GetMass",&Atom::getMass) // NOTE: these may be used at some point in the future, but they // aren't now, so there's no point in confusing things. //.def("SetDativeFlag",&Atom::setDativeFlag) //.def("GetDativeFlag",&Atom::getDativeFlag) //.def("ClearDativeFlag",&Atom::clearDativeFlag) .def("SetChiralTag",&Atom::setChiralTag) .def("InvertChirality",&Atom::invertChirality) .def("GetChiralTag",&Atom::getChiralTag) .def("SetHybridization",&Atom::setHybridization, "Sets the hybridization of the atom.\n" " The argument should be a HybridizationType\n") .def("GetHybridization",&Atom::getHybridization, "Returns the atom's hybridization.\n") .def("GetOwningMol",&Atom::getOwningMol, "Returns the Mol that owns this atom.\n", python::return_value_policy<python::reference_existing_object>()) .def("GetNeighbors",AtomGetNeighbors, "Returns a read-only sequence of the atom's neighbors\n") .def("GetBonds",AtomGetBonds, "Returns a read-only sequence of the atom's bonds\n") .def("Match",(bool (Atom::*)(const Atom *) const)&Atom::Match, "Returns whether or not this atom matches another Atom.\n\n" " Each Atom (or query Atom) has a query function which is\n" " used for this type of matching.\n\n" " ARGUMENTS:\n" " - other: the other Atom to which to compare\n") .def("IsInRingSize",AtomIsInRingSize, "Returns whether or not the atom is in a ring of a particular size.\n\n" " ARGUMENTS:\n" " - size: the ring size to look for\n") .def("IsInRing",AtomIsInRing, "Returns whether or not the atom is in a ring\n\n") .def("HasQuery",&Atom::hasQuery, "Returns whether or not the atom has an associated query\n\n") .def("GetSmarts",AtomGetSmarts, "returns the SMARTS (or SMILES) string for an Atom\n\n") // properties .def("SetProp",AtomSetProp, (python::arg("self"), python::arg("key"), python::arg("val")), "Sets an atomic property\n\n" " ARGUMENTS:\n" " - key: the name of the property to be set (a string).\n" " - value: the property value (a string).\n\n" ) .def("GetProp", AtomGetProp, "Returns the value of the property.\n\n" " ARGUMENTS:\n" " - key: the name of the property to return (a string).\n\n" " RETURNS: a string\n\n" " NOTE:\n" " - If the property has not been set, a KeyError exception will be raised.\n") .def("HasProp", AtomHasProp, "Queries a Atom to see if a particular property has been assigned.\n\n" " ARGUMENTS:\n" " - key: the name of the property to check for (a string).\n") ; python::enum_<Atom::HybridizationType>("HybridizationType") .value("UNSPECIFIED",Atom::UNSPECIFIED) .value("SP",Atom::SP) .value("SP2",Atom::SP2) .value("SP3",Atom::SP3) .value("SP3D",Atom::SP3D) .value("SP3D2",Atom::SP3D2) .value("OTHER",Atom::OTHER) ; python::enum_<Atom::ChiralType>("ChiralType") .value("CHI_UNSPECIFIED",Atom::CHI_UNSPECIFIED) .value("CHI_TETRAHEDRAL_CW",Atom::CHI_TETRAHEDRAL_CW) .value("CHI_TETRAHEDRAL_CCW",Atom::CHI_TETRAHEDRAL_CCW) .value("CHI_OTHER",Atom::CHI_OTHER) ; }; }; }// end of namespace void wrap_atom() { RDKit::atom_wrapper::wrap(); } <commit_msg>a bit of refactoring.<commit_after>// $Id$ // // Copyright (C) 2003-2006 Rational Discovery LLC // // @@ All Rights Reserved @@ // #define NO_IMPORT_ARRAY #include <boost/python.hpp> #include <string> #include <GraphMol/RDKitBase.h> #include <GraphMol/QueryAtom.h> #include <RDGeneral/types.h> #include <Geometry/point.h> #include <GraphMol/SmilesParse/SmilesWrite.h> #include <GraphMol/SmilesParse/SmartsWrite.h> #include "seqs.hpp" #include <algorithm> namespace python = boost::python; namespace RDKit{ void AtomSetProp(const Atom *atom, const char *key,std::string val) { //std::cerr<<"asp: "<<atom<<" " << key<<" - " << val << std::endl; atom->setProp(key, val); } int AtomHasProp(const Atom *atom, const char *key) { //std::cerr<<"ahp: "<<atom<<" " << key<< std::endl; int res = atom->hasProp(key); return res; } std::string AtomGetProp(const Atom *atom, const char *key) { if (!atom->hasProp(key)) { PyErr_SetString(PyExc_KeyError,key); throw python::error_already_set(); } std::string res; atom->getProp(key, res); return res; } python::tuple AtomGetNeighbors(Atom *atom){ python::list res; const ROMol *parent = &atom->getOwningMol(); ROMol::ADJ_ITER begin,end; boost::tie(begin,end) = parent->getAtomNeighbors(atom); while(begin!=end){ res.append(python::ptr(parent->getAtomWithIdx(*begin))); begin++; } return python::tuple(res); } python::tuple AtomGetBonds(Atom *atom){ python::list res; const ROMol *parent = &atom->getOwningMol(); ROMol::OEDGE_ITER begin,end; ROMol::GRAPH_MOL_BOND_PMAP::const_type pMap = parent->getBondPMap(); boost::tie(begin,end) = parent->getAtomBonds(atom); while(begin!=end){ Bond *tmpB = pMap[*begin]; res.append(python::ptr(tmpB)); begin++; } return python::tuple(res); } bool AtomIsInRing(const Atom *atom){ if(!atom->getOwningMol().getRingInfo()->isInitialized()){ MolOps::findSSSR(atom->getOwningMol()); } return atom->getOwningMol().getRingInfo()->numAtomRings(atom->getIdx())!=0; } bool AtomIsInRingSize(const Atom *atom,int size){ if(!atom->getOwningMol().getRingInfo()->isInitialized()){ MolOps::findSSSR(atom->getOwningMol()); } return atom->getOwningMol().getRingInfo()->isAtomInRingOfSize(atom->getIdx(),size); } std::string AtomGetSmarts(const Atom *atom){ std::string res; if(atom->hasQuery()){ res=SmartsWrite::GetAtomSmarts(static_cast<const QueryAtom *>(atom)); } else { res = SmilesWrite::GetAtomSmiles(atom); } return res; } // FIX: is there any reason at all to not just prevent the construction of Atoms? std::string atomClassDoc="The class to store Atoms.\n\ Note that, though it is possible to create one, having an Atom on its own\n\ (i.e not associated with a molecule) is not particularly useful.\n"; struct atom_wrapper { static void wrap(){ python::class_<Atom>("Atom",atomClassDoc.c_str(),python::init<std::string>()) .def(python::init<unsigned int>("Constructor, takes either an int (atomic number) or a string (atomic symbol).\n")) .def("GetAtomicNum",&Atom::getAtomicNum, "Returns the atomic number.") .def("SetAtomicNum",&Atom::setAtomicNum, "Sets the atomic number, takes an integer value as an argument") .def("GetSymbol",&Atom::getSymbol, "Returns the atomic number (a string)\n") .def("GetIdx",&Atom::getIdx, "Returns the atom's index (ordering in the molecule)\n") .def("GetDegree",&Atom::getDegree, "Returns the degree of the atom in the molecule.\n\n" " The degree of an atom is defined to be its number of\n" " directly-bonded neighbors.\n" " The degree is independent of bond orders.\n") .def("GetTotalNumHs",&Atom::getTotalNumHs, (python::arg("self"),python::arg("includeNeighbors")=false), "Returns the total number of Hs (explicit and implicit) on the atom.\n\n" " ARGUMENTS:\n\n" " - includeNeighbors: (optional) toggles inclusion of neighboring H atoms in the sum.\n" " Defaults to 0.\n") .def("GetNumImplicitHs",&Atom::getNumImplicitHs, "Returns the total number of implicit Hs on the atom.\n") .def("GetExplicitValence",&Atom::getExplicitValence, "Returns the number of explicit Hs on the atom.\n") .def("GetImplicitValence",&Atom::getImplicitValence, "Returns the number of implicit Hs on the atom.\n") .def("GetFormalCharge",&Atom::getFormalCharge) .def("SetFormalCharge",&Atom::setFormalCharge) .def("SetNoImplicit",&Atom::setNoImplicit, "Sets a marker on the atom that *disallows* implicit Hs.\n" " This holds even if the atom would otherwise have implicit Hs added.\n") .def("GetNoImplicit",&Atom::getNoImplicit, "Returns whether or not the atom is *allowed* to have implicit Hs.\n") .def("SetNumExplicitHs",&Atom::setNumExplicitHs) .def("GetNumExplicitHs",&Atom::getNumExplicitHs) .def("SetIsAromatic",&Atom::setIsAromatic) .def("GetIsAromatic",&Atom::getIsAromatic) .def("SetMass",&Atom::setMass) .def("GetMass",&Atom::getMass) // NOTE: these may be used at some point in the future, but they // aren't now, so there's no point in confusing things. //.def("SetDativeFlag",&Atom::setDativeFlag) //.def("GetDativeFlag",&Atom::getDativeFlag) //.def("ClearDativeFlag",&Atom::clearDativeFlag) .def("SetChiralTag",&Atom::setChiralTag) .def("InvertChirality",&Atom::invertChirality) .def("GetChiralTag",&Atom::getChiralTag) .def("SetHybridization",&Atom::setHybridization, "Sets the hybridization of the atom.\n" " The argument should be a HybridizationType\n") .def("GetHybridization",&Atom::getHybridization, "Returns the atom's hybridization.\n") .def("GetOwningMol",&Atom::getOwningMol, "Returns the Mol that owns this atom.\n", python::return_value_policy<python::reference_existing_object>()) .def("GetNeighbors",AtomGetNeighbors, "Returns a read-only sequence of the atom's neighbors\n") .def("GetBonds",AtomGetBonds, "Returns a read-only sequence of the atom's bonds\n") .def("Match",(bool (Atom::*)(const Atom *) const)&Atom::Match, "Returns whether or not this atom matches another Atom.\n\n" " Each Atom (or query Atom) has a query function which is\n" " used for this type of matching.\n\n" " ARGUMENTS:\n" " - other: the other Atom to which to compare\n") .def("IsInRingSize",AtomIsInRingSize, "Returns whether or not the atom is in a ring of a particular size.\n\n" " ARGUMENTS:\n" " - size: the ring size to look for\n") .def("IsInRing",AtomIsInRing, "Returns whether or not the atom is in a ring\n\n") .def("HasQuery",&Atom::hasQuery, "Returns whether or not the atom has an associated query\n\n") .def("GetSmarts",AtomGetSmarts, "returns the SMARTS (or SMILES) string for an Atom\n\n") // properties .def("SetProp",AtomSetProp, (python::arg("self"), python::arg("key"), python::arg("val")), "Sets an atomic property\n\n" " ARGUMENTS:\n" " - key: the name of the property to be set (a string).\n" " - value: the property value (a string).\n\n" ) .def("GetProp", AtomGetProp, "Returns the value of the property.\n\n" " ARGUMENTS:\n" " - key: the name of the property to return (a string).\n\n" " RETURNS: a string\n\n" " NOTE:\n" " - If the property has not been set, a KeyError exception will be raised.\n") .def("HasProp", AtomHasProp, "Queries a Atom to see if a particular property has been assigned.\n\n" " ARGUMENTS:\n" " - key: the name of the property to check for (a string).\n") ; python::enum_<Atom::HybridizationType>("HybridizationType") .value("UNSPECIFIED",Atom::UNSPECIFIED) .value("SP",Atom::SP) .value("SP2",Atom::SP2) .value("SP3",Atom::SP3) .value("SP3D",Atom::SP3D) .value("SP3D2",Atom::SP3D2) .value("OTHER",Atom::OTHER) ; python::enum_<Atom::ChiralType>("ChiralType") .value("CHI_UNSPECIFIED",Atom::CHI_UNSPECIFIED) .value("CHI_TETRAHEDRAL_CW",Atom::CHI_TETRAHEDRAL_CW) .value("CHI_TETRAHEDRAL_CCW",Atom::CHI_TETRAHEDRAL_CCW) .value("CHI_OTHER",Atom::CHI_OTHER) ; }; }; }// end of namespace void wrap_atom() { RDKit::atom_wrapper::wrap(); } <|endoftext|>
<commit_before>/** \file ExecUtil.cc * \brief Implementation of the ExecUtil class. * \author Dr. Gordon W. Paynter * \author Dr. Johannes Ruscheinski */ /* * Copyright 2004-2008 Project iVia. * Copyright 2004-2008 The Regents of The University of California. * Copyright 2017-2018 Universitätsbibliothek Tübingen * * This file is part of the libiViaCore package. * * The libiViaCore package 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 of the License, or * (at your option) any later version. * * libiViaCore 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 libiViaCore; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ExecUtil.h" #include <stdexcept> #include <cassert> #include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <fcntl.h> #include <signal.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <unordered_map> #include "StringUtil.h" #include "FileUtil.h" #include "util.h" namespace { // The following variables are set in Execute. static bool alarm_went_off; pid_t child_pid; // SigAlarmHandler -- Used by Execute. // void SigAlarmHandler(int /* sig_no */) { alarm_went_off = true; } bool IsExecutableFile(const std::string &path) { struct stat statbuf; return ::stat(path.c_str(), &statbuf) == 0 and (statbuf.st_mode & S_IXUSR); } enum class ExecMode { WAIT, //< Exec() will wait for the child to exit. DETACH //< Exec() will not wait for the child to exit and will return the child's PID. }; int Exec(const std::string &command, const std::vector<std::string> &args, const std::string &new_stdin, const std::string &new_stdout, const std::string &new_stderr, const ExecMode exec_mode, unsigned timeout_in_seconds, const int tardy_child_signal) { errno = 0; if (::access(command.c_str(), X_OK) != 0) throw std::runtime_error("in ExecUtil::Exec: can't execute \"" + command + "\"!"); if (exec_mode == ExecMode::DETACH and timeout_in_seconds > 0) throw std::runtime_error("in ExecUtil::Exec: non-zero timeout is incompatible w/ ExecMode::DETACH!"); const int EXECVE_FAILURE(248); const pid_t pid = ::fork(); if (pid == -1) throw std::runtime_error("in Exec: ::fork() failed: " + std::to_string(errno) + "!"); // The child process: else if (pid == 0) { // Make us the leader of a new process group: if (::setsid() == static_cast<pid_t>(-1)) logger->error("in Exec(): child failed to become a new session leader!"); if (not new_stdin.empty()) { const int new_stdin_fd(::open(new_stdin.c_str(), O_RDONLY)); if (new_stdin_fd == -1) ::_exit(-1); if (::dup2(new_stdin_fd, STDIN_FILENO) == -1) ::_exit(-1); ::close(new_stdin_fd); } if (not new_stdout.empty()) { const int new_stdout_fd(::open(new_stdout.c_str(), O_WRONLY | O_CREAT, 0644)); if (new_stdout_fd == -1) ::_exit(-1); if (::dup2(new_stdout_fd, STDOUT_FILENO) == -1) ::_exit(-1); ::close(new_stdout_fd); } if (not new_stderr.empty()) { const int new_stderr_fd(::open(new_stderr.c_str(), O_WRONLY | O_CREAT, 0644)); if (new_stderr_fd == -1) ::_exit(-1); if (::dup2(new_stderr_fd, STDERR_FILENO) == -1) ::_exit(-1); ::close(new_stderr_fd); } // Build the argument list for execve(2): #pragma GCC diagnostic ignored "-Wvla" char *argv[1 + args.size() + 1]; #ifndef __clang__ #pragma GCC diagnostic ignored "+Wvla" #endif unsigned arg_no(0); argv[arg_no++] = ::strdup(command.c_str()); for (const auto &arg : args) argv[arg_no++] = ::strdup(arg.c_str()); argv[arg_no] = nullptr; ::execv(command.c_str(), argv); ::_exit(EXECVE_FAILURE); // We typically never get here. } // The parent of the fork: else { if (exec_mode == ExecMode::DETACH) return pid; void (*old_alarm_handler)(int) = nullptr; if (timeout_in_seconds > 0) { // Install new alarm handler... alarm_went_off = false; child_pid = pid; old_alarm_handler = ::signal(SIGALRM, SigAlarmHandler); // ...and wind the clock: ::alarm(timeout_in_seconds); } int child_exit_status; errno = 0; int wait_retval = ::wait4(pid, &child_exit_status, 0, nullptr); assert(wait_retval == pid or errno == EINTR); if (timeout_in_seconds > 0) { // Cancel any outstanding alarm: ::alarm(0); // Restore the old alarm handler: ::signal(SIGALRM, old_alarm_handler); // Check to see whether the test timed out or not: if (alarm_went_off) { // Snuff out all of our offspring. ::kill(-pid, tardy_child_signal); while (::wait4(-pid, &child_exit_status, 0, nullptr) != -1) /* Intentionally empty! */; errno = ETIME; return -1; } } // Now process the child's various exit status values: if (WIFEXITED(child_exit_status)) { switch (WEXITSTATUS(child_exit_status)) { case EXECVE_FAILURE: throw std::runtime_error("in Exec: failed to execve(2) in child!"); default: return WEXITSTATUS(child_exit_status); } } else if (WIFSIGNALED(child_exit_status)) throw std::runtime_error("in Exec: \"" + command + "\" killed by signal " + std::to_string(WTERMSIG(child_exit_status)) + "!"); else // I have no idea how we got here! logger->error("in Exec: dazed and confused!"); } return 0; // Keep the compiler happy! } } // unnamed namespace namespace ExecUtil { SignalBlocker::SignalBlocker(const int signal_to_block) { sigset_t new_set; ::sigemptyset(&new_set); ::sigaddset(&new_set, signal_to_block); if (::sigprocmask(SIG_BLOCK, &new_set, &saved_set_) != 0) logger->error("in ExecUtil::SignalBlocker::SignalBlocker: call to sigprocmask(2) failed!"); } SignalBlocker::~SignalBlocker() { if (::sigprocmask(SIG_SETMASK, &saved_set_, nullptr) != 0) logger->error("in ExecUtil::SignalBlocker::~SignalBlocker: call to sigprocmask(2) failed!"); } int Exec(const std::string &command, const std::vector<std::string> &args, const std::string &new_stdin, const std::string &new_stdout, const std::string &new_stderr, const unsigned timeout_in_seconds, const int tardy_child_signal) { return ::Exec(command, args, new_stdin, new_stdout, new_stderr, ExecMode::WAIT, timeout_in_seconds, tardy_child_signal); } void ExecOrDie(const std::string &command, const std::vector<std::string> &args, const std::string &new_stdin, const std::string &new_stdout, const std::string &new_stderr, const unsigned timeout_in_seconds, const int tardy_child_signal) { int exit_code; if ((exit_code = Exec(command, args, new_stdin, new_stdout, new_stderr, timeout_in_seconds, tardy_child_signal)) != 0) LOG_ERROR("Failed to execute \"" + command + "\"! (exit code was " + std::to_string(exit_code) + ")"); } pid_t Spawn(const std::string &command, const std::vector<std::string> &args, const std::string &new_stdin, const std::string &new_stdout , const std::string &new_stderr) { return ::Exec(command, args, new_stdin, new_stdout, new_stderr, ExecMode::DETACH, 0, SIGKILL /* Not used because the timeout is 0. */); } std::unordered_map<std::string, std::string> which_cache; std::string Which(const std::string &executable_candidate) { auto which_cache_entry = which_cache.find(executable_candidate); if (which_cache_entry != which_cache.cend()) return which_cache[executable_candidate]; std::string executable; const size_t last_slash_pos(executable_candidate.find_last_of('/')); if (last_slash_pos != std::string::npos) { if (not IsExecutableFile(executable_candidate)) return ""; executable = executable_candidate; } if (executable.empty()) { const char * const PATH(::secure_getenv("PATH")); if (PATH == nullptr) return ""; const std::string path_str(PATH); std::vector<std::string> path_compoments; StringUtil::Split(path_str, ':', &path_compoments); for (const auto &path_compoment : path_compoments) { const std::string full_path(path_compoment + "/" + executable_candidate); if (IsExecutableFile(full_path)) { executable = full_path; break; } } } if (executable.empty()) return ""; else { which_cache[executable_candidate] = executable; return executable; } } std::string LocateOrDie(const std::string &executable_candidate) { const std::string path(ExecUtil::Which(executable_candidate)); if (path.empty()) logger->error("in ExecUtil::LocateOrDie: can't find \"" + executable_candidate + "\" in our PATH environment!"); return path; } bool ExecSubcommandAndCaptureStdout(const std::string &command, std::string * const stdout_output) { stdout_output->clear(); FILE * const subcommand_stdout(::popen(command.c_str(), "r")); if (subcommand_stdout == nullptr) return false; int ch; while ((ch = std::getc(subcommand_stdout)) != EOF) *stdout_output += static_cast<char>(ch); const int ret_code(::pclose(subcommand_stdout)); if (ret_code == -1) logger->error("pclose(3) failed: " + std::string(::strerror(errno))); return WEXITSTATUS(ret_code) == 0; } bool ExecSubcommandAndCaptureStdoutAndStderr(const std::string &command, const std::vector<std::string> &args, std::string * const stdout_output, std::string * const stderr_output) { FileUtil::AutoTempFile stdout_temp; FileUtil::AutoTempFile stderr_temp; const int retcode(Exec(command, args, /* new_stdin = */ "", stdout_temp.getFilePath(), stderr_temp.getFilePath())); if (retcode != 0) return false; if (not FileUtil::ReadString(stdout_temp.getFilePath(), stdout_output)) logger->error("failed to read temporary file w/ stdout contents!"); if (not FileUtil::ReadString(stderr_temp.getFilePath(), stderr_output)) logger->error("failed to read temporary file w/ stderr contents!"); return true; } bool ShouldScheduleNewProcess() { static const long NO_OF_CORES(::sysconf(_SC_NPROCESSORS_ONLN)); double loadavg; if (unlikely(::getloadavg(&loadavg, 1) == -1)) LOG_ERROR("getloadavg(3) failed!"); return loadavg < NO_OF_CORES - 0.5; } void FindActivePrograms(const std::string &program_name, std::unordered_set<unsigned> * const pids) { pids->clear(); std::string stdout; ExecSubcommandAndCaptureStdout("pgrep " + program_name, &stdout); std::unordered_set<std::string> pids_strings; StringUtil::Split(stdout, '\n', &pids_strings); for (const auto pid : pids_strings) pids->emplace(StringUtil::ToUnsigned(pid)); } std::unordered_set<unsigned> FindActivePrograms(const std::string &program_name) { std::unordered_set<unsigned> pids; FindActivePrograms(program_name, &pids); return pids; } } // namespace ExecUtil <commit_msg>ExecUtil: Correctly handle return codes in ExecSubcommandAndCaptureStdoutAndStderr<commit_after>/** \file ExecUtil.cc * \brief Implementation of the ExecUtil class. * \author Dr. Gordon W. Paynter * \author Dr. Johannes Ruscheinski */ /* * Copyright 2004-2008 Project iVia. * Copyright 2004-2008 The Regents of The University of California. * Copyright 2017-2018 Universitätsbibliothek Tübingen * * This file is part of the libiViaCore package. * * The libiViaCore package 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 of the License, or * (at your option) any later version. * * libiViaCore 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 libiViaCore; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "ExecUtil.h" #include <stdexcept> #include <cassert> #include <cerrno> #include <cstdio> #include <cstdlib> #include <cstring> #include <fcntl.h> #include <signal.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <unordered_map> #include "StringUtil.h" #include "FileUtil.h" #include "util.h" namespace { // The following variables are set in Execute. static bool alarm_went_off; pid_t child_pid; // SigAlarmHandler -- Used by Execute. // void SigAlarmHandler(int /* sig_no */) { alarm_went_off = true; } bool IsExecutableFile(const std::string &path) { struct stat statbuf; return ::stat(path.c_str(), &statbuf) == 0 and (statbuf.st_mode & S_IXUSR); } enum class ExecMode { WAIT, //< Exec() will wait for the child to exit. DETACH //< Exec() will not wait for the child to exit and will return the child's PID. }; int Exec(const std::string &command, const std::vector<std::string> &args, const std::string &new_stdin, const std::string &new_stdout, const std::string &new_stderr, const ExecMode exec_mode, unsigned timeout_in_seconds, const int tardy_child_signal) { errno = 0; if (::access(command.c_str(), X_OK) != 0) throw std::runtime_error("in ExecUtil::Exec: can't execute \"" + command + "\"!"); if (exec_mode == ExecMode::DETACH and timeout_in_seconds > 0) throw std::runtime_error("in ExecUtil::Exec: non-zero timeout is incompatible w/ ExecMode::DETACH!"); const int EXECVE_FAILURE(248); const pid_t pid = ::fork(); if (pid == -1) throw std::runtime_error("in Exec: ::fork() failed: " + std::to_string(errno) + "!"); // The child process: else if (pid == 0) { // Make us the leader of a new process group: if (::setsid() == static_cast<pid_t>(-1)) logger->error("in Exec(): child failed to become a new session leader!"); if (not new_stdin.empty()) { const int new_stdin_fd(::open(new_stdin.c_str(), O_RDONLY)); if (new_stdin_fd == -1) ::_exit(-1); if (::dup2(new_stdin_fd, STDIN_FILENO) == -1) ::_exit(-1); ::close(new_stdin_fd); } if (not new_stdout.empty()) { const int new_stdout_fd(::open(new_stdout.c_str(), O_WRONLY | O_CREAT, 0644)); if (new_stdout_fd == -1) ::_exit(-1); if (::dup2(new_stdout_fd, STDOUT_FILENO) == -1) ::_exit(-1); ::close(new_stdout_fd); } if (not new_stderr.empty()) { const int new_stderr_fd(::open(new_stderr.c_str(), O_WRONLY | O_CREAT, 0644)); if (new_stderr_fd == -1) ::_exit(-1); if (::dup2(new_stderr_fd, STDERR_FILENO) == -1) ::_exit(-1); ::close(new_stderr_fd); } // Build the argument list for execve(2): #pragma GCC diagnostic ignored "-Wvla" char *argv[1 + args.size() + 1]; #ifndef __clang__ #pragma GCC diagnostic ignored "+Wvla" #endif unsigned arg_no(0); argv[arg_no++] = ::strdup(command.c_str()); for (const auto &arg : args) argv[arg_no++] = ::strdup(arg.c_str()); argv[arg_no] = nullptr; ::execv(command.c_str(), argv); ::_exit(EXECVE_FAILURE); // We typically never get here. } // The parent of the fork: else { if (exec_mode == ExecMode::DETACH) return pid; void (*old_alarm_handler)(int) = nullptr; if (timeout_in_seconds > 0) { // Install new alarm handler... alarm_went_off = false; child_pid = pid; old_alarm_handler = ::signal(SIGALRM, SigAlarmHandler); // ...and wind the clock: ::alarm(timeout_in_seconds); } int child_exit_status; errno = 0; int wait_retval = ::wait4(pid, &child_exit_status, 0, nullptr); assert(wait_retval == pid or errno == EINTR); if (timeout_in_seconds > 0) { // Cancel any outstanding alarm: ::alarm(0); // Restore the old alarm handler: ::signal(SIGALRM, old_alarm_handler); // Check to see whether the test timed out or not: if (alarm_went_off) { // Snuff out all of our offspring. ::kill(-pid, tardy_child_signal); while (::wait4(-pid, &child_exit_status, 0, nullptr) != -1) /* Intentionally empty! */; errno = ETIME; return -1; } } // Now process the child's various exit status values: if (WIFEXITED(child_exit_status)) { switch (WEXITSTATUS(child_exit_status)) { case EXECVE_FAILURE: throw std::runtime_error("in Exec: failed to execve(2) in child!"); default: return WEXITSTATUS(child_exit_status); } } else if (WIFSIGNALED(child_exit_status)) throw std::runtime_error("in Exec: \"" + command + "\" killed by signal " + std::to_string(WTERMSIG(child_exit_status)) + "!"); else // I have no idea how we got here! logger->error("in Exec: dazed and confused!"); } return 0; // Keep the compiler happy! } } // unnamed namespace namespace ExecUtil { SignalBlocker::SignalBlocker(const int signal_to_block) { sigset_t new_set; ::sigemptyset(&new_set); ::sigaddset(&new_set, signal_to_block); if (::sigprocmask(SIG_BLOCK, &new_set, &saved_set_) != 0) logger->error("in ExecUtil::SignalBlocker::SignalBlocker: call to sigprocmask(2) failed!"); } SignalBlocker::~SignalBlocker() { if (::sigprocmask(SIG_SETMASK, &saved_set_, nullptr) != 0) logger->error("in ExecUtil::SignalBlocker::~SignalBlocker: call to sigprocmask(2) failed!"); } int Exec(const std::string &command, const std::vector<std::string> &args, const std::string &new_stdin, const std::string &new_stdout, const std::string &new_stderr, const unsigned timeout_in_seconds, const int tardy_child_signal) { return ::Exec(command, args, new_stdin, new_stdout, new_stderr, ExecMode::WAIT, timeout_in_seconds, tardy_child_signal); } void ExecOrDie(const std::string &command, const std::vector<std::string> &args, const std::string &new_stdin, const std::string &new_stdout, const std::string &new_stderr, const unsigned timeout_in_seconds, const int tardy_child_signal) { int exit_code; if ((exit_code = Exec(command, args, new_stdin, new_stdout, new_stderr, timeout_in_seconds, tardy_child_signal)) != 0) LOG_ERROR("Failed to execute \"" + command + "\"! (exit code was " + std::to_string(exit_code) + ")"); } pid_t Spawn(const std::string &command, const std::vector<std::string> &args, const std::string &new_stdin, const std::string &new_stdout , const std::string &new_stderr) { return ::Exec(command, args, new_stdin, new_stdout, new_stderr, ExecMode::DETACH, 0, SIGKILL /* Not used because the timeout is 0. */); } std::unordered_map<std::string, std::string> which_cache; std::string Which(const std::string &executable_candidate) { auto which_cache_entry = which_cache.find(executable_candidate); if (which_cache_entry != which_cache.cend()) return which_cache[executable_candidate]; std::string executable; const size_t last_slash_pos(executable_candidate.find_last_of('/')); if (last_slash_pos != std::string::npos) { if (not IsExecutableFile(executable_candidate)) return ""; executable = executable_candidate; } if (executable.empty()) { const char * const PATH(::secure_getenv("PATH")); if (PATH == nullptr) return ""; const std::string path_str(PATH); std::vector<std::string> path_compoments; StringUtil::Split(path_str, ':', &path_compoments); for (const auto &path_compoment : path_compoments) { const std::string full_path(path_compoment + "/" + executable_candidate); if (IsExecutableFile(full_path)) { executable = full_path; break; } } } if (executable.empty()) return ""; else { which_cache[executable_candidate] = executable; return executable; } } std::string LocateOrDie(const std::string &executable_candidate) { const std::string path(ExecUtil::Which(executable_candidate)); if (path.empty()) logger->error("in ExecUtil::LocateOrDie: can't find \"" + executable_candidate + "\" in our PATH environment!"); return path; } bool ExecSubcommandAndCaptureStdout(const std::string &command, std::string * const stdout_output) { stdout_output->clear(); FILE * const subcommand_stdout(::popen(command.c_str(), "r")); if (subcommand_stdout == nullptr) return false; int ch; while ((ch = std::getc(subcommand_stdout)) != EOF) *stdout_output += static_cast<char>(ch); const int ret_code(::pclose(subcommand_stdout)); if (ret_code == -1) logger->error("pclose(3) failed: " + std::string(::strerror(errno))); return WEXITSTATUS(ret_code) == 0; } bool ExecSubcommandAndCaptureStdoutAndStderr(const std::string &command, const std::vector<std::string> &args, std::string * const stdout_output, std::string * const stderr_output) { FileUtil::AutoTempFile stdout_temp; FileUtil::AutoTempFile stderr_temp; const int retcode(Exec(command, args, /* new_stdin = */ "", stdout_temp.getFilePath(), stderr_temp.getFilePath())); if (not FileUtil::ReadString(stdout_temp.getFilePath(), stdout_output)) logger->error("failed to read temporary file w/ stdout contents!"); if (not FileUtil::ReadString(stderr_temp.getFilePath(), stderr_output)) logger->error("failed to read temporary file w/ stderr contents!"); return retcode == 0; } bool ShouldScheduleNewProcess() { static const long NO_OF_CORES(::sysconf(_SC_NPROCESSORS_ONLN)); double loadavg; if (unlikely(::getloadavg(&loadavg, 1) == -1)) LOG_ERROR("getloadavg(3) failed!"); return loadavg < NO_OF_CORES - 0.5; } void FindActivePrograms(const std::string &program_name, std::unordered_set<unsigned> * const pids) { pids->clear(); std::string stdout; ExecSubcommandAndCaptureStdout("pgrep " + program_name, &stdout); std::unordered_set<std::string> pids_strings; StringUtil::Split(stdout, '\n', &pids_strings); for (const auto pid : pids_strings) pids->emplace(StringUtil::ToUnsigned(pid)); } std::unordered_set<unsigned> FindActivePrograms(const std::string &program_name) { std::unordered_set<unsigned> pids; FindActivePrograms(program_name, &pids); return pids; } } // namespace ExecUtil <|endoftext|>
<commit_before>/** \brief A MARC-21 filter utility that can remove characters from a set of subfields. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2016 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <unordered_set> #include <cstdio> #include <cstdlib> #include <cstring> #include "DirectoryEntry.h" #include "FileUtil.h" #include "Leader.h" #include "MarcUtil.h" #include "MarcXmlWriter.h" #include "MediaTypeUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" void Usage() { std::cerr << "usage: " << progname << " marc_input marc_output subfield_spec1:subfield_spec2:...:subfield_specN " << " characters_to_delete\n" << " where \"subfieldspec\" must be a MARC tag followed by a single-character\n" << " subfield code and \"characters_to_delete\" is list of characters that will be removed\n" << " from the contents of the specified subfields.\n\n"; std::exit(EXIT_FAILURE); } std::string GetSubfieldCodes(const std::string &tag, const std::vector<std::string> &subfield_specs) { std::string subfield_codes; for (const auto &subfield_spec : subfield_specs) { if (subfield_spec.substr(0, DirectoryEntry::TAG_LENGTH) == tag) subfield_codes += subfield_spec[DirectoryEntry::TAG_LENGTH]; } return subfield_codes; } void Filter(File * const input, File * const output, const std::vector<std::string> &subfield_specs, const std::string &filter_chars) { MarcXmlWriter xml_writer(output); unsigned total_count(0), modified_record_count(0), modified_field_count(0); while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(input)) { ++total_count; record.setRecordWillBeWrittenAsXml(true); const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); const std::vector<std::string> &fields(record.getFields()); for (std::vector<DirectoryEntry>::const_iterator dir_entry(dir_entries.cbegin()); dir_entry != dir_entries.cend(); ++dir_entry) { const std::string subfield_codes(GetSubfieldCodes(dir_entry->getTag(), subfield_specs)); if (subfield_codes.empty()) { record.write(&xml_writer); continue; } bool modified_at_least_one(false); const auto field_index(dir_entry - dir_entries.cbegin()); Subfields subfields(fields[field_index]); for (const auto subfield_code : subfield_codes) { const auto begin_end(subfields.getIterators(subfield_code)); for (auto subfield(begin_end.first); subfield != begin_end.second; ++subfield) { const auto old_length(subfield->second.length()); StringUtil::RemoveChars(filter_chars, &(subfield->second)); if (subfield->second.length() != old_length) { ++modified_field_count; modified_at_least_one = true; } } } if (modified_at_least_one) { record.replaceField(field_index, subfields.toString()); ++modified_record_count; } record.write(&xml_writer); } } std::cerr << "Mofified " << modified_record_count << " (" << modified_field_count << " fields) of " << total_count << " record(s).\n"; } // Sanity check. bool ArePlausibleSubfieldSpecs(const std::vector<std::string> &subfield_specs) { if (subfield_specs.empty()) return false; for (const auto &subfield_spec : subfield_specs) { if (subfield_spec.length() != (DirectoryEntry::TAG_LENGTH + 1)) return false; } return true; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 5) Usage(); std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(argv[1])); std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(argv[2])); std::vector<std::string> subfield_specs; StringUtil::Split(argv[3], ':', &subfield_specs); if (not ArePlausibleSubfieldSpecs(subfield_specs)) Error("bad subfield specifications!"); const std::string filter_chars(argv[4]); if (filter_chars.empty()) Error(""); try { Filter(input.get(), output.get(), subfield_specs, filter_chars); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <commit_msg>Added a missing error message.<commit_after>/** \brief A MARC-21 filter utility that can remove characters from a set of subfields. * \author Dr. Johannes Ruscheinski (johannes.ruscheinski@uni-tuebingen.de) * * \copyright 2016 Universitätsbiblothek Tübingen. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ #include <iostream> #include <memory> #include <unordered_set> #include <cstdio> #include <cstdlib> #include <cstring> #include "DirectoryEntry.h" #include "FileUtil.h" #include "Leader.h" #include "MarcUtil.h" #include "MarcXmlWriter.h" #include "MediaTypeUtil.h" #include "RegexMatcher.h" #include "StringUtil.h" #include "Subfields.h" #include "util.h" void Usage() { std::cerr << "usage: " << progname << " marc_input marc_output subfield_spec1:subfield_spec2:...:subfield_specN " << " characters_to_delete\n" << " where \"subfieldspec\" must be a MARC tag followed by a single-character\n" << " subfield code and \"characters_to_delete\" is list of characters that will be removed\n" << " from the contents of the specified subfields.\n\n"; std::exit(EXIT_FAILURE); } std::string GetSubfieldCodes(const std::string &tag, const std::vector<std::string> &subfield_specs) { std::string subfield_codes; for (const auto &subfield_spec : subfield_specs) { if (subfield_spec.substr(0, DirectoryEntry::TAG_LENGTH) == tag) subfield_codes += subfield_spec[DirectoryEntry::TAG_LENGTH]; } return subfield_codes; } void Filter(File * const input, File * const output, const std::vector<std::string> &subfield_specs, const std::string &filter_chars) { MarcXmlWriter xml_writer(output); unsigned total_count(0), modified_record_count(0), modified_field_count(0); while (MarcUtil::Record record = MarcUtil::Record::XmlFactory(input)) { ++total_count; record.setRecordWillBeWrittenAsXml(true); const std::vector<DirectoryEntry> &dir_entries(record.getDirEntries()); const std::vector<std::string> &fields(record.getFields()); for (std::vector<DirectoryEntry>::const_iterator dir_entry(dir_entries.cbegin()); dir_entry != dir_entries.cend(); ++dir_entry) { const std::string subfield_codes(GetSubfieldCodes(dir_entry->getTag(), subfield_specs)); if (subfield_codes.empty()) { record.write(&xml_writer); continue; } bool modified_at_least_one(false); const auto field_index(dir_entry - dir_entries.cbegin()); Subfields subfields(fields[field_index]); for (const auto subfield_code : subfield_codes) { const auto begin_end(subfields.getIterators(subfield_code)); for (auto subfield(begin_end.first); subfield != begin_end.second; ++subfield) { const auto old_length(subfield->second.length()); StringUtil::RemoveChars(filter_chars, &(subfield->second)); if (subfield->second.length() != old_length) { ++modified_field_count; modified_at_least_one = true; } } } if (modified_at_least_one) { record.replaceField(field_index, subfields.toString()); ++modified_record_count; } record.write(&xml_writer); } } std::cerr << "Mofified " << modified_record_count << " (" << modified_field_count << " fields) of " << total_count << " record(s).\n"; } // Sanity check. bool ArePlausibleSubfieldSpecs(const std::vector<std::string> &subfield_specs) { if (subfield_specs.empty()) return false; for (const auto &subfield_spec : subfield_specs) { if (subfield_spec.length() != (DirectoryEntry::TAG_LENGTH + 1)) return false; } return true; } int main(int argc, char **argv) { ::progname = argv[0]; if (argc != 5) Usage(); std::unique_ptr<File> input(FileUtil::OpenInputFileOrDie(argv[1])); std::unique_ptr<File> output(FileUtil::OpenOutputFileOrDie(argv[2])); std::vector<std::string> subfield_specs; StringUtil::Split(argv[3], ':', &subfield_specs); if (not ArePlausibleSubfieldSpecs(subfield_specs)) Error("bad subfield specifications!"); const std::string filter_chars(argv[4]); if (filter_chars.empty()) Error("missing characters to be filtered!"); try { Filter(input.get(), output.get(), subfield_specs, filter_chars); } catch (const std::exception &x) { Error("caught exception: " + std::string(x.what())); } } <|endoftext|>
<commit_before>/* * Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <memory> #include <vector> #include "src/Check.h" #include "src/CudaUtils.h" #include "src/common.h" #include "nvcomp_common_deps/hlif_shared_types.h" #include "PinnedPtrs.hpp" namespace nvcomp { /****************************************************************************** * CLASSES ******************************************************************** *****************************************************************************/ /** * @brief Config used to aggregate information about the compression of a particular buffer. * * Contains a "PinnedPtrHandle" to an nvcompStatus. After the compression is complete, * the user can check the result status which resides in pinned host memory. */ struct CompressionConfig { private: std::shared_ptr<PinnedPtrPool<nvcompStatus_t>::PinnedPtrHandle> status; public: size_t max_compressed_buffer_size; /** * @brief Construct the config given an nvcompStatus_t memory pool */ CompressionConfig( PinnedPtrPool<nvcompStatus_t>& pool, size_t max_compressed_buffer_size) : status(pool.allocate()), max_compressed_buffer_size(max_compressed_buffer_size) { *get_status() = nvcompSuccess; } /** * @brief Get the raw nvcompStatus_t* */ nvcompStatus_t* get_status() const { return status->get_ptr(); } }; /** * @brief Config used to aggregate information about a particular decompression. * * Contains a "PinnedPtrHandle" to an nvcompStatus. After the decompression is complete, * the user can check the result status which resides in pinned host memory. */ struct DecompressionConfig { private: std::shared_ptr<PinnedPtrPool<nvcompStatus_t>::PinnedPtrHandle> status; public: size_t decomp_data_size; uint32_t num_chunks; /** * @brief Construct the config given an nvcompStatus_t memory pool */ DecompressionConfig(PinnedPtrPool<nvcompStatus_t>& pool) : status(pool.allocate()), decomp_data_size(), num_chunks() { *get_status() = nvcompSuccess; } /** * @brief Get the raw nvcompStatus_t* */ nvcompStatus_t* get_status() const { return status->get_ptr(); } }; /** * @brief Abstract base class that defines the nvCOMP high level interface */ struct nvcompManagerBase { /** * @brief Configure the compression. * * This routine computes the size of the required result buffer. The result config also * contains the nvcompStatus* that allows error checking. Synchronizes the device (cudaMemcpy) * * @param decomp_buffer_size The uncompressed input data size. * \return comp_config Result */ virtual CompressionConfig configure_compression(const size_t decomp_buffer_size) = 0; /** * @brief Perform compression asynchronously. * * @param decomp_buffer The uncompressed input data (GPU accessible). * @param decomp_buffer_size The length of the uncompressed input data. * @param comp_buffer The location to output the compressed data to (GPU accessible). * @param comp_config Resulted from configure_compression given this decomp_buffer_size. * Contains the nvcompStatus* that allows error checking. */ virtual void compress( const uint8_t* decomp_buffer, const size_t decomp_buffer_size, uint8_t* comp_buffer, const CompressionConfig& comp_config) = 0; /** * @brief Configure the decompression. * * Synchronizes the user stream. * * In the base case, this only computes the size of the decompressed buffer from the compressed buffer header. * * @param comp_buffer The compressed input data (GPU accessible). * \return decomp_config Result */ virtual DecompressionConfig configure_decompression(const uint8_t* comp_buffer) = 0; /** * @brief Perform decompression asynchronously. * * @param decomp_buffer The location to output the decompressed data to (GPU accessible). * @param comp_buffer The compressed input data (GPU accessible). * @param decomp_config Resulted from configure_decompression given this decomp_buffer_size. * Contains nvcompStatus* in CPU/GPU-accessible memory to allow error checking. */ virtual void decompress( uint8_t* decomp_buffer, const uint8_t* comp_buffer, const DecompressionConfig& decomp_config) = 0; /** * @brief Allows the user to provide a user-allocated scratch buffer. * * If this routine is not called before compression / decompression is called, the manager * allocates the required scratch buffer. If this is called after the manager has allocated a * scratch buffer, the manager frees the scratch buffer it allocated then switches to use * the new user-provided one. * * @param new_scratch_buffer The location (GPU accessible) to use for comp/decomp scratch space * */ virtual void set_scratch_buffer(uint8_t* new_scratch_buffer) = 0; /** * @brief Computes the size of the required scratch space * * This scratch space size is constant and based on the configuration of the manager and the * maximum occupancy on the device. * * \return The required scratch buffer size */ virtual size_t get_required_scratch_buffer_size() = 0; /** * @brief Computes the compressed output size of a given buffer * * Synchronously copies the size of the compressed buffer to a stack variable for return. * * @param comp_buffer The start pointer of the compressed buffer to assess. * \return Size of the compressed buffer */ virtual size_t get_compressed_output_size(uint8_t* comp_buffer) = 0; virtual ~nvcompManagerBase() = default; }; /** * @brief ManagerBase contains shared functionality amongst the different nvcompManager types * * - Intended that all Managers will inherit from this class directly or indirectly. * * - Contains a CPU/GPU-accessible memory pool for result statuses to avoid repeated * allocations when tasked with multiple compressions / decompressions. * * - Templated on the particular format's FormatSpecHeader so that some operations can be shared here. * This is likely to be inherited by template classes. In this case, * some usage trickery is suggested to get around dependent name lookup issues. * https://en.cppreference.com/w/cpp/language/dependent_name * */ template <typename FormatSpecHeader> struct ManagerBase : nvcompManagerBase { protected: // members CommonHeader* common_header_cpu; cudaStream_t user_stream; uint8_t* scratch_buffer; size_t scratch_buffer_size; int device_id; PinnedPtrPool<nvcompStatus_t> status_pool; bool manager_filled_scratch_buffer; private: // members bool scratch_buffer_filled; protected: // members bool finished_init; public: // API /** * @brief Construct a ManagerBase * * @param user_stream The stream to use for all operations. Optional, defaults to the default stream * @param device_id The default device ID to use for all operations. Optional, defaults to the default device */ ManagerBase(cudaStream_t user_stream = 0, int device_id = 0) : common_header_cpu(), user_stream(user_stream), scratch_buffer(nullptr), scratch_buffer_size(0), device_id(device_id), status_pool(), manager_filled_scratch_buffer(false), scratch_buffer_filled(false), finished_init(false) { CudaUtils::check(cudaHostAlloc(&common_header_cpu, sizeof(CommonHeader), cudaHostAllocDefault)); } size_t get_required_scratch_buffer_size() final override { return scratch_buffer_size; } // Disable copying ManagerBase(const ManagerBase&) = delete; ManagerBase& operator=(const ManagerBase&) = delete; ManagerBase() = delete; size_t get_compressed_output_size(uint8_t* comp_buffer) final override { CommonHeader* common_header = reinterpret_cast<CommonHeader*>(comp_buffer); CudaUtils::check(cudaMemcpy(common_header_cpu, common_header, sizeof(CommonHeader), cudaMemcpyDefault)); return common_header_cpu->comp_data_size + common_header_cpu->comp_data_offset; }; virtual ~ManagerBase() { CudaUtils::check(cudaFreeHost(common_header_cpu)); if (manager_filled_scratch_buffer) { #if CUDART_VERSION >= 11020 CudaUtils::check(cudaFreeAsync(scratch_buffer, user_stream)); #else CudaUtils::check(cudaFree(scratch_buffer)); #endif } } CompressionConfig configure_compression(const size_t decomp_buffer_size) final override { const size_t max_comp_size = calculate_max_compressed_output_size(decomp_buffer_size); return CompressionConfig{status_pool, max_comp_size}; } virtual DecompressionConfig configure_decompression(const uint8_t* comp_buffer) override { const CommonHeader* common_header = reinterpret_cast<const CommonHeader*>(comp_buffer); DecompressionConfig decomp_config{status_pool}; CudaUtils::check(cudaMemcpyAsync(&decomp_config.decomp_data_size, &common_header->decomp_data_size, sizeof(size_t), cudaMemcpyDefault, user_stream)); do_configure_decompression(decomp_config, common_header); return decomp_config; } void set_scratch_buffer(uint8_t* new_scratch_buffer) final override { if (scratch_buffer_filled) { if (manager_filled_scratch_buffer) { #if CUDART_VERSION >= 11020 CudaUtils::check(cudaFreeAsync(scratch_buffer, user_stream)); #else CudaUtils::check(cudaFree(scratch_buffer)); #endif manager_filled_scratch_buffer = false; } } else { scratch_buffer_filled = true; } scratch_buffer = new_scratch_buffer; } virtual void compress( const uint8_t* decomp_buffer, const size_t decomp_buffer_size, uint8_t* comp_buffer, const CompressionConfig& comp_config) { assert(finished_init); if (not scratch_buffer_filled) { #if CUDART_VERSION >= 11020 CudaUtils::check(cudaMallocAsync(&scratch_buffer, scratch_buffer_size, user_stream)); #else CudaUtils::check(cudaMalloc(&scratch_buffer, scratch_buffer_size)); #endif scratch_buffer_filled = true; manager_filled_scratch_buffer = true; } CommonHeader* common_header = reinterpret_cast<CommonHeader*>(comp_buffer); FormatSpecHeader* comp_format_header = reinterpret_cast<FormatSpecHeader*>(common_header + 1); CudaUtils::check(cudaMemcpyAsync(comp_format_header, get_format_header(), sizeof(FormatSpecHeader), cudaMemcpyDefault, user_stream)); CudaUtils::check(cudaMemsetAsync(&common_header->comp_data_size, 0, sizeof(uint64_t), user_stream)); uint8_t* new_comp_buffer = comp_buffer + sizeof(CommonHeader) + sizeof(FormatSpecHeader); do_compress(common_header, decomp_buffer, decomp_buffer_size, new_comp_buffer, comp_config); } virtual void decompress( uint8_t* decomp_buffer, const uint8_t* comp_buffer, const DecompressionConfig& config) { assert(finished_init); const uint8_t* new_comp_buffer = comp_buffer + sizeof(CommonHeader) + sizeof(FormatSpecHeader); do_decompress(decomp_buffer, new_comp_buffer, config); } protected: // helpers virtual void finish_init() { scratch_buffer_size = compute_scratch_buffer_size(); finished_init = true; } private: // helpers /** * @brief Required helper that actually does the compression * * @param common_header header filled in by this routine (GPU accessible) * @param decomp_buffer The uncompressed input data (GPU accessible) * @param decomp_buffer_size The length of the uncompressed input data * @param comp_buffer The location to output the compressed data to (GPU accessible). * @param comp_config Resulted from configure_compression given this decomp_buffer_size. * */ virtual void do_compress( CommonHeader* common_header, const uint8_t* decomp_buffer, const size_t decomp_buffer_size, uint8_t* comp_buffer, const CompressionConfig& comp_config) = 0; /** * @brief Required helper that actually does the decompression * * @param decomp_buffer The location to output the decompressed data to (GPU accessible). * @param comp_buffer The compressed input data (GPU accessible). * @param decomp_config Resulted from configure_decompression given this decomp_buffer_size. */ virtual void do_decompress( uint8_t* decomp_buffer, const uint8_t* comp_buffer, const DecompressionConfig& config) = 0; /** * @brief Optionally does additional decompression configuration */ virtual void do_configure_decompression( DecompressionConfig& decomp_config, const CommonHeader* common_header) = 0; /** * @brief Computes the required scratch buffer size */ virtual size_t compute_scratch_buffer_size() = 0; /** * @brief Computes the maximum compressed output size for a given * uncompressed buffer. */ virtual size_t calculate_max_compressed_output_size(size_t decomp_buffer_size) = 0; /** * @brief Retrieves a CPU-accessible pointer to the FormatSpecHeader */ virtual FormatSpecHeader* get_format_header() = 0; }; } // namespace nvcomp<commit_msg>ManagerBase fixup<commit_after>/* * Copyright (c) 2022, NVIDIA CORPORATION. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of NVIDIA CORPORATION nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #pragma once #include <memory> #include <vector> #include "src/Check.h" #include "src/CudaUtils.h" #include "src/common.h" #include "nvcomp_common_deps/hlif_shared_types.h" #include "PinnedPtrs.hpp" namespace nvcomp { /****************************************************************************** * CLASSES ******************************************************************** *****************************************************************************/ /** * @brief Config used to aggregate information about the compression of a particular buffer. * * Contains a "PinnedPtrHandle" to an nvcompStatus. After the compression is complete, * the user can check the result status which resides in pinned host memory. */ struct CompressionConfig { private: std::shared_ptr<PinnedPtrPool<nvcompStatus_t>::PinnedPtrHandle> status; public: size_t max_compressed_buffer_size; /** * @brief Construct the config given an nvcompStatus_t memory pool */ CompressionConfig( PinnedPtrPool<nvcompStatus_t>& pool, size_t max_compressed_buffer_size) : status(pool.allocate()), max_compressed_buffer_size(max_compressed_buffer_size) { *get_status() = nvcompSuccess; } /** * @brief Get the raw nvcompStatus_t* */ nvcompStatus_t* get_status() const { return status->get_ptr(); } }; /** * @brief Config used to aggregate information about a particular decompression. * * Contains a "PinnedPtrHandle" to an nvcompStatus. After the decompression is complete, * the user can check the result status which resides in pinned host memory. */ struct DecompressionConfig { private: std::shared_ptr<PinnedPtrPool<nvcompStatus_t>::PinnedPtrHandle> status; public: size_t decomp_data_size; uint32_t num_chunks; /** * @brief Construct the config given an nvcompStatus_t memory pool */ DecompressionConfig(PinnedPtrPool<nvcompStatus_t>& pool) : status(pool.allocate()), decomp_data_size(), num_chunks() { *get_status() = nvcompSuccess; } /** * @brief Get the raw nvcompStatus_t* */ nvcompStatus_t* get_status() const { return status->get_ptr(); } }; /** * @brief Abstract base class that defines the nvCOMP high level interface */ struct nvcompManagerBase { /** * @brief Configure the compression. * * This routine computes the size of the required result buffer. The result config also * contains the nvcompStatus* that allows error checking. Synchronizes the device (cudaMemcpy) * * @param decomp_buffer_size The uncompressed input data size. * \return comp_config Result */ virtual CompressionConfig configure_compression(const size_t decomp_buffer_size) = 0; /** * @brief Perform compression asynchronously. * * @param decomp_buffer The uncompressed input data (GPU accessible). * @param decomp_buffer_size The length of the uncompressed input data. * @param comp_buffer The location to output the compressed data to (GPU accessible). * @param comp_config Resulted from configure_compression given this decomp_buffer_size. * Contains the nvcompStatus* that allows error checking. */ virtual void compress( const uint8_t* decomp_buffer, const size_t decomp_buffer_size, uint8_t* comp_buffer, const CompressionConfig& comp_config) = 0; /** * @brief Configure the decompression. * * Synchronizes the user stream. * * In the base case, this only computes the size of the decompressed buffer from the compressed buffer header. * * @param comp_buffer The compressed input data (GPU accessible). * \return decomp_config Result */ virtual DecompressionConfig configure_decompression(const uint8_t* comp_buffer) = 0; /** * @brief Perform decompression asynchronously. * * @param decomp_buffer The location to output the decompressed data to (GPU accessible). * @param comp_buffer The compressed input data (GPU accessible). * @param decomp_config Resulted from configure_decompression given this decomp_buffer_size. * Contains nvcompStatus* in CPU/GPU-accessible memory to allow error checking. */ virtual void decompress( uint8_t* decomp_buffer, const uint8_t* comp_buffer, const DecompressionConfig& decomp_config) = 0; /** * @brief Allows the user to provide a user-allocated scratch buffer. * * If this routine is not called before compression / decompression is called, the manager * allocates the required scratch buffer. If this is called after the manager has allocated a * scratch buffer, the manager frees the scratch buffer it allocated then switches to use * the new user-provided one. * * @param new_scratch_buffer The location (GPU accessible) to use for comp/decomp scratch space * */ virtual void set_scratch_buffer(uint8_t* new_scratch_buffer) = 0; /** * @brief Computes the size of the required scratch space * * This scratch space size is constant and based on the configuration of the manager and the * maximum occupancy on the device. * * \return The required scratch buffer size */ virtual size_t get_required_scratch_buffer_size() = 0; /** * @brief Computes the compressed output size of a given buffer * * Synchronously copies the size of the compressed buffer to a stack variable for return. * * @param comp_buffer The start pointer of the compressed buffer to assess. * \return Size of the compressed buffer */ virtual size_t get_compressed_output_size(uint8_t* comp_buffer) = 0; virtual ~nvcompManagerBase() = default; }; /** * @brief ManagerBase contains shared functionality amongst the different nvcompManager types * * - Intended that all Managers will inherit from this class directly or indirectly. * * - Contains a CPU/GPU-accessible memory pool for result statuses to avoid repeated * allocations when tasked with multiple compressions / decompressions. * * - Templated on the particular format's FormatSpecHeader so that some operations can be shared here. * This is likely to be inherited by template classes. In this case, * some usage trickery is suggested to get around dependent name lookup issues. * https://en.cppreference.com/w/cpp/language/dependent_name * */ template <typename FormatSpecHeader> struct ManagerBase : nvcompManagerBase { protected: // members CommonHeader* common_header_cpu; cudaStream_t user_stream; uint8_t* scratch_buffer; size_t scratch_buffer_size; int device_id; PinnedPtrPool<nvcompStatus_t> status_pool; bool manager_filled_scratch_buffer; private: // members bool scratch_buffer_filled; protected: // members bool finished_init; public: // API /** * @brief Construct a ManagerBase * * @param user_stream The stream to use for all operations. Optional, defaults to the default stream * @param device_id The default device ID to use for all operations. Optional, defaults to the default device */ ManagerBase(cudaStream_t user_stream = 0, int device_id = 0) : common_header_cpu(), user_stream(user_stream), scratch_buffer(nullptr), scratch_buffer_size(0), device_id(device_id), status_pool(), manager_filled_scratch_buffer(false), scratch_buffer_filled(false), finished_init(false) { CudaUtils::check(cudaHostAlloc(&common_header_cpu, sizeof(CommonHeader), cudaHostAllocDefault)); } size_t get_required_scratch_buffer_size() final override { return scratch_buffer_size; } // Disable copying ManagerBase(const ManagerBase&) = delete; ManagerBase& operator=(const ManagerBase&) = delete; ManagerBase() = delete; size_t get_compressed_output_size(uint8_t* comp_buffer) final override { CommonHeader* common_header = reinterpret_cast<CommonHeader*>(comp_buffer); CudaUtils::check(cudaMemcpy(common_header_cpu, common_header, sizeof(CommonHeader), cudaMemcpyDefault)); return common_header_cpu->comp_data_size + common_header_cpu->comp_data_offset; }; virtual ~ManagerBase() { CudaUtils::check(cudaFreeHost(common_header_cpu)); if (scratch_buffer_filled) { if (manager_filled_scratch_buffer) { #if CUDART_VERSION >= 11020 CudaUtils::check(cudaFreeAsync(scratch_buffer, user_stream)); #else CudaUtils::check(cudaFree(scratch_buffer)); #endif } } } CompressionConfig configure_compression(const size_t decomp_buffer_size) final override { const size_t max_comp_size = calculate_max_compressed_output_size(decomp_buffer_size); return CompressionConfig{status_pool, max_comp_size}; } virtual DecompressionConfig configure_decompression(const uint8_t* comp_buffer) override { const CommonHeader* common_header = reinterpret_cast<const CommonHeader*>(comp_buffer); DecompressionConfig decomp_config{status_pool}; CudaUtils::check(cudaMemcpyAsync(&decomp_config.decomp_data_size, &common_header->decomp_data_size, sizeof(size_t), cudaMemcpyDefault, user_stream)); do_configure_decompression(decomp_config, common_header); return decomp_config; } void set_scratch_buffer(uint8_t* new_scratch_buffer) final override { if (scratch_buffer_filled) { if (manager_filled_scratch_buffer) { #if CUDART_VERSION >= 11020 CudaUtils::check(cudaFreeAsync(scratch_buffer, user_stream)); #else CudaUtils::check(cudaFree(scratch_buffer)); #endif manager_filled_scratch_buffer = false; } } else { scratch_buffer_filled = true; } scratch_buffer = new_scratch_buffer; } virtual void compress( const uint8_t* decomp_buffer, const size_t decomp_buffer_size, uint8_t* comp_buffer, const CompressionConfig& comp_config) { assert(finished_init); if (not scratch_buffer_filled) { #if CUDART_VERSION >= 11020 CudaUtils::check(cudaMallocAsync(&scratch_buffer, scratch_buffer_size, user_stream)); #else CudaUtils::check(cudaMalloc(&scratch_buffer, scratch_buffer_size)); #endif scratch_buffer_filled = true; manager_filled_scratch_buffer = true; } CommonHeader* common_header = reinterpret_cast<CommonHeader*>(comp_buffer); FormatSpecHeader* comp_format_header = reinterpret_cast<FormatSpecHeader*>(common_header + 1); CudaUtils::check(cudaMemcpyAsync(comp_format_header, get_format_header(), sizeof(FormatSpecHeader), cudaMemcpyDefault, user_stream)); CudaUtils::check(cudaMemsetAsync(&common_header->comp_data_size, 0, sizeof(uint64_t), user_stream)); uint8_t* new_comp_buffer = comp_buffer + sizeof(CommonHeader) + sizeof(FormatSpecHeader); do_compress(common_header, decomp_buffer, decomp_buffer_size, new_comp_buffer, comp_config); } virtual void decompress( uint8_t* decomp_buffer, const uint8_t* comp_buffer, const DecompressionConfig& config) { assert(finished_init); if (not scratch_buffer_filled) { #if CUDART_VERSION >= 11020 CudaUtils::check(cudaMallocAsync(&scratch_buffer, scratch_buffer_size, user_stream)); #else CudaUtils::check(cudaMalloc(&scratch_buffer, scratch_buffer_size)); #endif scratch_buffer_filled = true; manager_filled_scratch_buffer = true; } const uint8_t* new_comp_buffer = comp_buffer + sizeof(CommonHeader) + sizeof(FormatSpecHeader); do_decompress(decomp_buffer, new_comp_buffer, config); } protected: // helpers virtual void finish_init() { scratch_buffer_size = compute_scratch_buffer_size(); finished_init = true; } private: // helpers /** * @brief Required helper that actually does the compression * * @param common_header header filled in by this routine (GPU accessible) * @param decomp_buffer The uncompressed input data (GPU accessible) * @param decomp_buffer_size The length of the uncompressed input data * @param comp_buffer The location to output the compressed data to (GPU accessible). * @param comp_config Resulted from configure_compression given this decomp_buffer_size. * */ virtual void do_compress( CommonHeader* common_header, const uint8_t* decomp_buffer, const size_t decomp_buffer_size, uint8_t* comp_buffer, const CompressionConfig& comp_config) = 0; /** * @brief Required helper that actually does the decompression * * @param decomp_buffer The location to output the decompressed data to (GPU accessible). * @param comp_buffer The compressed input data (GPU accessible). * @param decomp_config Resulted from configure_decompression given this decomp_buffer_size. */ virtual void do_decompress( uint8_t* decomp_buffer, const uint8_t* comp_buffer, const DecompressionConfig& config) = 0; /** * @brief Optionally does additional decompression configuration */ virtual void do_configure_decompression( DecompressionConfig& decomp_config, const CommonHeader* common_header) = 0; /** * @brief Computes the required scratch buffer size */ virtual size_t compute_scratch_buffer_size() = 0; /** * @brief Computes the maximum compressed output size for a given * uncompressed buffer. */ virtual size_t calculate_max_compressed_output_size(size_t decomp_buffer_size) = 0; /** * @brief Retrieves a CPU-accessible pointer to the FormatSpecHeader */ virtual FormatSpecHeader* get_format_header() = 0; }; } // namespace nvcomp<|endoftext|>
<commit_before>// $Id$ // -*-C++-*- // * BeginRiceCopyright ***************************************************** // // Copyright ((c)) 2002, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // main.C // // Purpose: // [The purpose of this file] // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** //************************* System Include Files **************************** #include <iostream> #include <fstream> #include <new> #include <sys/stat.h> #include <sys/types.h> //*************************** User Include Files **************************** #include "Args.h" //#include "ProfileReader.h" FIXME #include "CSProfileUtils.h" #include <lib/binutils/LoadModule.h> #include <lib/binutils/PCToSrcLineMap.h> #include <lib/binutils/LoadModuleInfo.h> //*************************** Forward Declarations *************************** using std::cerr; //**************************************************************************** #if 0 #define DEB_ON_LINUX 1 #endif int main(int argc, char* argv[]) { Args args(argc, argv); // ------------------------------------------------------------ // Read executable // ------------------------------------------------------------ // Since in the executable is already in the load module // We don't need to include the executable in the command // line option ! ---FMZ #if 0 Executable* exe = NULL; try { exe = new Executable(); if (!exe->Open(args.progFile)) { exit(1); } // Error already printed if (!exe->Read()) { exit(1); } // Error already printed } catch (std::bad_alloc& x) { cerr << "Error: Memory alloc failed while reading binary!\n"; exit(1); } catch (...) { cerr << "Error: Exception encountered while reading binary!\n"; exit(2); } #endif #ifdef XCSPROFILE_DEBUG exe->Dump(); #endif // ------------------------------------------------------------ // Read 'profData', the profiling data file // ------------------------------------------------------------ CSProfile* profData = NULL; try { //profData = TheProfileReader.ReadProfileFile(args.profFile /*filetype*/); // we need to know the name of the executable profData = ReadCSProfileFile_HCSPROFILE(args.profFile,args.progFile); if (!profData) { exit(1); } } catch (std::bad_alloc& x) { cerr << "Error: Memory alloc failed while reading profile!\n"; exit(1); } catch (...) { cerr << "Error: Exception encountered while reading profile!\n"; exit(2); } // After checking we have samples in the profile, create the database directory args.createDatabaseDirectory(); // ------------------------------------------------------------ // Read 'PCToSrcLineXMap', if available // ------------------------------------------------------------ PCToSrcLineXMap* map = NULL; // cf. xprof, main.C: During program structure recovery it is // possible to output source line info supplemented with, e.g., loop // nesting info. While this is not yet fully supported, we may want // to use something similar in the future. // ------------------------------------------------------------ // Add source file info and dump // ------------------------------------------------------------ try { // for each "used" load module, go through the call stack tree // to find the source line infornmation // for efficiency, we add a flag in CSProfLDmodule "used" // add one more pass search the callstack tree, to set // the flag -"alpha"- only, since we get info from binary // profile file not from bfd LdmdSetUsedFlag(profData); int numberofldmd =profData->GetEpoch()->GetNumLdModule() ; LoadModule* ldmd = NULL; CSProfLDmodule * csploadmd= NULL; LoadModuleInfo * modInfo; Addr startaddr; Addr endaddr = 0; bool lastone ; for (int i=numberofldmd-1; i>=0; i--) { if (i==numberofldmd-1) lastone = true; else lastone = false; csploadmd = profData->GetEpoch()->GetLdModule(i); startaddr = csploadmd->GetMapaddr(); // for next csploadmodule if (!(csploadmd->GetUsedFlag())) //ignore unused loadmodule continue; try { ldmd = new LoadModule(); if (!ldmd ->Open(csploadmd->GetName())) //Error message already printed continue; if (!ldmd->Read()) //Error message already printed continue; } catch (std::bad_alloc& x) { cerr << "Error: Memory alloc failed while reading binary!\n"; exit(1); } catch (...) { cerr << "Error: Exception encountered while reading binary!\n"; exit(2); } // get the start and end PC from the text sections Addr tmp1,tmp2; cout << "*****Current load module is : " << csploadmd->GetName()<<"*****"<< endl; ldmd->GetTextStartEndPC(&tmp1,&tmp2); ldmd->SetTextStart(tmp1); ldmd->SetTextEnd(tmp2); #if 0 cout<< "\t LoadModule text started from address : "<< hex <<"0x" << tmp1 << endl; cout<< "\t LoadModule text end at the address : "<< hex <<"0x" << tmp2 << endl; cout<< "\t LoadModule entry point is: "<< hex << "0x" << ldmd->GetTextStart() << endl; cout<< "\t data file mapaddress from address : "<< hex <<"0x" << startaddr << endl; cout<< "\t data file mapaddress supposed end : "<< hex <<"0x" << endaddr <<dec<< endl; // if ldmd is not an excutable, do relocate #endif if ( !(ldmd->GetType() == LoadModule::Executable) ) { ldmd->Relocate(startaddr); } modInfo = new LoadModuleInfo(ldmd, map); AddSourceFileInfoToCSProfile(profData, modInfo,startaddr,endaddr,lastone); // create an extended profile representation // normalize call sites // // main main // / \ =====> | // / \ foo:<start line foo> // foo:1 foo:2 / \ // / \ // foo:1 foo:2 // NormalizeInternalCallSites(profData, modInfo,startaddr, endaddr,lastone); endaddr = startaddr-1; // close current load module and free memory space delete(modInfo->GetLM()); modInfo = NULL; } /* for each load module */ NormalizeCSProfile(profData); // prepare output directory /* FIXME: if (db exists) { create other one, dbname+randomNumber until new name found create xml file (name csprof.xml) create src dir } */ String dbSourceDirectory = args.databaseDirectory+"/src"; if (mkdir(dbSourceDirectory, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == -1) { cerr << "could not create database source code directory " << dbSourceDirectory << endl; exit (1); } copySourceFiles (profData, args.searchPaths, dbSourceDirectory); WriteCSProfileInDatabase (profData, args.databaseDirectory); //WriteCSProfile(profData, std::cout, /* prettyPrint */ true); } catch (...) { // FIXME cerr << "Error: Exception encountered while preparing CSPROFILE!\n"; exit(2); } #if 0 /* already deleted */ delete exe; delete map; #endif delete profData; return (0); } //**************************************************************************** <commit_msg> alpha version use "textStart" address relocate PC.<commit_after>// $Id$ // -*-C++-*- // * BeginRiceCopyright ***************************************************** // // Copyright ((c)) 2002, Rice University // 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 Rice University (RICE) 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 RICE 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 RICE 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. // // ******************************************************* EndRiceCopyright * //*************************************************************************** // // File: // main.C // // Purpose: // [The purpose of this file] // // Description: // [The set of functions, macros, etc. defined in the file] // //*************************************************************************** //************************* System Include Files **************************** #include <iostream> #include <fstream> #include <new> #include <sys/stat.h> #include <sys/types.h> //*************************** User Include Files **************************** #include "Args.h" //#include "ProfileReader.h" FIXME #include "CSProfileUtils.h" #include <lib/binutils/LoadModule.h> #include <lib/binutils/PCToSrcLineMap.h> #include <lib/binutils/LoadModuleInfo.h> //*************************** Forward Declarations *************************** using std::cerr; //**************************************************************************** #if 0 #define DEB_ON_LINUX 1 #endif int main(int argc, char* argv[]) { Args args(argc, argv); // ------------------------------------------------------------ // Read executable // ------------------------------------------------------------ // Since in the executable is already in the load module // We don't need to include the executable in the command // line option ! ---FMZ #if 0 Executable* exe = NULL; try { exe = new Executable(); if (!exe->Open(args.progFile)) { exit(1); } // Error already printed if (!exe->Read()) { exit(1); } // Error already printed } catch (std::bad_alloc& x) { cerr << "Error: Memory alloc failed while reading binary!\n"; exit(1); } catch (...) { cerr << "Error: Exception encountered while reading binary!\n"; exit(2); } #endif #ifdef XCSPROFILE_DEBUG exe->Dump(); #endif // ------------------------------------------------------------ // Read 'profData', the profiling data file // ------------------------------------------------------------ CSProfile* profData = NULL; try { //profData = TheProfileReader.ReadProfileFile(args.profFile /*filetype*/); // we need to know the name of the executable profData = ReadCSProfileFile_HCSPROFILE(args.profFile,args.progFile); if (!profData) { exit(1); } } catch (std::bad_alloc& x) { cerr << "Error: Memory alloc failed while reading profile!\n"; exit(1); } catch (...) { cerr << "Error: Exception encountered while reading profile!\n"; exit(2); } // After checking we have samples in the profile, create the database directory args.createDatabaseDirectory(); // ------------------------------------------------------------ // Read 'PCToSrcLineXMap', if available // ------------------------------------------------------------ PCToSrcLineXMap* map = NULL; // cf. xprof, main.C: During program structure recovery it is // possible to output source line info supplemented with, e.g., loop // nesting info. While this is not yet fully supported, we may want // to use something similar in the future. // ------------------------------------------------------------ // Add source file info and dump // ------------------------------------------------------------ try { // for each "used" load module, go through the call stack tree // to find the source line infornmation // for efficiency, we add a flag in CSProfLDmodule "used" // add one more pass search the callstack tree, to set // the flag -"alpha"- only, since we get info from binary // profile file not from bfd LdmdSetUsedFlag(profData); int numberofldmd =profData->GetEpoch()->GetNumLdModule() ; LoadModule* ldmd = NULL; CSProfLDmodule * csploadmd= NULL; LoadModuleInfo * modInfo; Addr startaddr; Addr endaddr = 0; bool lastone ; for (int i=numberofldmd-1; i>=0; i--) { if (i==numberofldmd-1) lastone = true; else lastone = false; csploadmd = profData->GetEpoch()->GetLdModule(i); startaddr = csploadmd->GetMapaddr(); // for next csploadmodule if (!(csploadmd->GetUsedFlag())){ //ignore unused loadmodule endaddr = startaddr-1; continue; } try { ldmd = new LoadModule(); if (!ldmd ->Open(csploadmd->GetName())) //Error message already printed continue; if (!ldmd->Read()) //Error message already printed continue; } catch (std::bad_alloc& x) { cerr << "Error: Memory alloc failed while reading binary!\n"; exit(1); } catch (...) { cerr << "Error: Exception encountered while reading binary!\n"; exit(2); } // get the start and end PC from the text sections cout << "*****Current load module is : " << csploadmd->GetName()<<"*****"<< endl; #if 0 Addr tmp1,tmp2; ldmd->GetTextStartEndPC(&tmp1,&tmp2); ldmd->SetTextStart(tmp1); ldmd->SetTextEnd(tmp2); cout<< "\t LoadModule text started from address : "<< hex <<"0x" << tmp1 << endl; cout<< "\t LoadModule text end at the address : "<< hex <<"0x" << tmp2 << endl; cout<< "\t LoadModule entry point is: "<< hex << "0x" << ldmd->GetTextStart() << endl; cout<< "\t data file mapaddress from address : "<< hex <<"0x" << startaddr << endl; cout<< "\t data file mapaddress supposed end : "<< hex <<"0x" << endaddr <<dec<< endl; // if ldmd is not an excutable, do relocate #endif if ( !(ldmd->GetType() == LoadModule::Executable) ) { ldmd->Relocate(startaddr); } modInfo = new LoadModuleInfo(ldmd, map); AddSourceFileInfoToCSProfile(profData, modInfo,startaddr,endaddr,lastone); // create an extended profile representation // normalize call sites // // main main // / \ =====> | // / \ foo:<start line foo> // foo:1 foo:2 / \ // / \ // foo:1 foo:2 // NormalizeInternalCallSites(profData, modInfo,startaddr, endaddr,lastone); endaddr = startaddr-1; // close current load module and free memory space delete(modInfo->GetLM()); modInfo = NULL; } /* for each load module */ NormalizeCSProfile(profData); // prepare output directory /* FIXME: if (db exists) { create other one, dbname+randomNumber until new name found create xml file (name csprof.xml) create src dir } */ String dbSourceDirectory = args.databaseDirectory+"/src"; if (mkdir(dbSourceDirectory, S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH) == -1) { cerr << "could not create database source code directory " << dbSourceDirectory << endl; exit (1); } copySourceFiles (profData, args.searchPaths, dbSourceDirectory); WriteCSProfileInDatabase (profData, args.databaseDirectory); //WriteCSProfile(profData, std::cout, /* prettyPrint */ true); } catch (...) { // FIXME cerr << "Error: Exception encountered while preparing CSPROFILE!\n"; exit(2); } #if 0 /* already deleted */ delete exe; delete map; #endif delete profData; return (0); } //**************************************************************************** <|endoftext|>
<commit_before>#include "phAttrib.h" #include "gmi_sim.h" #include <SimAttribute.h> #include <SimUtil.h> #include <cstdlib> /* Simmetrix, for the love of all that is good, please put this in your header files. We can't work with files from Simmodeler without it. */ pAManager SModel_attManager(pModel model); typedef ph::BC* (*BCFactory)(pAttribute a, pGEntity ge); typedef std::map<std::string, BCFactory> BCFactories; struct SimBC : public ph::BC { SimBC(pGEntity ge) { dim = GEN_type(ge); tag = GEN_tag(ge); } }; struct Tensor0BC : public SimBC { Tensor0BC(pAttribute a, pGEntity ge):SimBC(ge) { if (Attribute_repType(a) != Att_tensor0) { fprintf(stderr, "tensor 0 attribute does not match type\n"); abort(); } attribute = (pAttributeTensor0)a; } virtual double* eval(apf::Vector3 const& x) { buf = AttributeTensor0_evalDS(attribute, &x[0]); return &buf; } pAttributeTensor0 attribute; double buf; }; struct Tensor1BC : public SimBC { Tensor1BC(pAttribute a, pGEntity ge):SimBC(ge) { if (Attribute_repType(a) != Att_tensor1) { fprintf(stderr, "tensor 1 attribute does not match type\n"); abort(); } attribute = (pAttributeTensor1)a; } virtual double* eval(apf::Vector3 const& x) { for (int i = 0; i < 3; ++i) buf[i] = AttributeTensor1_evalDS(attribute, i, &x[0]); return buf; } pAttributeTensor1 attribute; double buf[3]; }; struct CompBC : public SimBC { CompBC(pAttribute a, pGEntity ge):SimBC(ge) { if (Attribute_repType(a) != Att_void) { fprintf(stderr, "comp1/3 attribute does not match type\n"); abort(); } pPList children = Attribute_children(a); magnitude = 0; direction = 0; for (int i = 0; i < PList_size(children); ++i) { pAttribute child = (pAttribute) PList_item(children, i); if (Attribute_repType(child) == Att_double) magnitude = (pAttributeDouble) child; else if (Attribute_repType(child) == Att_tensor1) direction = (pAttributeTensor1) child; } PList_delete(children); if (!magnitude) { fprintf(stderr, "comp1/3 attribute does not have magnitude\n"); abort(); } if (!direction) { fprintf(stderr, "comp1/3 attribute does not have direction\n"); abort(); } } virtual double* eval(apf::Vector3 const& x) { buf[0] = AttributeDouble_evalDS(magnitude, &x[0]); for (int i = 0; i < 3; ++i) buf[i + 1] = AttributeTensor1_evalDS(direction, i, &x[0]); return buf; } pAttributeDouble magnitude; pAttributeTensor1 direction; double buf[4]; }; struct IntBC : public SimBC { IntBC(pAttribute a, pGEntity ge):SimBC(ge) { if (Attribute_repType(a) != Att_int) { fprintf(stderr, "int attribute does not match type\n"); abort(); } attribute = (pAttributeInt)a; } virtual double* eval(apf::Vector3 const&) { /* forgive me for I am storing an int in a double. let there be more than 32 mantissa bits such that this conversion is lossless. */ buf = AttributeInt_value(attribute); return &buf; } pAttributeInt attribute; double buf; }; static ph::BC* tensor0Factory(pAttribute a, pGEntity ge) { return new Tensor0BC(a, ge); } static ph::BC* tensor1Factory(pAttribute a, pGEntity ge) { return new Tensor1BC(a, ge); } static ph::BC* compFactory(pAttribute a, pGEntity ge) { return new CompBC(a, ge); } static ph::BC* intFactory(pAttribute a, pGEntity ge) { return new IntBC(a, ge); } /* this should follow the KnownBC tables in phBC.cc */ static void formFactories(BCFactories& fs) { fs["density"] = tensor0Factory; fs["temperature"] = tensor0Factory; fs["pressure"] = tensor0Factory; fs["comp1"] = compFactory; fs["comp3"] = compFactory; fs["scalar_1"] = tensor0Factory; fs["scalar_2"] = tensor0Factory; fs["scalar_3"] = tensor0Factory; fs["scalar_4"] = tensor0Factory; fs["mass flux"] = tensor0Factory; fs["natural pressure"] = tensor0Factory; fs["traction vector"] = tensor1Factory; fs["heat flux"] = tensor0Factory; fs["turbulence wall"] = tensor0Factory; fs["scalar_1 flux"] = tensor0Factory; fs["scalar_2 flux"] = tensor0Factory; fs["scalar_3 flux"] = tensor0Factory; fs["scalar_4 flux"] = tensor0Factory; fs["surf ID"] = tensor0Factory; fs["initial pressure"] = tensor0Factory; fs["initial velocity"] = tensor1Factory; fs["initial temperature"] = tensor0Factory; fs["initial scalar_1"] = tensor0Factory; fs["initial scalar_2"] = tensor0Factory; fs["initial scalar_3"] = tensor0Factory; fs["initial scalar_4"] = tensor0Factory; fs["periodic slave"] = intFactory; fs["DG interface"] = intFactory; fs["material type"] = intFactory; } static void addAttribute(BCFactories& fs, pAttribute a, pGEntity ge, ph::BCs& bcs) { char* c_infoType = Attribute_infoType(a); std::string infoType(c_infoType); if (!fs.count(infoType)) { fprintf(stderr,"unknown attribute type \"%s\", ignoring !\n", c_infoType); fprintf(stderr,"it had repType %d\n", Attribute_repType(a)); return; } if (!bcs.fields.count(infoType)) bcs.fields[infoType] = ph::FieldBCs(); ph::FieldBCs& fbcs = bcs.fields[infoType]; Sim_deleteString(c_infoType); BCFactory f = fs[infoType]; fbcs.bcs.insert( f(a, ge) ); } static void addAttributes(BCFactories& fs, pPList as, pGEntity ge, ph::BCs& bcs) { for (int i = 0; i < PList_size(as); ++i) { pAttribute a = (pAttribute) PList_item(as, i); addAttribute(fs, a, ge, bcs); } } namespace { void getSimModelAndCase(gmi_model* m, pGModel& smdl, pACase& pd) { smdl = gmi_export_sim(m); pAManager mngr = SModel_attManager(smdl); if (!mngr) { fprintf(stderr,"Simmetrix model did not come with an Attribute Manager\n"); abort(); } pd = AMAN_findCaseByType(mngr, "problem definition"); if (!pd) { fprintf(stderr,"no Attribute Case \"problem definition\"\n"); abort(); } } } void ph::clearAttAssociation(gmi_model* mdl, ph::Input& in) { const char* attFile = in.attributeFileName.c_str(); if (gmi_has_ext(attFile, "spj")) return; pGModel smdl = NULL; pACase pd = NULL; getSimModelAndCase(mdl,smdl,pd); AttCase_unassociate(pd); } void ph::getSimmetrixAttributes(gmi_model* model, ph::BCs& bcs) { pGModel smdl = NULL; pACase pd = NULL; getSimModelAndCase(model,smdl,pd); AttCase_setModel(pd, smdl); AttCase_associate(pd, NULL); BCFactories fs; formFactories(fs); for (int dim = 0; dim < 4; ++dim) { gmi_iter* it = gmi_begin(model, dim); gmi_ent* e; while ((e = gmi_next(model, it))) { pGEntity ge = (pGEntity) e; pPList attribs = GEN_attributes(ge, ""); addAttributes(fs, attribs, ge, bcs); } gmi_end(model, it); } /* Simmodeler seems to put ICs on the model itself, not the regions. spread all ICs off the model onto the regions. also, this code does assume the domain is 3D. */ pPList attribs = GM_attributes(smdl, ""); GRIter rit = GM_regionIter(smdl); pGRegion gr; while ((gr = GRIter_next(rit))) addAttributes(fs, attribs, gr, bcs); GRIter_delete(rit); } <commit_msg>Chef accepts imageClass, if any, over infoType<commit_after>#include "phAttrib.h" #include "gmi_sim.h" #include <SimAttribute.h> #include <SimUtil.h> #include <cstdlib> /* Simmetrix, for the love of all that is good, please put this in your header files. We can't work with files from Simmodeler without it. */ pAManager SModel_attManager(pModel model); typedef ph::BC* (*BCFactory)(pAttribute a, pGEntity ge); typedef std::map<std::string, BCFactory> BCFactories; struct SimBC : public ph::BC { SimBC(pGEntity ge) { dim = GEN_type(ge); tag = GEN_tag(ge); } }; struct Tensor0BC : public SimBC { Tensor0BC(pAttribute a, pGEntity ge):SimBC(ge) { if (Attribute_repType(a) != Att_tensor0) { fprintf(stderr, "tensor 0 attribute does not match type\n"); abort(); } attribute = (pAttributeTensor0)a; } virtual double* eval(apf::Vector3 const& x) { buf = AttributeTensor0_evalDS(attribute, &x[0]); return &buf; } pAttributeTensor0 attribute; double buf; }; struct Tensor1BC : public SimBC { Tensor1BC(pAttribute a, pGEntity ge):SimBC(ge) { if (Attribute_repType(a) != Att_tensor1) { fprintf(stderr, "tensor 1 attribute does not match type\n"); abort(); } attribute = (pAttributeTensor1)a; } virtual double* eval(apf::Vector3 const& x) { for (int i = 0; i < 3; ++i) buf[i] = AttributeTensor1_evalDS(attribute, i, &x[0]); return buf; } pAttributeTensor1 attribute; double buf[3]; }; struct CompBC : public SimBC { CompBC(pAttribute a, pGEntity ge):SimBC(ge) { if (Attribute_repType(a) != Att_void) { fprintf(stderr, "comp1/3 attribute does not match type\n"); abort(); } pPList children = Attribute_children(a); magnitude = 0; direction = 0; for (int i = 0; i < PList_size(children); ++i) { pAttribute child = (pAttribute) PList_item(children, i); if (Attribute_repType(child) == Att_double) magnitude = (pAttributeDouble) child; else if (Attribute_repType(child) == Att_tensor1) direction = (pAttributeTensor1) child; } PList_delete(children); if (!magnitude) { fprintf(stderr, "comp1/3 attribute does not have magnitude\n"); abort(); } if (!direction) { fprintf(stderr, "comp1/3 attribute does not have direction\n"); abort(); } } virtual double* eval(apf::Vector3 const& x) { buf[0] = AttributeDouble_evalDS(magnitude, &x[0]); for (int i = 0; i < 3; ++i) buf[i + 1] = AttributeTensor1_evalDS(direction, i, &x[0]); return buf; } pAttributeDouble magnitude; pAttributeTensor1 direction; double buf[4]; }; struct IntBC : public SimBC { IntBC(pAttribute a, pGEntity ge):SimBC(ge) { if (Attribute_repType(a) != Att_int) { fprintf(stderr, "int attribute does not match type\n"); abort(); } attribute = (pAttributeInt)a; } virtual double* eval(apf::Vector3 const&) { /* forgive me for I am storing an int in a double. let there be more than 32 mantissa bits such that this conversion is lossless. */ buf = AttributeInt_value(attribute); return &buf; } pAttributeInt attribute; double buf; }; static ph::BC* tensor0Factory(pAttribute a, pGEntity ge) { return new Tensor0BC(a, ge); } static ph::BC* tensor1Factory(pAttribute a, pGEntity ge) { return new Tensor1BC(a, ge); } static ph::BC* compFactory(pAttribute a, pGEntity ge) { return new CompBC(a, ge); } static ph::BC* intFactory(pAttribute a, pGEntity ge) { return new IntBC(a, ge); } /* this should follow the KnownBC tables in phBC.cc */ static void formFactories(BCFactories& fs) { fs["density"] = tensor0Factory; fs["temperature"] = tensor0Factory; fs["pressure"] = tensor0Factory; fs["comp1"] = compFactory; fs["comp3"] = compFactory; fs["scalar_1"] = tensor0Factory; fs["scalar_2"] = tensor0Factory; fs["scalar_3"] = tensor0Factory; fs["scalar_4"] = tensor0Factory; fs["mass flux"] = tensor0Factory; fs["natural pressure"] = tensor0Factory; fs["traction vector"] = tensor1Factory; fs["heat flux"] = tensor0Factory; fs["turbulence wall"] = tensor0Factory; fs["scalar_1 flux"] = tensor0Factory; fs["scalar_2 flux"] = tensor0Factory; fs["scalar_3 flux"] = tensor0Factory; fs["scalar_4 flux"] = tensor0Factory; fs["surf ID"] = tensor0Factory; fs["initial pressure"] = tensor0Factory; fs["initial velocity"] = tensor1Factory; fs["initial temperature"] = tensor0Factory; fs["initial scalar_1"] = tensor0Factory; fs["initial scalar_2"] = tensor0Factory; fs["initial scalar_3"] = tensor0Factory; fs["initial scalar_4"] = tensor0Factory; fs["periodic slave"] = intFactory; fs["DG interface"] = intFactory; fs["material type"] = intFactory; } static std::string getType(pAttribute a) { char* c_infoType = Attribute_infoType(a); std::string infoType(c_infoType); Sim_deleteString(c_infoType); char* c_imageClass = Attribute_infoType(a); std::string imageClass(c_imageClass); Sim_deleteString(c_imageClass); if (imageClass.length() != 0) return imageClass; return infoType; } static void addAttribute(BCFactories& fs, pAttribute a, pGEntity ge, ph::BCs& bcs) { std::string type = getType(a); if (!fs.count(type)) { fprintf(stderr,"unknown attribute type \"%s\", ignoring !\n", type.c_str()); fprintf(stderr,"it had repType %d\n", Attribute_repType(a)); return; } if (!bcs.fields.count(type)) bcs.fields[type] = ph::FieldBCs(); ph::FieldBCs& fbcs = bcs.fields[type]; BCFactory f = fs[type]; fbcs.bcs.insert( f(a, ge) ); } static void addAttributes(BCFactories& fs, pPList as, pGEntity ge, ph::BCs& bcs) { for (int i = 0; i < PList_size(as); ++i) { pAttribute a = (pAttribute) PList_item(as, i); addAttribute(fs, a, ge, bcs); } } namespace { void getSimModelAndCase(gmi_model* m, pGModel& smdl, pACase& pd) { smdl = gmi_export_sim(m); pAManager mngr = SModel_attManager(smdl); if (!mngr) { fprintf(stderr,"Simmetrix model did not come with an Attribute Manager\n"); abort(); } pd = AMAN_findCaseByType(mngr, "problem definition"); if (!pd) { fprintf(stderr,"no Attribute Case \"problem definition\"\n"); abort(); } } } void ph::clearAttAssociation(gmi_model* mdl, ph::Input& in) { const char* attFile = in.attributeFileName.c_str(); if (gmi_has_ext(attFile, "spj")) return; pGModel smdl = NULL; pACase pd = NULL; getSimModelAndCase(mdl,smdl,pd); AttCase_unassociate(pd); } void ph::getSimmetrixAttributes(gmi_model* model, ph::BCs& bcs) { pGModel smdl = NULL; pACase pd = NULL; getSimModelAndCase(model,smdl,pd); AttCase_setModel(pd, smdl); AttCase_associate(pd, NULL); BCFactories fs; formFactories(fs); for (int dim = 0; dim < 4; ++dim) { gmi_iter* it = gmi_begin(model, dim); gmi_ent* e; while ((e = gmi_next(model, it))) { pGEntity ge = (pGEntity) e; pPList attribs = GEN_attributes(ge, ""); addAttributes(fs, attribs, ge, bcs); } gmi_end(model, it); } /* Simmodeler seems to put ICs on the model itself, not the regions. spread all ICs off the model onto the regions. also, this code does assume the domain is 3D. */ pPList attribs = GM_attributes(smdl, ""); GRIter rit = GM_regionIter(smdl); pGRegion gr; while ((gr = GRIter_next(rit))) addAttributes(fs, attribs, gr, bcs); GRIter_delete(rit); } <|endoftext|>
<commit_before>/* This file is part of the KDE project Copyright (C) 2004-2007 Matthias Kretz <kretz@kde.org> 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) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Trolltech ASA (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. 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, see <http://www.gnu.org/licenses/>. */ #include "factory_p.h" #include "backendinterface.h" #include "medianode_p.h" #include "mediaobject.h" #include "audiooutput.h" #include "globalstatic_p.h" #include "objectdescription.h" #include "platformplugin.h" #include "phononnamespace_p.h" #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QList> #include <QtCore/QPluginLoader> #include <QtCore/QPointer> #ifndef QT_NO_DBUS #include <QtDBus/QtDBus> #endif QT_BEGIN_NAMESPACE namespace Phonon { class PlatformPlugin; class FactoryPrivate : public Phonon::Factory::Sender { friend QObject *Factory::backend(bool); Q_OBJECT public: FactoryPrivate(); ~FactoryPrivate(); bool createBackend(); #ifndef QT_NO_PHONON_PLATFORMPLUGIN PlatformPlugin *platformPlugin(); PlatformPlugin *m_platformPlugin; bool m_noPlatformPlugin; #endif //QT_NO_PHONON_PLATFORMPLUGIN QPointer<QObject> m_backendObject; QList<QObject *> objects; QList<MediaNodePrivate *> mediaNodePrivateList; private Q_SLOTS: /** * This is called via DBUS when the user changes the Phonon Backend. */ #ifndef QT_NO_DBUS void phononBackendChanged(); #endif //QT_NO_DBUS /** * unregisters the backend object */ void objectDestroyed(QObject *); void objectDescriptionChanged(ObjectDescriptionType); }; PHONON_GLOBAL_STATIC(Phonon::FactoryPrivate, globalFactory) static inline void ensureLibraryPathSet() { #ifdef PHONON_LIBRARY_PATH static bool done = false; if (!done) { done = true; QCoreApplication::addLibraryPath(QLatin1String(PHONON_LIBRARY_PATH)); } #endif // PHONON_LIBRARY_PATH } void Factory::setBackend(QObject *b) { Q_ASSERT(globalFactory->m_backendObject == 0); globalFactory->m_backendObject = b; } /*void Factory::createBackend(const QString &library, const QString &version) { Q_ASSERT(globalFactory->m_backendObject == 0); PlatformPlugin *f = globalFactory->platformPlugin(); if (f) { globalFactory->m_backendObject = f->createBackend(library, version); } }*/ bool FactoryPrivate::createBackend() { Q_ASSERT(m_backendObject == 0); #ifndef QT_NO_PHONON_PLATFORMPLUGIN PlatformPlugin *f = globalFactory->platformPlugin(); if (f) { m_backendObject = f->createBackend(); } #endif //QT_NO_PHONON_PLATFORMPLUGIN if (!m_backendObject) { ensureLibraryPathSet(); // could not load a backend through the platform plugin. Falling back to the default // (finding the first loadable backend). const QLatin1String suffix("/phonon_backend/"); foreach (QString libPath, QCoreApplication::libraryPaths()) { libPath += suffix; const QDir dir(libPath); if (!dir.exists()) { pDebug() << Q_FUNC_INFO << dir.absolutePath() << "does not exist"; continue; } foreach (const QString &pluginName, dir.entryList(QDir::Files)) { QPluginLoader pluginLoader(libPath + pluginName); if (!pluginLoader.load()) { pDebug() << Q_FUNC_INFO << " load failed:" << pluginLoader.errorString(); continue; } pDebug() << pluginLoader.instance(); m_backendObject = pluginLoader.instance(); if (m_backendObject) { break; } // no backend found, don't leave an unused plugin in memory pluginLoader.unload(); } if (m_backendObject) { break; } } if (!m_backendObject) { pWarning() << Q_FUNC_INFO << "phonon backend plugin could not be loaded"; return false; } } connect(m_backendObject, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SLOT(objectDescriptionChanged(ObjectDescriptionType))); return true; } FactoryPrivate::FactoryPrivate() #ifndef QT_NO_PHONON_PLATFORMPLUGIN : m_platformPlugin(0), m_noPlatformPlugin(false) #endif //QT_NO_PHONON_PLATFORMPLUGIN , m_backendObject(0) { // Add the post routine to make sure that all other global statics (especially the ones from Qt) // are still available. If the FactoryPrivate dtor is called too late many bad things can happen // as the whole backend might still be alive. qAddPostRoutine(globalFactory.destroy); #ifndef QT_NO_DBUS QDBusConnection::sessionBus().connect(QString(), QString(), "org.kde.Phonon.Factory", "phononBackendChanged", this, SLOT(phononBackendChanged())); #endif } FactoryPrivate::~FactoryPrivate() { foreach (QObject *o, objects) { MediaObject *m = qobject_cast<MediaObject *>(o); if (m) { m->stop(); } } foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->deleteBackendObject(); } if (objects.size() > 0) { pError() << "The backend objects are not deleted as was requested."; qDeleteAll(objects); } delete m_backendObject; #ifndef QT_NO_PHONON_PLATFORMPLUGIN delete m_platformPlugin; #endif //QT_NO_PHONON_PLATFORMPLUGIN } void FactoryPrivate::objectDescriptionChanged(ObjectDescriptionType type) { #ifdef PHONON_METHODTEST Q_UNUSED(type); #else pDebug() << Q_FUNC_INFO << type; switch (type) { case AudioOutputDeviceType: emit availableAudioOutputDevicesChanged(); break; case AudioCaptureDeviceType: emit availableAudioCaptureDevicesChanged(); break; default: break; } //emit capabilitiesChanged(); #endif // PHONON_METHODTEST } Factory::Sender *Factory::sender() { return globalFactory; } bool Factory::isMimeTypeAvailable(const QString &mimeType) { #ifndef QT_NO_PHONON_PLATFORMPLUGIN PlatformPlugin *f = globalFactory->platformPlugin(); if (f) { return f->isMimeTypeAvailable(mimeType); } #else Q_UNUSED(mimeType); #endif //QT_NO_PHONON_PLATFORMPLUGIN return true; // the MIME type might be supported, let BackendCapabilities find out } void Factory::registerFrontendObject(MediaNodePrivate *bp) { globalFactory->mediaNodePrivateList.prepend(bp); // inserted last => deleted first } void Factory::deregisterFrontendObject(MediaNodePrivate *bp) { // The Factory can already be cleaned up while there are other frontend objects still alive. // When those are deleted they'll call deregisterFrontendObject through ~BasePrivate if (!globalFactory.isDestroyed()) { globalFactory->mediaNodePrivateList.removeAll(bp); } } #ifndef QT_NO_DBUS void FactoryPrivate::phononBackendChanged() { if (m_backendObject) { foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->deleteBackendObject(); } if (objects.size() > 0) { pDebug() << "WARNING: we were asked to change the backend but the application did\n" "not free all references to objects created by the factory. Therefore we can not\n" "change the backend without crashing. Now we have to wait for a restart to make\n" "backendswitching possible."; // in case there were objects deleted give 'em a chance to recreate // them now foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->createBackendObject(); } return; } delete m_backendObject; m_backendObject = 0; } createBackend(); foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->createBackendObject(); } emit backendChanged(); } #endif //QT_NO_DBUS //X void Factory::freeSoundcardDevices() //X { //X if (globalFactory->backend) { //X globalFactory->backend->freeSoundcardDevices(); //X } //X } void FactoryPrivate::objectDestroyed(QObject * obj) { //pDebug() << Q_FUNC_INFO << obj; objects.removeAll(obj); } #define FACTORY_IMPL(classname) \ QObject *Factory::create ## classname(QObject *parent) \ { \ if (backend()) { \ return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent)); \ } \ return 0; \ } #define FACTORY_IMPL_1ARG(classname) \ QObject *Factory::create ## classname(int arg1, QObject *parent) \ { \ if (backend()) { \ return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent, QList<QVariant>() << arg1)); \ } \ return 0; \ } FACTORY_IMPL(MediaObject) #ifndef QT_NO_PHONON_EFFECT FACTORY_IMPL_1ARG(Effect) #endif //QT_NO_PHONON_EFFECT #ifndef QT_NO_PHONON_VOLUMEFADEREFFECT FACTORY_IMPL(VolumeFaderEffect) #endif //QT_NO_PHONON_VOLUMEFADEREFFECT FACTORY_IMPL(AudioOutput) #ifndef QT_NO_PHONON_VIDEO FACTORY_IMPL(VideoWidget) #endif //QT_NO_PHONON_VIDEO #undef FACTORY_IMPL #ifndef QT_NO_PHONON_PLATFORMPLUGIN PlatformPlugin *FactoryPrivate::platformPlugin() { if (m_platformPlugin) { return m_platformPlugin; } if (m_noPlatformPlugin) { return 0; } #ifndef QT_NO_DBUS if (!QCoreApplication::instance() || QCoreApplication::applicationName().isEmpty()) { pWarning() << "Phonon needs QCoreApplication::applicationName to be set to export audio output names through the DBUS interface"; } #endif const QString suffix(QLatin1String("/phonon_platform/")); Q_ASSERT(QCoreApplication::instance()); ensureLibraryPathSet(); foreach (QString libPath, QCoreApplication::libraryPaths()) { libPath += suffix; const QDir dir(libPath); if (!dir.exists()) { pDebug() << Q_FUNC_INFO << dir.absolutePath() << "does not exist"; continue; } foreach (const QString &pluginName, dir.entryList(QDir::Files)) { QPluginLoader pluginLoader(libPath + pluginName); if (!pluginLoader.load()) { pDebug() << Q_FUNC_INFO << " platform plugin load failed:" << pluginLoader.errorString(); continue; } pDebug() << pluginLoader.instance(); QObject *qobj = pluginLoader.instance(); m_platformPlugin = qobject_cast<PlatformPlugin *>(qobj); pDebug() << m_platformPlugin; if (m_platformPlugin) { connect(qobj, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SLOT(objectDescriptionChanged(ObjectDescriptionType))); return m_platformPlugin; } else { delete qobj; pDebug() << Q_FUNC_INFO << dir.absolutePath() << "exists but the platform plugin was not loadable:" << pluginLoader.errorString(); pluginLoader.unload(); } } } pDebug() << Q_FUNC_INFO << "phonon_platform/kde plugin could not be loaded"; m_noPlatformPlugin = true; return 0; } PlatformPlugin *Factory::platformPlugin() { return globalFactory->platformPlugin(); } #endif // QT_NO_PHONON_PLATFORMPLUGIN QObject *Factory::backend(bool createWhenNull) { if (globalFactory.isDestroyed()) { return 0; } if (createWhenNull && globalFactory->m_backendObject == 0) { globalFactory->createBackend(); // XXX: might create "reentrancy" problems: // a method calls this method and is called again because the // backendChanged signal is emitted emit globalFactory->backendChanged(); } return globalFactory->m_backendObject; } #define GET_STRING_PROPERTY(name) \ QString Factory::name() \ { \ if (globalFactory->m_backendObject) { \ return globalFactory->m_backendObject->property(#name).toString(); \ } \ return QString(); \ } \ GET_STRING_PROPERTY(identifier) GET_STRING_PROPERTY(backendName) GET_STRING_PROPERTY(backendComment) GET_STRING_PROPERTY(backendVersion) GET_STRING_PROPERTY(backendIcon) GET_STRING_PROPERTY(backendWebsite) QObject *Factory::registerQObject(QObject *o) { if (o) { QObject::connect(o, SIGNAL(destroyed(QObject *)), globalFactory, SLOT(objectDestroyed(QObject *)), Qt::DirectConnection); globalFactory->objects.append(o); } return o; } } //namespace Phonon QT_END_NAMESPACE #include "factory.moc" #include "moc_factory_p.cpp" // vim: sw=4 ts=4 <commit_msg>When running in a KDE session prefer the KDE platform plugin, when running in a GNOME session prefer gnome.* (doesn't exist atm, but might be added after the release, so it makes sense to let libphonon behave correctly already). Also allow to load a specific platform plugin using the PHONON_PLATFORMPLUGIN environment variable<commit_after>/* This file is part of the KDE project Copyright (C) 2004-2007 Matthias Kretz <kretz@kde.org> 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) version 3, or any later version accepted by the membership of KDE e.V. (or its successor approved by the membership of KDE e.V.), Trolltech ASA (or its successors, if any) and the KDE Free Qt Foundation, which shall act as a proxy defined in Section 6 of version 3 of the license. 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, see <http://www.gnu.org/licenses/>. */ #include "factory_p.h" #include "backendinterface.h" #include "medianode_p.h" #include "mediaobject.h" #include "audiooutput.h" #include "globalstatic_p.h" #include "objectdescription.h" #include "platformplugin.h" #include "phononnamespace_p.h" #include <QtCore/QCoreApplication> #include <QtCore/QDir> #include <QtCore/QList> #include <QtCore/QPluginLoader> #include <QtCore/QPointer> #ifndef QT_NO_DBUS #include <QtDBus/QtDBus> #endif QT_BEGIN_NAMESPACE namespace Phonon { class PlatformPlugin; class FactoryPrivate : public Phonon::Factory::Sender { friend QObject *Factory::backend(bool); Q_OBJECT public: FactoryPrivate(); ~FactoryPrivate(); bool createBackend(); #ifndef QT_NO_PHONON_PLATFORMPLUGIN PlatformPlugin *platformPlugin(); PlatformPlugin *m_platformPlugin; bool m_noPlatformPlugin; #endif //QT_NO_PHONON_PLATFORMPLUGIN QPointer<QObject> m_backendObject; QList<QObject *> objects; QList<MediaNodePrivate *> mediaNodePrivateList; private Q_SLOTS: /** * This is called via DBUS when the user changes the Phonon Backend. */ #ifndef QT_NO_DBUS void phononBackendChanged(); #endif //QT_NO_DBUS /** * unregisters the backend object */ void objectDestroyed(QObject *); void objectDescriptionChanged(ObjectDescriptionType); }; PHONON_GLOBAL_STATIC(Phonon::FactoryPrivate, globalFactory) static inline void ensureLibraryPathSet() { #ifdef PHONON_LIBRARY_PATH static bool done = false; if (!done) { done = true; QCoreApplication::addLibraryPath(QLatin1String(PHONON_LIBRARY_PATH)); } #endif // PHONON_LIBRARY_PATH } void Factory::setBackend(QObject *b) { Q_ASSERT(globalFactory->m_backendObject == 0); globalFactory->m_backendObject = b; } /*void Factory::createBackend(const QString &library, const QString &version) { Q_ASSERT(globalFactory->m_backendObject == 0); PlatformPlugin *f = globalFactory->platformPlugin(); if (f) { globalFactory->m_backendObject = f->createBackend(library, version); } }*/ bool FactoryPrivate::createBackend() { Q_ASSERT(m_backendObject == 0); #ifndef QT_NO_PHONON_PLATFORMPLUGIN PlatformPlugin *f = globalFactory->platformPlugin(); if (f) { m_backendObject = f->createBackend(); } #endif //QT_NO_PHONON_PLATFORMPLUGIN if (!m_backendObject) { ensureLibraryPathSet(); // could not load a backend through the platform plugin. Falling back to the default // (finding the first loadable backend). const QLatin1String suffix("/phonon_backend/"); foreach (QString libPath, QCoreApplication::libraryPaths()) { libPath += suffix; const QDir dir(libPath); if (!dir.exists()) { pDebug() << Q_FUNC_INFO << dir.absolutePath() << "does not exist"; continue; } foreach (const QString &pluginName, dir.entryList(QDir::Files)) { QPluginLoader pluginLoader(libPath + pluginName); if (!pluginLoader.load()) { pDebug() << Q_FUNC_INFO << " load failed:" << pluginLoader.errorString(); continue; } pDebug() << pluginLoader.instance(); m_backendObject = pluginLoader.instance(); if (m_backendObject) { break; } // no backend found, don't leave an unused plugin in memory pluginLoader.unload(); } if (m_backendObject) { break; } } if (!m_backendObject) { pWarning() << Q_FUNC_INFO << "phonon backend plugin could not be loaded"; return false; } } connect(m_backendObject, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SLOT(objectDescriptionChanged(ObjectDescriptionType))); return true; } FactoryPrivate::FactoryPrivate() #ifndef QT_NO_PHONON_PLATFORMPLUGIN : m_platformPlugin(0), m_noPlatformPlugin(false) #endif //QT_NO_PHONON_PLATFORMPLUGIN , m_backendObject(0) { // Add the post routine to make sure that all other global statics (especially the ones from Qt) // are still available. If the FactoryPrivate dtor is called too late many bad things can happen // as the whole backend might still be alive. qAddPostRoutine(globalFactory.destroy); #ifndef QT_NO_DBUS QDBusConnection::sessionBus().connect(QString(), QString(), "org.kde.Phonon.Factory", "phononBackendChanged", this, SLOT(phononBackendChanged())); #endif } FactoryPrivate::~FactoryPrivate() { foreach (QObject *o, objects) { MediaObject *m = qobject_cast<MediaObject *>(o); if (m) { m->stop(); } } foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->deleteBackendObject(); } if (objects.size() > 0) { pError() << "The backend objects are not deleted as was requested."; qDeleteAll(objects); } delete m_backendObject; #ifndef QT_NO_PHONON_PLATFORMPLUGIN delete m_platformPlugin; #endif //QT_NO_PHONON_PLATFORMPLUGIN } void FactoryPrivate::objectDescriptionChanged(ObjectDescriptionType type) { #ifdef PHONON_METHODTEST Q_UNUSED(type); #else pDebug() << Q_FUNC_INFO << type; switch (type) { case AudioOutputDeviceType: emit availableAudioOutputDevicesChanged(); break; case AudioCaptureDeviceType: emit availableAudioCaptureDevicesChanged(); break; default: break; } //emit capabilitiesChanged(); #endif // PHONON_METHODTEST } Factory::Sender *Factory::sender() { return globalFactory; } bool Factory::isMimeTypeAvailable(const QString &mimeType) { #ifndef QT_NO_PHONON_PLATFORMPLUGIN PlatformPlugin *f = globalFactory->platformPlugin(); if (f) { return f->isMimeTypeAvailable(mimeType); } #else Q_UNUSED(mimeType); #endif //QT_NO_PHONON_PLATFORMPLUGIN return true; // the MIME type might be supported, let BackendCapabilities find out } void Factory::registerFrontendObject(MediaNodePrivate *bp) { globalFactory->mediaNodePrivateList.prepend(bp); // inserted last => deleted first } void Factory::deregisterFrontendObject(MediaNodePrivate *bp) { // The Factory can already be cleaned up while there are other frontend objects still alive. // When those are deleted they'll call deregisterFrontendObject through ~BasePrivate if (!globalFactory.isDestroyed()) { globalFactory->mediaNodePrivateList.removeAll(bp); } } #ifndef QT_NO_DBUS void FactoryPrivate::phononBackendChanged() { if (m_backendObject) { foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->deleteBackendObject(); } if (objects.size() > 0) { pDebug() << "WARNING: we were asked to change the backend but the application did\n" "not free all references to objects created by the factory. Therefore we can not\n" "change the backend without crashing. Now we have to wait for a restart to make\n" "backendswitching possible."; // in case there were objects deleted give 'em a chance to recreate // them now foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->createBackendObject(); } return; } delete m_backendObject; m_backendObject = 0; } createBackend(); foreach (MediaNodePrivate *bp, mediaNodePrivateList) { bp->createBackendObject(); } emit backendChanged(); } #endif //QT_NO_DBUS //X void Factory::freeSoundcardDevices() //X { //X if (globalFactory->backend) { //X globalFactory->backend->freeSoundcardDevices(); //X } //X } void FactoryPrivate::objectDestroyed(QObject * obj) { //pDebug() << Q_FUNC_INFO << obj; objects.removeAll(obj); } #define FACTORY_IMPL(classname) \ QObject *Factory::create ## classname(QObject *parent) \ { \ if (backend()) { \ return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent)); \ } \ return 0; \ } #define FACTORY_IMPL_1ARG(classname) \ QObject *Factory::create ## classname(int arg1, QObject *parent) \ { \ if (backend()) { \ return registerQObject(qobject_cast<BackendInterface *>(backend())->createObject(BackendInterface::classname##Class, parent, QList<QVariant>() << arg1)); \ } \ return 0; \ } FACTORY_IMPL(MediaObject) #ifndef QT_NO_PHONON_EFFECT FACTORY_IMPL_1ARG(Effect) #endif //QT_NO_PHONON_EFFECT #ifndef QT_NO_PHONON_VOLUMEFADEREFFECT FACTORY_IMPL(VolumeFaderEffect) #endif //QT_NO_PHONON_VOLUMEFADEREFFECT FACTORY_IMPL(AudioOutput) #ifndef QT_NO_PHONON_VIDEO FACTORY_IMPL(VideoWidget) #endif //QT_NO_PHONON_VIDEO #undef FACTORY_IMPL #ifndef QT_NO_PHONON_PLATFORMPLUGIN PlatformPlugin *FactoryPrivate::platformPlugin() { if (m_platformPlugin) { return m_platformPlugin; } if (m_noPlatformPlugin) { return 0; } #ifndef QT_NO_DBUS if (!QCoreApplication::instance() || QCoreApplication::applicationName().isEmpty()) { pWarning() << "Phonon needs QCoreApplication::applicationName to be set to export audio output names through the DBUS interface"; } #endif Q_ASSERT(QCoreApplication::instance()); if (!qgetenv("PHONON_PLATFORMPLUGIN").isEmpty()) { QPluginLoader pluginLoader(qgetenv("PHONON_PLATFORMPLUGIN")); if (pluginLoader.load()) { m_platformPlugin = qobject_cast<PlatformPlugin *>(pluginLoader.instance()); if (m_platformPlugin) { return m_platformPlugin; } } } const QString suffix(QLatin1String("/phonon_platform/")); ensureLibraryPathSet(); QDir dir; dir.setNameFilters( !qgetenv("KDE_FULL_SESSION").isEmpty() ? QStringList(QLatin1String("kde.*")) : (!qgetenv("GNOME_DESKTOP_SESSION_ID").isEmpty() ? QStringList(QLatin1String("gnome.*")) : QStringList()) ); dir.setFilter(QDir::Files); forever { foreach (QString libPath, QCoreApplication::libraryPaths()) { libPath += suffix; dir.setPath(libPath); if (!dir.exists()) { continue; } foreach (const QString &pluginName, dir.entryList()) { QPluginLoader pluginLoader(libPath + pluginName); if (!pluginLoader.load()) { pDebug() << Q_FUNC_INFO << " platform plugin load failed:" << pluginLoader.errorString(); continue; } pDebug() << pluginLoader.instance(); QObject *qobj = pluginLoader.instance(); m_platformPlugin = qobject_cast<PlatformPlugin *>(qobj); pDebug() << m_platformPlugin; if (m_platformPlugin) { connect(qobj, SIGNAL(objectDescriptionChanged(ObjectDescriptionType)), SLOT(objectDescriptionChanged(ObjectDescriptionType))); return m_platformPlugin; } else { delete qobj; pDebug() << Q_FUNC_INFO << dir.absolutePath() << "exists but the platform plugin was not loadable:" << pluginLoader.errorString(); pluginLoader.unload(); } } } if (dir.nameFilters().isEmpty()) { break; } dir.setNameFilters(QStringList()); } pDebug() << Q_FUNC_INFO << "platform plugin could not be loaded"; m_noPlatformPlugin = true; return 0; } PlatformPlugin *Factory::platformPlugin() { return globalFactory->platformPlugin(); } #endif // QT_NO_PHONON_PLATFORMPLUGIN QObject *Factory::backend(bool createWhenNull) { if (globalFactory.isDestroyed()) { return 0; } if (createWhenNull && globalFactory->m_backendObject == 0) { globalFactory->createBackend(); // XXX: might create "reentrancy" problems: // a method calls this method and is called again because the // backendChanged signal is emitted emit globalFactory->backendChanged(); } return globalFactory->m_backendObject; } #define GET_STRING_PROPERTY(name) \ QString Factory::name() \ { \ if (globalFactory->m_backendObject) { \ return globalFactory->m_backendObject->property(#name).toString(); \ } \ return QString(); \ } \ GET_STRING_PROPERTY(identifier) GET_STRING_PROPERTY(backendName) GET_STRING_PROPERTY(backendComment) GET_STRING_PROPERTY(backendVersion) GET_STRING_PROPERTY(backendIcon) GET_STRING_PROPERTY(backendWebsite) QObject *Factory::registerQObject(QObject *o) { if (o) { QObject::connect(o, SIGNAL(destroyed(QObject *)), globalFactory, SLOT(objectDestroyed(QObject *)), Qt::DirectConnection); globalFactory->objects.append(o); } return o; } } //namespace Phonon QT_END_NAMESPACE #include "factory.moc" #include "moc_factory_p.cpp" // vim: sw=4 ts=4 <|endoftext|>
<commit_before>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageWriter.h" #include "mitkItkImageWrite.h" #include "mitkImage.h" #include "mitkImageTimeSelector.h" #include "mitkImageAccessByItk.h" #include "mitkPicFileWriter.h" #include <itksys/SystemTools.hxx> #include <sstream> mitk::ImageWriter::ImageWriter() { this->SetNumberOfRequiredInputs( 1 ); m_MimeType = ""; SetDefaultExtension(); } mitk::ImageWriter::~ImageWriter() { } void mitk::ImageWriter::SetDefaultExtension() { m_Extension = ".mhd"; } #include <vtkConfigure.h> #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) #include <vtkImageData.h> #include <vtkXMLImageDataWriter.h> static void writeVti(const char * filename, mitk::Image* image, int t=0) { vtkXMLImageDataWriter * vtkwriter = vtkXMLImageDataWriter::New(); vtkwriter->SetFileName( filename ); vtkwriter->SetInput(image->GetVtkImageData(t)); vtkwriter->Write(); vtkwriter->Delete(); } #endif void mitk::ImageWriter::WriteByITK(mitk::Image* image, const std::string& filename) { if(image->GetPixelType().GetNumberOfComponents()==1) { AccessByItk_1( image, _mitkItkImageWrite, filename ); } //// Extension for RGB (and maybe also for vector types) //// Does not work yet, see bug 320 and mitkImageCastPart2.cpp //else //if(image->GetPixelType().GetNumberOfComponents()==3) //{ // const std::type_info& typeId=*(image)->GetPixelType().GetTypeId(); // if ( typeId == typeid(unsigned char) ) // { // if(image->GetDimension()==2) // { // typedef itk::Image<itk::RGBPixel<unsigned char>, 2> itkImageRGBUC2; // itkImageRGBUC2::Pointer itkRGBimage; // mitk::CastToItkImage(image, itkRGBimage); // _mitkItkImageWrite(itkRGBimage.GetPointer(), filename); // } // else // if(image->GetDimension()==3) // { // typedef itk::Image<itk::RGBPixel<unsigned char>, 3> itkImageRGBUC3; // itkImageRGBUC3::Pointer itkRGBimage; // mitk::CastToItkImage(image, itkRGBimage); // _mitkItkImageWrite(itkRGBimage.GetPointer(), filename); // } // } // else // { // itkWarningMacro(<<"Sorry, cannot write images with GetNumberOfComponents()==3 that " // << "have pixeltype " << typeId.name() << " using ITK writers ."); // } //} else { itkWarningMacro(<<"Sorry, cannot write images with GetNumberOfComponents()==" << image->GetPixelType().GetNumberOfComponents() << " using ITK writers ."); } } void mitk::ImageWriter::GenerateData() { if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } if (fopen(m_FileName.c_str(),"w")==NULL) { itkExceptionMacro(<<"File location not writeable"); return; } mitk::Image::Pointer input = const_cast<mitk::Image*>(this->GetInput()); #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) bool vti = (m_Extension.find(".vti") != std::string::npos); #endif if ( m_Extension.find(".pic") == std::string::npos ) { if(input->GetDimension() > 3) { int t, timesteps; timesteps = input->GetDimension(3); ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput(input); mitk::Image::Pointer image = timeSelector->GetOutput(); for(t = 0; t < timesteps; ++t) { ::itk::OStringStream filename; timeSelector->SetTimeNr(t); timeSelector->Update(); if(input->GetTimeSlicedGeometry()->IsValidTime(t)) { const mitk::TimeBounds& timebounds = input->GetTimeSlicedGeometry()->GetGeometry3D(t)->GetTimeBounds(); filename << m_FileName.c_str() << "_S" << std::setprecision(0) << timebounds[0] << "_E" << std::setprecision(0) << timebounds[1] << "_T" << t << m_Extension; } else { itkWarningMacro(<<"Error on write: TimeSlicedGeometry invalid of image " << filename << "."); filename << m_FileName.c_str() << "_T" << t << m_Extension; } #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) if ( vti ) { writeVti(filename.str().c_str(), input, t); } else #endif { WriteByITK(input, filename.str()); } } } #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) else if ( vti ) { ::itk::OStringStream filename; filename << m_FileName.c_str() << m_Extension; writeVti(filename.str().c_str(), input); } #endif else { ::itk::OStringStream filename; filename << m_FileName.c_str() << m_Extension; WriteByITK(input, filename.str()); } } else { PicFileWriter::Pointer picWriter = PicFileWriter::New(); size_t found; found = m_FileName.find( m_Extension ); // !!! HAS to be at the very end of the filename (not somewhere in the middle) if( m_FileName.length() > 3 && found != m_FileName.length() - 4 ) { //if Extension not in Filename ::itk::OStringStream filename; filename << m_FileName.c_str() << m_Extension; picWriter->SetFileName( filename.str().c_str() ); } else picWriter->SetFileName( m_FileName.c_str() ); picWriter->SetInput( input ); picWriter->Write(); } m_MimeType = "application/MITK.Pic"; } bool mitk::ImageWriter::CanWriteDataType( DataTreeNode* input ) { if ( input ) { mitk::BaseData* data = input->GetData(); if ( data ) { mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( data ); if( image.IsNotNull() ) { //"SetDefaultExtension()" set m_Extension to ".mhd" ????? m_Extension = ".pic"; return true; } } } return false; } void mitk::ImageWriter::SetInput( DataTreeNode* input ) { if( input && CanWriteDataType( input ) ) this->ProcessObject::SetNthInput( 0, dynamic_cast<mitk::Image*>( input->GetData() ) ); } std::string mitk::ImageWriter::GetWritenMIMEType() { return m_MimeType; } std::vector<std::string> mitk::ImageWriter::GetPossibleFileExtensions() { std::vector<std::string> possibleFileExtensions; possibleFileExtensions.push_back(".pic"); possibleFileExtensions.push_back(".mhd"); possibleFileExtensions.push_back(".vtk"); possibleFileExtensions.push_back(".vti"); possibleFileExtensions.push_back(".hdr"); possibleFileExtensions.push_back(".png"); possibleFileExtensions.push_back(".tif"); possibleFileExtensions.push_back(".jpg"); return possibleFileExtensions; } std::string mitk::ImageWriter::GetFileExtension() { return m_Extension; } void mitk::ImageWriter::SetInput( mitk::Image* image ) { this->ProcessObject::SetNthInput( 0, image ); } const mitk::Image* mitk::ImageWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return NULL; } else { return static_cast< const mitk::Image * >( this->ProcessObject::GetInput( 0 ) ); } } <commit_msg>FIX (#1830): removed test file after file writing test<commit_after>/*========================================================================= Program: Medical Imaging & Interaction Toolkit Language: C++ Date: $Date$ Version: $Revision$ Copyright (c) German Cancer Research Center, Division of Medical and Biological Informatics. All rights reserved. See MITKCopyright.txt or http://www.mitk.org/copyright.html for details. This software is distributed WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the above copyright notices for more information. =========================================================================*/ #include "mitkImageWriter.h" #include "mitkItkImageWrite.h" #include "mitkImage.h" #include "mitkImageTimeSelector.h" #include "mitkImageAccessByItk.h" #include "mitkPicFileWriter.h" #include <itksys/SystemTools.hxx> #include <sstream> mitk::ImageWriter::ImageWriter() { this->SetNumberOfRequiredInputs( 1 ); m_MimeType = ""; SetDefaultExtension(); } mitk::ImageWriter::~ImageWriter() { } void mitk::ImageWriter::SetDefaultExtension() { m_Extension = ".mhd"; } #include <vtkConfigure.h> #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) #include <vtkImageData.h> #include <vtkXMLImageDataWriter.h> static void writeVti(const char * filename, mitk::Image* image, int t=0) { vtkXMLImageDataWriter * vtkwriter = vtkXMLImageDataWriter::New(); vtkwriter->SetFileName( filename ); vtkwriter->SetInput(image->GetVtkImageData(t)); vtkwriter->Write(); vtkwriter->Delete(); } #endif void mitk::ImageWriter::WriteByITK(mitk::Image* image, const std::string& filename) { if(image->GetPixelType().GetNumberOfComponents()==1) { AccessByItk_1( image, _mitkItkImageWrite, filename ); } //// Extension for RGB (and maybe also for vector types) //// Does not work yet, see bug 320 and mitkImageCastPart2.cpp //else //if(image->GetPixelType().GetNumberOfComponents()==3) //{ // const std::type_info& typeId=*(image)->GetPixelType().GetTypeId(); // if ( typeId == typeid(unsigned char) ) // { // if(image->GetDimension()==2) // { // typedef itk::Image<itk::RGBPixel<unsigned char>, 2> itkImageRGBUC2; // itkImageRGBUC2::Pointer itkRGBimage; // mitk::CastToItkImage(image, itkRGBimage); // _mitkItkImageWrite(itkRGBimage.GetPointer(), filename); // } // else // if(image->GetDimension()==3) // { // typedef itk::Image<itk::RGBPixel<unsigned char>, 3> itkImageRGBUC3; // itkImageRGBUC3::Pointer itkRGBimage; // mitk::CastToItkImage(image, itkRGBimage); // _mitkItkImageWrite(itkRGBimage.GetPointer(), filename); // } // } // else // { // itkWarningMacro(<<"Sorry, cannot write images with GetNumberOfComponents()==3 that " // << "have pixeltype " << typeId.name() << " using ITK writers ."); // } //} else { itkWarningMacro(<<"Sorry, cannot write images with GetNumberOfComponents()==" << image->GetPixelType().GetNumberOfComponents() << " using ITK writers ."); } } void mitk::ImageWriter::GenerateData() { if ( m_FileName == "" ) { itkWarningMacro( << "Sorry, filename has not been set!" ); return ; } FILE* tempFile = fopen(m_FileName.c_str(),"w"); if (tempFile==NULL) { itkExceptionMacro(<<"File location not writeable"); return; } fclose(tempFile); remove(m_FileName.c_str()); mitk::Image::Pointer input = const_cast<mitk::Image*>(this->GetInput()); #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) bool vti = (m_Extension.find(".vti") != std::string::npos); #endif if ( m_Extension.find(".pic") == std::string::npos ) { if(input->GetDimension() > 3) { int t, timesteps; timesteps = input->GetDimension(3); ImageTimeSelector::Pointer timeSelector = ImageTimeSelector::New(); timeSelector->SetInput(input); mitk::Image::Pointer image = timeSelector->GetOutput(); for(t = 0; t < timesteps; ++t) { ::itk::OStringStream filename; timeSelector->SetTimeNr(t); timeSelector->Update(); if(input->GetTimeSlicedGeometry()->IsValidTime(t)) { const mitk::TimeBounds& timebounds = input->GetTimeSlicedGeometry()->GetGeometry3D(t)->GetTimeBounds(); filename << m_FileName.c_str() << "_S" << std::setprecision(0) << timebounds[0] << "_E" << std::setprecision(0) << timebounds[1] << "_T" << t << m_Extension; } else { itkWarningMacro(<<"Error on write: TimeSlicedGeometry invalid of image " << filename << "."); filename << m_FileName.c_str() << "_T" << t << m_Extension; } #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) if ( vti ) { writeVti(filename.str().c_str(), input, t); } else #endif { WriteByITK(input, filename.str()); } } } #if ((VTK_MAJOR_VERSION > 4) || ((VTK_MAJOR_VERSION==4) && (VTK_MINOR_VERSION>=4) )) else if ( vti ) { ::itk::OStringStream filename; filename << m_FileName.c_str() << m_Extension; writeVti(filename.str().c_str(), input); } #endif else { ::itk::OStringStream filename; filename << m_FileName.c_str() << m_Extension; WriteByITK(input, filename.str()); } } else { PicFileWriter::Pointer picWriter = PicFileWriter::New(); size_t found; found = m_FileName.find( m_Extension ); // !!! HAS to be at the very end of the filename (not somewhere in the middle) if( m_FileName.length() > 3 && found != m_FileName.length() - 4 ) { //if Extension not in Filename ::itk::OStringStream filename; filename << m_FileName.c_str() << m_Extension; picWriter->SetFileName( filename.str().c_str() ); } else picWriter->SetFileName( m_FileName.c_str() ); picWriter->SetInput( input ); picWriter->Write(); } m_MimeType = "application/MITK.Pic"; } bool mitk::ImageWriter::CanWriteDataType( DataTreeNode* input ) { if ( input ) { mitk::BaseData* data = input->GetData(); if ( data ) { mitk::Image::Pointer image = dynamic_cast<mitk::Image*>( data ); if( image.IsNotNull() ) { //"SetDefaultExtension()" set m_Extension to ".mhd" ????? m_Extension = ".pic"; return true; } } } return false; } void mitk::ImageWriter::SetInput( DataTreeNode* input ) { if( input && CanWriteDataType( input ) ) this->ProcessObject::SetNthInput( 0, dynamic_cast<mitk::Image*>( input->GetData() ) ); } std::string mitk::ImageWriter::GetWritenMIMEType() { return m_MimeType; } std::vector<std::string> mitk::ImageWriter::GetPossibleFileExtensions() { std::vector<std::string> possibleFileExtensions; possibleFileExtensions.push_back(".pic"); possibleFileExtensions.push_back(".mhd"); possibleFileExtensions.push_back(".vtk"); possibleFileExtensions.push_back(".vti"); possibleFileExtensions.push_back(".hdr"); possibleFileExtensions.push_back(".png"); possibleFileExtensions.push_back(".tif"); possibleFileExtensions.push_back(".jpg"); return possibleFileExtensions; } std::string mitk::ImageWriter::GetFileExtension() { return m_Extension; } void mitk::ImageWriter::SetInput( mitk::Image* image ) { this->ProcessObject::SetNthInput( 0, image ); } const mitk::Image* mitk::ImageWriter::GetInput() { if ( this->GetNumberOfInputs() < 1 ) { return NULL; } else { return static_cast< const mitk::Image * >( this->ProcessObject::GetInput( 0 ) ); } } <|endoftext|>
<commit_before>/* This file is part of the MinSG library. Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org> Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "ShaderState.h" #include "../FrameContext.h" #include "../Nodes/Node.h" #include <Rendering/RenderingContext/RenderingContext.h> #include <Util/Macros.h> #include <map> namespace MinSG { //! (ctor) ShaderState::ShaderState(Rendering::Shader * _shader/*=nullptr*/) : State(), shader(_shader) { } //! (ctor) ShaderState::ShaderState(const ShaderState & source) : State(source), uMap(source.uMap), shader(source.shader) { } //! (dtor) ShaderState::~ShaderState() { setShader( nullptr); uMap.clear(); } //! ---|> [Node] ShaderState * ShaderState::clone() const { return new ShaderState(*this); } void ShaderState::setUniform(const Rendering::Uniform & value) { uMap[value.getName()] = Rendering::Uniform(value); } void ShaderState::setUniform(FrameContext & context, const Rendering::Uniform & value) { setUniform(value); shader->setUniform(context.getRenderingContext(),value,true,true); // warn if uniform is not defined in shader and force at least one try on applying the uniform } Rendering::Uniform ShaderState::getUniform(const std::string & name) const { auto it = uMap.find(name); return it == uMap.end() ? Rendering::Uniform() : Rendering::Uniform(it->second); } //! ---|> [State] State::stateResult_t ShaderState::doEnableState(FrameContext & context, Node *, const RenderParam & /*rp*/) { if (shader.isNull()) return State::STATE_SKIPPED; // push current shader to stack context.getRenderingContext().pushAndSetShader(shader.get()); if (context.getRenderingContext().isShaderEnabled(shader.get())) for(auto & uniformEntry : uMap) { shader->setUniform(context.getRenderingContext(), uniformEntry.second); } else{ deactivate(); WARN("Enabling shaderstate failed. State has been deactivated!"); return State::STATE_SKIPPED; } return State::STATE_OK; } //! ---|> [State] void ShaderState::doDisableState(FrameContext & context, Node *, const RenderParam & /*rp*/) { if (shader.isNull()) { return; } // restore old shader context.getRenderingContext().popShader(); } } <commit_msg>ShaderState: Increase robustness when trying to use invalid shader.<commit_after>/* This file is part of the MinSG library. Copyright (C) 2007-2012 Benjamin Eikel <benjamin@eikel.org> Copyright (C) 2007-2012 Claudius Jähn <claudius@uni-paderborn.de> Copyright (C) 2007-2012 Ralf Petring <ralf@petring.net> This library is subject to the terms of the Mozilla Public License, v. 2.0. You should have received a copy of the MPL along with this library; see the file LICENSE. If not, you can obtain one at http://mozilla.org/MPL/2.0/. */ #include "ShaderState.h" #include "../FrameContext.h" #include "../Nodes/Node.h" #include <Rendering/RenderingContext/RenderingContext.h> #include <Util/Macros.h> #include <map> namespace MinSG { //! (ctor) ShaderState::ShaderState(Rendering::Shader * _shader/*=nullptr*/) : State(), shader(_shader) { } //! (ctor) ShaderState::ShaderState(const ShaderState & source) : State(source), uMap(source.uMap), shader(source.shader) { } //! (dtor) ShaderState::~ShaderState() { setShader( nullptr); uMap.clear(); } //! ---|> [Node] ShaderState * ShaderState::clone() const { return new ShaderState(*this); } void ShaderState::setUniform(const Rendering::Uniform & value) { uMap[value.getName()] = Rendering::Uniform(value); } void ShaderState::setUniform(FrameContext & context, const Rendering::Uniform & value) { setUniform(value); shader->setUniform(context.getRenderingContext(),value,true,true); // warn if uniform is not defined in shader and force at least one try on applying the uniform } Rendering::Uniform ShaderState::getUniform(const std::string & name) const { auto it = uMap.find(name); return it == uMap.end() ? Rendering::Uniform() : Rendering::Uniform(it->second); } //! ---|> [State] State::stateResult_t ShaderState::doEnableState(FrameContext & context, Node *, const RenderParam & /*rp*/) { if( !shader ) return State::STATE_SKIPPED; auto & rCtxt = context.getRenderingContext(); // push current shader to stack rCtxt.pushAndSetShader(shader.get()); if( !rCtxt.isShaderEnabled(shader.get()) ){ rCtxt.popShader(); deactivate(); WARN("Enabling ShaderState failed. State has been deactivated!"); return State::STATE_SKIPPED; } for(const auto & uniformEntry : uMap) shader->setUniform(rCtxt, uniformEntry.second); return State::STATE_OK; } //! ---|> [State] void ShaderState::doDisableState(FrameContext & context, Node *, const RenderParam & /*rp*/) { // restore old shader context.getRenderingContext().popShader(); } } <|endoftext|>
<commit_before>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** 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 "IconProvider.hpp" #include <QBuffer> #include "Database/SqlDatabase.hpp" #include "Utils/AutoSaver.hpp" #include "Web/WebView.hpp" #include "Application.hpp" #include <ndb/query.hpp> Q_GLOBAL_STATIC(Sn::IconProvider, sn_icon_provider) constexpr auto& icons = ndb::models::images.icons; namespace Sn { QByteArray IconProvider::encodeUrl(const QUrl& url) { return url.toEncoded(QUrl::RemoveFragment | QUrl::StripTrailingSlash); } IconProvider::IconProvider() : QObject(), m_autoSaver(new AutoSaver(this)) { // Empty } IconProvider::~IconProvider() { // Empty } void IconProvider::saveIcon(WebView* view) { // Don't save icons in private mode. if (Application::instance()->privateBrowsing()) return; const QIcon icon{view->icon(true)}; if (icon.isNull()) // We don't want to store nulle icon return; // Some schem must be ignored beceause we don't want to save the icon const QStringList ignoredSchemes = { QStringLiteral("sielo"), QStringLiteral("ftp"), QStringLiteral("file"), QStringLiteral("view-source") }; if (ignoredSchemes.contains(view->url().scheme())) return; // We should not save an icon twice for (int i{0}; i < m_iconBuffer.size(); ++i) { if (m_iconBuffer[i].first == view->url()) { m_iconBuffer.removeAt(i); break; } } BufferedIcon item{}; item.first = view->url(); item.second = icon.pixmap(16).toImage(); m_autoSaver->changeOccurred(); m_iconBuffer.append(item); } QIcon IconProvider::iconForUrl(const QUrl& url, bool allowNull) { return instance()->iconFromImage(imageForUrl(url, allowNull)); } QImage IconProvider::imageForUrl(const QUrl& url, bool allowNull) { if (url.path().isEmpty()) return allowNull ? QImage() : Application::getAppIcon("webpage").pixmap(16).toImage(); const QByteArray encodedUrl = encodeUrl(url); // Check if we aleady have the image loaded in the buffer foreach(const BufferedIcon &ic, instance()->m_iconBuffer) { if (encodeUrl(ic.first) == encodedUrl) return ic.second; } auto result = ndb::query<dbs::image>() << (icons.icon << (ndb::glob(icons.url, QString("%1*").arg(QString::fromUtf8(encodedUrl)).toStdString()) << ndb::limit(1))); if (result.has_result()) return QImage::fromData(result[0][icons.icon]); return allowNull ? QImage() : Application::getAppIcon("webpage").pixmap(16).toImage(); } QIcon IconProvider::iconForDomain(const QUrl& url, bool allowNull) { return instance()->iconFromImage(imageForDomain(url, allowNull)); } QImage IconProvider::imageForDomain(const QUrl& url, bool allowNull) { if (url.path().isEmpty()) return allowNull ? QImage() : Application::getAppIcon("webpage").pixmap(16).toImage(); std::string strUrlHost = url.host().toStdString(); // Check if we aleady have the image loaded in the buffer foreach(const BufferedIcon &ic, instance()->m_iconBuffer) { if (ic.first.host() == url.host()) return ic.second; } auto result = ndb::query<dbs::image>() << (icons.icon << (ndb::glob(icons.url, QString("*%1*").arg(url.host()).toStdString()) << ndb::limit(1))); if (result.has_result()) return QImage::fromData(result[0][icons.icon]); return allowNull ? QImage() : Application::getAppIcon("webpage").pixmap(16).toImage(); } IconProvider *IconProvider::instance() { return sn_icon_provider(); } void IconProvider::save() { foreach(const BufferedIcon &ic, m_iconBuffer) { QByteArray ba; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); ic.second.save(&buffer, "PNG"); auto iconQuery = ndb::query<dbs::image>() << (icons.url == QString::fromUtf8(encodeUrl(ic.first))); if (iconQuery.has_result()) ndb::query<dbs::image>() >> (icons.icon = buffer.data() << (icons.url == QString::fromUtf8(encodeUrl(ic.first)))); else ndb::query<dbs::image>() + (icons.icon = buffer.data(), icons.url = QString::fromUtf8(encodeUrl(ic.first))); } m_iconBuffer.clear(); } QIcon IconProvider::iconFromImage(const QImage& image) { return QIcon(QPixmap::fromImage(image)); } } <commit_msg>[Update] Replace ndb for Icon provider<commit_after>/*********************************************************************************** ** MIT License ** ** ** ** Copyright (c) 2018 Victor DENIS (victordenis01@gmail.com) ** ** ** ** 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 "IconProvider.hpp" #include <QBuffer> #include <QSqlQuery> #include "Database/SqlDatabase.hpp" #include "Utils/AutoSaver.hpp" #include "Web/WebView.hpp" #include "Application.hpp" Q_GLOBAL_STATIC(Sn::IconProvider, sn_icon_provider) namespace Sn { QByteArray IconProvider::encodeUrl(const QUrl& url) { return url.toEncoded(QUrl::RemoveFragment | QUrl::StripTrailingSlash); } IconProvider::IconProvider() : QObject(), m_autoSaver(new AutoSaver(this)) { // Empty } IconProvider::~IconProvider() { // Empty } void IconProvider::saveIcon(WebView* view) { // Don't save icons in private mode. if (Application::instance()->privateBrowsing()) return; const QIcon icon{view->icon(true)}; if (icon.isNull()) // We don't want to store nulle icon return; // Some schem must be ignored beceause we don't want to save the icon const QStringList ignoredSchemes = { QStringLiteral("sielo"), QStringLiteral("ftp"), QStringLiteral("file"), QStringLiteral("view-source") }; if (ignoredSchemes.contains(view->url().scheme())) return; // We should not save an icon twice for (int i{0}; i < m_iconBuffer.size(); ++i) { if (m_iconBuffer[i].first == view->url()) { m_iconBuffer.removeAt(i); break; } } BufferedIcon item{}; item.first = view->url(); item.second = icon.pixmap(16).toImage(); m_autoSaver->changeOccurred(); m_iconBuffer.append(item); } QIcon IconProvider::iconForUrl(const QUrl& url, bool allowNull) { return instance()->iconFromImage(imageForUrl(url, allowNull)); } QImage IconProvider::imageForUrl(const QUrl& url, bool allowNull) { if (url.path().isEmpty()) return allowNull ? QImage() : Application::getAppIcon("webpage").pixmap(16).toImage(); const QByteArray encodedUrl = encodeUrl(url); // Check if we aleady have the image loaded in the buffer foreach(const BufferedIcon &ic, instance()->m_iconBuffer) { if (encodeUrl(ic.first) == encodedUrl) return ic.second; } QString urlString{QString::fromUtf8(encodedUrl)}; urlString.replace(QLatin1Char('['), QStringLiteral("[[")); urlString.replace(QLatin1Char(']'), QStringLiteral("[]]")); urlString.replace(QStringLiteral("[["), QStringLiteral("[[]")); urlString.replace(QLatin1Char('*'), QStringLiteral("[*]")); urlString.replace(QLatin1Char('?'), QStringLiteral("[?]")); QSqlQuery query{SqlDatabase::instance()->database()}; query.prepare("SELECT icon FROM icons WHERE url GLOB ? LIMIT 1"); query.addBindValue(QString("%1*").arg(urlString)); query.exec(); if (query.next()) return QImage::fromData(query.value(0).toByteArray()); return allowNull ? QImage() : Application::getAppIcon("webpage").pixmap(16).toImage(); } QIcon IconProvider::iconForDomain(const QUrl& url, bool allowNull) { return instance()->iconFromImage(imageForDomain(url, allowNull)); } QImage IconProvider::imageForDomain(const QUrl& url, bool allowNull) { if (url.path().isEmpty()) return allowNull ? QImage() : Application::getAppIcon("webpage").pixmap(16).toImage(); // Check if we aleady have the image loaded in the buffer foreach(const BufferedIcon &ic, instance()->m_iconBuffer) { if (ic.first.host() == url.host()) return ic.second; } QString urlString{url.host()}; urlString.replace(QLatin1Char('['), QStringLiteral("[[")); urlString.replace(QLatin1Char(']'), QStringLiteral("[]]")); urlString.replace(QStringLiteral("[["), QStringLiteral("[[]")); urlString.replace(QLatin1Char('*'), QStringLiteral("[*]")); urlString.replace(QLatin1Char('?'), QStringLiteral("[?]")); QSqlQuery query{SqlDatabase::instance()->database()}; query.prepare("SELECT icon FROM icons WHERE url GLOB ? LIMIT 1"); query.addBindValue(QString("*%1*").arg(urlString)); query.exec(); if (query.next()) return QImage::fromData(query.value(0).toByteArray()); return allowNull ? QImage() : Application::getAppIcon("webpage").pixmap(16).toImage(); } IconProvider *IconProvider::instance() { return sn_icon_provider(); } void IconProvider::save() { foreach(const BufferedIcon &ic, m_iconBuffer) { QSqlQuery query{SqlDatabase::instance()->database()}; query.prepare("SELECT id FROM icons WHERE url = ?"); query.bindValue(0, encodeUrl(ic.first)); query.exec(); if (query.next()) query.prepare("UPDATE icons SET icon = ? WHERE url = ?"); else query.prepare("INSERT INTO icons (icon, url) VALUES (?,?)"); QByteArray ba{}; QBuffer buffer(&ba); buffer.open(QIODevice::WriteOnly); ic.second.save(&buffer, "PNG"); query.bindValue(0, buffer.data()); query.bindValue(1, QString::fromUtf8(encodeUrl(ic.first))); query.exec(); } m_iconBuffer.clear(); } QIcon IconProvider::iconFromImage(const QImage& image) { return QIcon(QPixmap::fromImage(image)); } } <|endoftext|>
<commit_before>/* Copyright (c) 2003, Arvid Norberg 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 author 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. */ #include "libtorrent/pch.hpp" #include <vector> #include <iostream> #include <cctype> #include <iomanip> #include <sstream> #include <algorithm> #include "libtorrent/config.hpp" #include "libtorrent/gzip.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/bind.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/tracker_manager.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/http_connection.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/io.hpp" #include "libtorrent/socket.hpp" using namespace libtorrent; using boost::bind; namespace libtorrent { http_tracker_connection::http_tracker_connection( io_service& ios , connection_queue& cc , tracker_manager& man , tracker_request const& req , address bind_infc , boost::weak_ptr<request_callback> c , session_settings const& stn , proxy_settings const& ps , std::string const& auth) : tracker_connection(man, req, ios, bind_infc, c) , m_man(man) , m_settings(stn) , m_bind_iface(bind_infc) , m_ps(ps) , m_cc(cc) , m_ios(ios) {} void http_tracker_connection::start() { // TODO: authentication std::string url = tracker_req().url; if (tracker_req().kind == tracker_request::scrape_request) { // find and replace "announce" with "scrape" // in request std::size_t pos = url.find("announce"); if (pos == std::string::npos) { fail(-1, ("scrape is not available on url: '" + tracker_req().url +"'").c_str()); return; } url.replace(pos, 8, "scrape"); } // if request-string already contains // some parameters, append an ampersand instead // of a question mark size_t arguments_start = url.find('?'); if (arguments_start != std::string::npos) url += "&"; else url += "?"; url += "info_hash="; url += escape_string( reinterpret_cast<const char*>(tracker_req().info_hash.begin()), 20); if (tracker_req().kind == tracker_request::announce_request) { url += "&peer_id="; url += escape_string( reinterpret_cast<const char*>(tracker_req().pid.begin()), 20); url += "&port="; url += boost::lexical_cast<std::string>(tracker_req().listen_port); url += "&uploaded="; url += boost::lexical_cast<std::string>(tracker_req().uploaded); url += "&downloaded="; url += boost::lexical_cast<std::string>(tracker_req().downloaded); url += "&left="; url += boost::lexical_cast<std::string>(tracker_req().left); if (tracker_req().event != tracker_request::none) { const char* event_string[] = {"completed", "started", "stopped"}; url += "&event="; url += event_string[tracker_req().event - 1]; } url += "&key="; std::stringstream key_string; key_string << std::hex << tracker_req().key; url += key_string.str(); url += "&compact=1"; url += "&numwant="; url += boost::lexical_cast<std::string>( (std::min)(tracker_req().num_want, 999)); if (m_settings.announce_ip != address()) { url += "&ip="; url += m_settings.announce_ip.to_string(); } #ifndef TORRENT_DISABLE_ENCRYPTION url += "&supportcrypto=1"; #endif url += "&ipv6="; url += tracker_req().ipv6; // extension that tells the tracker that // we don't need any peer_id's in the response url += "&no_peer_id=1"; } m_tracker_connection.reset(new http_connection(m_ios, m_cc , boost::bind(&http_tracker_connection::on_response, self(), _1, _2, _3, _4))); int timeout = tracker_req().event==tracker_request::stopped ?m_settings.stop_tracker_timeout :m_settings.tracker_completion_timeout; m_tracker_connection->get(url, seconds(timeout) , 1, &m_ps, 5, m_settings.user_agent, m_bind_iface); #if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING) boost::shared_ptr<request_callback> cb = requester(); if (cb) { cb->debug_log("==> TRACKER_REQUEST [ url: " + url + " ]"); } #endif } void http_tracker_connection::close() { if (m_tracker_connection) { m_tracker_connection->close(); m_tracker_connection.reset(); } tracker_connection::close(); } void http_tracker_connection::on_response(error_code const& ec , http_parser const& parser, char const* data, int size) { // keep this alive boost::intrusive_ptr<http_tracker_connection> me(this); if (ec && ec != asio::error::eof) { fail(-1, ec.message().c_str()); return; } if (!parser.header_finished()) { fail(-1, "premature end of file"); return; } if (parser.status_code() != 200) { fail(parser.status_code(), parser.message().c_str()); return; } if (ec && ec != asio::error::eof) { fail(parser.status_code(), ec.message().c_str()); return; } // handle tracker response entry e; e = bdecode(data, data + size); if (e.type() != entry::undefined_t) { parse(parser.status_code(), e); } else { std::string error_str("invalid bencoding of tracker response: \""); for (char const* i = data, *end(data + size); i != end; ++i) { if (std::isprint(*i)) error_str += *i; else error_str += "0x" + boost::lexical_cast<std::string>((unsigned int)*i) + " "; } error_str += "\""; fail(parser.status_code(), error_str.c_str()); } close(); } bool http_tracker_connection::extract_peer_info(const entry& info, peer_entry& ret) { // extract peer id (if any) if (info.type() != entry::dictionary_t) { fail(-1, "invalid response from tracker (invalid peer entry)"); return false; } entry const* i = info.find_key("peer id"); if (i != 0) { if (i->type() != entry::string_t || i->string().length() != 20) { fail(-1, "invalid response from tracker (invalid peer id)"); return false; } std::copy(i->string().begin(), i->string().end(), ret.pid.begin()); } else { // if there's no peer_id, just initialize it to a bunch of zeroes std::fill_n(ret.pid.begin(), 20, 0); } // extract ip i = info.find_key("ip"); if (i == 0 || i->type() != entry::string_t) { fail(-1, "invalid response from tracker"); return false; } ret.ip = i->string(); // extract port i = info.find_key("port"); if (i == 0 || i->type() != entry::int_t) { fail(-1, "invalid response from tracker"); return false; } ret.port = (unsigned short)i->integer(); return true; } void http_tracker_connection::parse(int status_code, entry const& e) { boost::shared_ptr<request_callback> cb = requester(); if (!cb) return; // parse the response entry const* failure = e.find_key("failure reason"); if (failure && failure->type() == entry::string_t) { fail(status_code, failure->string().c_str()); return; } entry const* warning = e.find_key("warning message"); if (warning && warning->type() == entry::string_t) { cb->tracker_warning(tracker_req(), warning->string()); } std::vector<peer_entry> peer_list; if (tracker_req().kind == tracker_request::scrape_request) { std::string ih = tracker_req().info_hash.to_string(); entry const* files = e.find_key("files"); if (files == 0 || files->type() != entry::dictionary_t) { fail(-1, "invalid or missing 'files' entry in scrape response"); return; } entry const* scrape_data = files->find_key(ih); if (scrape_data == 0 || scrape_data->type() != entry::dictionary_t) { fail(-1, "missing or invalid info-hash entry in scrape response"); return; } entry const* complete = scrape_data->find_key("complete"); entry const* incomplete = scrape_data->find_key("incomplete"); entry const* downloaded = scrape_data->find_key("downloaded"); if (complete == 0 || incomplete == 0 || downloaded == 0 || complete->type() != entry::int_t || incomplete->type() != entry::int_t || downloaded->type() != entry::int_t) { fail(-1, "missing 'complete' or 'incomplete' entries in scrape response"); return; } cb->tracker_scrape_response(tracker_req(), int(complete->integer()) , int(incomplete->integer()), int(downloaded->integer())); return; } entry const* interval = e.find_key("interval"); if (interval == 0 || interval->type() != entry::int_t) { fail(-1, "missing or invalid 'interval' entry in tracker response"); return; } entry const* peers_ent = e.find_key("peers"); if (peers_ent == 0) { fail(-1, "missing 'peers' entry in tracker response"); return; } if (peers_ent->type() == entry::string_t) { std::string const& peers = peers_ent->string(); for (std::string::const_iterator i = peers.begin(); i != peers.end();) { if (std::distance(i, peers.end()) < 6) break; peer_entry p; p.pid.clear(); p.ip = detail::read_v4_address(i).to_string(); p.port = detail::read_uint16(i); peer_list.push_back(p); } } else if (peers_ent->type() == entry::list_t) { entry::list_type const& l = peers_ent->list(); for(entry::list_type::const_iterator i = l.begin(); i != l.end(); ++i) { peer_entry p; if (!extract_peer_info(*i, p)) return; peer_list.push_back(p); } } else { fail(-1, "invalid 'peers' entry in tracker response"); return; } entry const* ipv6_peers = e.find_key("peers6"); if (ipv6_peers && ipv6_peers->type() == entry::string_t) { std::string const& peers = ipv6_peers->string(); for (std::string::const_iterator i = peers.begin(); i != peers.end();) { if (std::distance(i, peers.end()) < 18) break; peer_entry p; p.pid.clear(); p.ip = detail::read_v6_address(i).to_string(); p.port = detail::read_uint16(i); peer_list.push_back(p); } } // look for optional scrape info int complete = -1; int incomplete = -1; address external_ip; entry const* ip_ent = e.find_key("external ip"); if (ip_ent && ip_ent->type() == entry::string_t) { std::string const& ip = ip_ent->string(); char const* p = &ip[0]; if (ip.size() == address_v4::bytes_type::static_size) external_ip = detail::read_v4_address(p); else if (ip.size() == address_v6::bytes_type::static_size) external_ip = detail::read_v6_address(p); } entry const* complete_ent = e.find_key("complete"); if (complete_ent && complete_ent->type() == entry::int_t) complete = int(complete_ent->integer()); entry const* incomplete_ent = e.find_key("incomplete"); if (incomplete_ent && incomplete_ent->type() == entry::int_t) incomplete = int(incomplete_ent->integer()); cb->tracker_response(tracker_req(), peer_list, interval->integer(), complete , incomplete, external_ip); } } <commit_msg>fixes bencode type check on tracker responses. Might fix #398<commit_after>/* Copyright (c) 2003, Arvid Norberg 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 author 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. */ #include "libtorrent/pch.hpp" #include <vector> #include <iostream> #include <cctype> #include <iomanip> #include <sstream> #include <algorithm> #include "libtorrent/config.hpp" #include "libtorrent/gzip.hpp" #ifdef _MSC_VER #pragma warning(push, 1) #endif #include <boost/bind.hpp> #ifdef _MSC_VER #pragma warning(pop) #endif #include "libtorrent/tracker_manager.hpp" #include "libtorrent/http_tracker_connection.hpp" #include "libtorrent/http_connection.hpp" #include "libtorrent/entry.hpp" #include "libtorrent/bencode.hpp" #include "libtorrent/torrent.hpp" #include "libtorrent/io.hpp" #include "libtorrent/socket.hpp" using namespace libtorrent; using boost::bind; namespace libtorrent { http_tracker_connection::http_tracker_connection( io_service& ios , connection_queue& cc , tracker_manager& man , tracker_request const& req , address bind_infc , boost::weak_ptr<request_callback> c , session_settings const& stn , proxy_settings const& ps , std::string const& auth) : tracker_connection(man, req, ios, bind_infc, c) , m_man(man) , m_settings(stn) , m_bind_iface(bind_infc) , m_ps(ps) , m_cc(cc) , m_ios(ios) {} void http_tracker_connection::start() { // TODO: authentication std::string url = tracker_req().url; if (tracker_req().kind == tracker_request::scrape_request) { // find and replace "announce" with "scrape" // in request std::size_t pos = url.find("announce"); if (pos == std::string::npos) { fail(-1, ("scrape is not available on url: '" + tracker_req().url +"'").c_str()); return; } url.replace(pos, 8, "scrape"); } // if request-string already contains // some parameters, append an ampersand instead // of a question mark size_t arguments_start = url.find('?'); if (arguments_start != std::string::npos) url += "&"; else url += "?"; url += "info_hash="; url += escape_string( reinterpret_cast<const char*>(tracker_req().info_hash.begin()), 20); if (tracker_req().kind == tracker_request::announce_request) { url += "&peer_id="; url += escape_string( reinterpret_cast<const char*>(tracker_req().pid.begin()), 20); url += "&port="; url += boost::lexical_cast<std::string>(tracker_req().listen_port); url += "&uploaded="; url += boost::lexical_cast<std::string>(tracker_req().uploaded); url += "&downloaded="; url += boost::lexical_cast<std::string>(tracker_req().downloaded); url += "&left="; url += boost::lexical_cast<std::string>(tracker_req().left); if (tracker_req().event != tracker_request::none) { const char* event_string[] = {"completed", "started", "stopped"}; url += "&event="; url += event_string[tracker_req().event - 1]; } url += "&key="; std::stringstream key_string; key_string << std::hex << tracker_req().key; url += key_string.str(); url += "&compact=1"; url += "&numwant="; url += boost::lexical_cast<std::string>( (std::min)(tracker_req().num_want, 999)); if (m_settings.announce_ip != address()) { url += "&ip="; url += m_settings.announce_ip.to_string(); } #ifndef TORRENT_DISABLE_ENCRYPTION url += "&supportcrypto=1"; #endif url += "&ipv6="; url += tracker_req().ipv6; // extension that tells the tracker that // we don't need any peer_id's in the response url += "&no_peer_id=1"; } m_tracker_connection.reset(new http_connection(m_ios, m_cc , boost::bind(&http_tracker_connection::on_response, self(), _1, _2, _3, _4))); int timeout = tracker_req().event==tracker_request::stopped ?m_settings.stop_tracker_timeout :m_settings.tracker_completion_timeout; m_tracker_connection->get(url, seconds(timeout) , 1, &m_ps, 5, m_settings.user_agent, m_bind_iface); #if defined(TORRENT_VERBOSE_LOGGING) || defined(TORRENT_LOGGING) boost::shared_ptr<request_callback> cb = requester(); if (cb) { cb->debug_log("==> TRACKER_REQUEST [ url: " + url + " ]"); } #endif } void http_tracker_connection::close() { if (m_tracker_connection) { m_tracker_connection->close(); m_tracker_connection.reset(); } tracker_connection::close(); } void http_tracker_connection::on_response(error_code const& ec , http_parser const& parser, char const* data, int size) { // keep this alive boost::intrusive_ptr<http_tracker_connection> me(this); if (ec && ec != asio::error::eof) { fail(-1, ec.message().c_str()); return; } if (!parser.header_finished()) { fail(-1, "premature end of file"); return; } if (parser.status_code() != 200) { fail(parser.status_code(), parser.message().c_str()); return; } if (ec && ec != asio::error::eof) { fail(parser.status_code(), ec.message().c_str()); return; } // handle tracker response entry e; e = bdecode(data, data + size); if (e.type() == entry::dictionary_t) { parse(parser.status_code(), e); } else { std::string error_str("invalid bencoding of tracker response: \""); for (char const* i = data, *end(data + size); i != end; ++i) { if (std::isprint(*i)) error_str += *i; else error_str += "0x" + boost::lexical_cast<std::string>((unsigned int)*i) + " "; } error_str += "\""; fail(parser.status_code(), error_str.c_str()); } close(); } bool http_tracker_connection::extract_peer_info(const entry& info, peer_entry& ret) { // extract peer id (if any) if (info.type() != entry::dictionary_t) { fail(-1, "invalid response from tracker (invalid peer entry)"); return false; } entry const* i = info.find_key("peer id"); if (i != 0) { if (i->type() != entry::string_t || i->string().length() != 20) { fail(-1, "invalid response from tracker (invalid peer id)"); return false; } std::copy(i->string().begin(), i->string().end(), ret.pid.begin()); } else { // if there's no peer_id, just initialize it to a bunch of zeroes std::fill_n(ret.pid.begin(), 20, 0); } // extract ip i = info.find_key("ip"); if (i == 0 || i->type() != entry::string_t) { fail(-1, "invalid response from tracker"); return false; } ret.ip = i->string(); // extract port i = info.find_key("port"); if (i == 0 || i->type() != entry::int_t) { fail(-1, "invalid response from tracker"); return false; } ret.port = (unsigned short)i->integer(); return true; } void http_tracker_connection::parse(int status_code, entry const& e) { boost::shared_ptr<request_callback> cb = requester(); if (!cb) return; // parse the response entry const* failure = e.find_key("failure reason"); if (failure && failure->type() == entry::string_t) { fail(status_code, failure->string().c_str()); return; } entry const* warning = e.find_key("warning message"); if (warning && warning->type() == entry::string_t) { cb->tracker_warning(tracker_req(), warning->string()); } std::vector<peer_entry> peer_list; if (tracker_req().kind == tracker_request::scrape_request) { std::string ih = tracker_req().info_hash.to_string(); entry const* files = e.find_key("files"); if (files == 0 || files->type() != entry::dictionary_t) { fail(-1, "invalid or missing 'files' entry in scrape response"); return; } entry const* scrape_data = files->find_key(ih); if (scrape_data == 0 || scrape_data->type() != entry::dictionary_t) { fail(-1, "missing or invalid info-hash entry in scrape response"); return; } entry const* complete = scrape_data->find_key("complete"); entry const* incomplete = scrape_data->find_key("incomplete"); entry const* downloaded = scrape_data->find_key("downloaded"); if (complete == 0 || incomplete == 0 || downloaded == 0 || complete->type() != entry::int_t || incomplete->type() != entry::int_t || downloaded->type() != entry::int_t) { fail(-1, "missing 'complete' or 'incomplete' entries in scrape response"); return; } cb->tracker_scrape_response(tracker_req(), int(complete->integer()) , int(incomplete->integer()), int(downloaded->integer())); return; } entry const* interval = e.find_key("interval"); if (interval == 0 || interval->type() != entry::int_t) { fail(-1, "missing or invalid 'interval' entry in tracker response"); return; } entry const* peers_ent = e.find_key("peers"); if (peers_ent == 0) { fail(-1, "missing 'peers' entry in tracker response"); return; } if (peers_ent->type() == entry::string_t) { std::string const& peers = peers_ent->string(); for (std::string::const_iterator i = peers.begin(); i != peers.end();) { if (std::distance(i, peers.end()) < 6) break; peer_entry p; p.pid.clear(); p.ip = detail::read_v4_address(i).to_string(); p.port = detail::read_uint16(i); peer_list.push_back(p); } } else if (peers_ent->type() == entry::list_t) { entry::list_type const& l = peers_ent->list(); for(entry::list_type::const_iterator i = l.begin(); i != l.end(); ++i) { peer_entry p; if (!extract_peer_info(*i, p)) return; peer_list.push_back(p); } } else { fail(-1, "invalid 'peers' entry in tracker response"); return; } entry const* ipv6_peers = e.find_key("peers6"); if (ipv6_peers && ipv6_peers->type() == entry::string_t) { std::string const& peers = ipv6_peers->string(); for (std::string::const_iterator i = peers.begin(); i != peers.end();) { if (std::distance(i, peers.end()) < 18) break; peer_entry p; p.pid.clear(); p.ip = detail::read_v6_address(i).to_string(); p.port = detail::read_uint16(i); peer_list.push_back(p); } } // look for optional scrape info int complete = -1; int incomplete = -1; address external_ip; entry const* ip_ent = e.find_key("external ip"); if (ip_ent && ip_ent->type() == entry::string_t) { std::string const& ip = ip_ent->string(); char const* p = &ip[0]; if (ip.size() == address_v4::bytes_type::static_size) external_ip = detail::read_v4_address(p); else if (ip.size() == address_v6::bytes_type::static_size) external_ip = detail::read_v6_address(p); } entry const* complete_ent = e.find_key("complete"); if (complete_ent && complete_ent->type() == entry::int_t) complete = int(complete_ent->integer()); entry const* incomplete_ent = e.find_key("incomplete"); if (incomplete_ent && incomplete_ent->type() == entry::int_t) incomplete = int(incomplete_ent->integer()); cb->tracker_response(tracker_req(), peer_list, interval->integer(), complete , incomplete, external_ip); } } <|endoftext|>
<commit_before>/** * This file is part of the CernVM File System. */ #include "upload_gateway.h" #include <limits> #include <vector> #include "file_processing/char_buffer.h" #include "util/string.h" namespace upload { GatewayStreamHandle::GatewayStreamHandle(const CallbackTN* commit_callback, ObjectPack::BucketHandle bkt) : UploadStreamHandle(commit_callback), bucket(bkt) {} bool GatewayUploader::WillHandle(const SpoolerDefinition& spooler_definition) { return spooler_definition.driver_type == SpoolerDefinition::Gateway; } bool GatewayUploader::ParseSpoolerDefinition( const SpoolerDefinition& spooler_definition, GatewayUploader::Config* config) { const std::string& config_string = spooler_definition.spooler_configuration; if (!config) { LogCvmfs(kLogUploadGateway, kLogStderr, "\"config\" argument is NULL"); return false; } if (spooler_definition.session_token_file.empty()) { LogCvmfs(kLogUploadGateway, kLogStderr, "Failed to configure HTTP uploader. " "Missing session token file.\n"); return false; } config->session_token_file = spooler_definition.session_token_file; // Repo address, e.g. http://my.repo.address config->api_url = config_string; return true; } GatewayUploader::GatewayUploader(const SpoolerDefinition& spooler_definition) : AbstractUploader(spooler_definition), config_(), session_context_(new SessionContext()) { assert(spooler_definition.IsValid() && spooler_definition.driver_type == SpoolerDefinition::Gateway); if (!ParseSpoolerDefinition(spooler_definition, &config_)) { abort(); } atomic_init32(&num_errors_); LogCvmfs(kLogUploadGateway, kLogStderr, "HTTP uploader configuration:\n" " API URL: %s\n" " Session token file: %s\n", config_.api_url.c_str(), config_.session_token_file.c_str()); } GatewayUploader::~GatewayUploader() { if (session_context_) { delete session_context_; } } bool GatewayUploader::Initialize() { if (!AbstractUploader::Initialize()) { return false; } std::string session_token; if (!ReadSessionTokenFile(config_.session_token_file, &session_token)) { return false; } return session_context_->Initialize(config_.api_url, session_token); } bool GatewayUploader::FinalizeSession() { return session_context_->Finalize(); } void GatewayUploader::WaitForUpload() const { session_context_->WaitForUpload(); } std::string GatewayUploader::name() const { return "HTTP"; } bool GatewayUploader::Remove(const std::string& /*file_to_delete*/) { return false; } bool GatewayUploader::Peek(const std::string& /*path*/) const { return false; } bool GatewayUploader::PlaceBootstrappingShortcut( const shash::Any& /*object*/) const { return false; } unsigned int GatewayUploader::GetNumberOfErrors() const { return atomic_read32(&num_errors_); } void GatewayUploader::FileUpload(const std::string& local_path, const std::string& remote_path, const CallbackTN* callback) { UniquePtr<GatewayStreamHandle> handle( new GatewayStreamHandle(callback, session_context_->NewBucket())); FILE* local_file = fopen(local_path.c_str(), "rb"); if (!local_file) { LogCvmfs(kLogUploadGateway, kLogStderr, "File upload - could not open local file."); BumpErrors(); Respond(callback, UploaderResults(1, local_path)); return; } std::vector<char> buf(1024); size_t read_bytes = 0; do { read_bytes = fread(&buf[0], buf.size(), 1, local_file); ObjectPack::AddToBucket(&buf[0], buf.size(), handle->bucket); } while (read_bytes == buf.size()); fclose(local_file); shash::Any content_hash(shash::kSha1); shash::HashFile(local_path, &content_hash); if (!session_context_->CommitBucket(ObjectPack::kNamed, content_hash, handle->bucket, remote_path)) { LogCvmfs(kLogUploadGateway, kLogStderr, "File upload - could not commit bucket"); BumpErrors(); Respond(handle->commit_callback, UploaderResults(2, local_path)); return; } Respond(callback, UploaderResults(0, local_path)); } UploadStreamHandle* GatewayUploader::InitStreamedUpload( const CallbackTN* callback) { return new GatewayStreamHandle(callback, session_context_->NewBucket()); } void GatewayUploader::StreamedUpload(UploadStreamHandle* handle, CharBuffer* buffer, const CallbackTN* callback) { if (!buffer->IsInitialized()) { LogCvmfs(kLogUploadGateway, kLogStderr, "Streamed upload - input buffer is not initialized"); BumpErrors(); Respond(callback, UploaderResults(1, buffer)); return; } GatewayStreamHandle* hd = dynamic_cast<GatewayStreamHandle*>(handle); if (!hd) { LogCvmfs(kLogUploadGateway, kLogStderr, "Streamed upload - incompatible upload handle"); BumpErrors(); Respond(callback, UploaderResults(2, buffer)); return; } ObjectPack::AddToBucket(buffer->ptr(), buffer->used_bytes(), hd->bucket); Respond(callback, UploaderResults(0, buffer)); } void GatewayUploader::FinalizeStreamedUpload(UploadStreamHandle* handle, const shash::Any& content_hash) { GatewayStreamHandle* hd = dynamic_cast<GatewayStreamHandle*>(handle); if (!hd) { LogCvmfs(kLogUploadGateway, kLogStderr, "Finalize streamed upload - incompatible upload handle"); BumpErrors(); Respond(handle->commit_callback, UploaderResults(2)); return; } if (!session_context_->CommitBucket(ObjectPack::kCas, content_hash, hd->bucket, "")) { LogCvmfs(kLogUploadGateway, kLogStderr, "Finalize streamed upload - could not commit bucket"); BumpErrors(); Respond(handle->commit_callback, UploaderResults(4)); return; } Respond(handle->commit_callback, UploaderResults(0)); } bool GatewayUploader::ReadSessionTokenFile(const std::string& token_file_name, std::string* token) { if (!token) { return false; } FILE* token_file = std::fopen(token_file_name.c_str(), "r"); if (!token_file) { LogCvmfs(kLogUploadGateway, kLogStderr, "HTTP Uploader - Could not open session token " "file. Aborting."); return false; } return GetLineFile(token_file, token); } void GatewayUploader::BumpErrors() const { atomic_inc32(&num_errors_); } } // namespace upload <commit_msg>GatewayUploader::FileUpload - use hash algorithm from spooler def<commit_after>/** * This file is part of the CernVM File System. */ #include "upload_gateway.h" #include <limits> #include <vector> #include "file_processing/char_buffer.h" #include "util/string.h" namespace upload { GatewayStreamHandle::GatewayStreamHandle(const CallbackTN* commit_callback, ObjectPack::BucketHandle bkt) : UploadStreamHandle(commit_callback), bucket(bkt) {} bool GatewayUploader::WillHandle(const SpoolerDefinition& spooler_definition) { return spooler_definition.driver_type == SpoolerDefinition::Gateway; } bool GatewayUploader::ParseSpoolerDefinition( const SpoolerDefinition& spooler_definition, GatewayUploader::Config* config) { const std::string& config_string = spooler_definition.spooler_configuration; if (!config) { LogCvmfs(kLogUploadGateway, kLogStderr, "\"config\" argument is NULL"); return false; } if (spooler_definition.session_token_file.empty()) { LogCvmfs(kLogUploadGateway, kLogStderr, "Failed to configure HTTP uploader. " "Missing session token file.\n"); return false; } config->session_token_file = spooler_definition.session_token_file; // Repo address, e.g. http://my.repo.address config->api_url = config_string; return true; } GatewayUploader::GatewayUploader(const SpoolerDefinition& spooler_definition) : AbstractUploader(spooler_definition), config_(), session_context_(new SessionContext()) { assert(spooler_definition.IsValid() && spooler_definition.driver_type == SpoolerDefinition::Gateway); if (!ParseSpoolerDefinition(spooler_definition, &config_)) { abort(); } atomic_init32(&num_errors_); LogCvmfs(kLogUploadGateway, kLogStderr, "HTTP uploader configuration:\n" " API URL: %s\n" " Session token file: %s\n", config_.api_url.c_str(), config_.session_token_file.c_str()); } GatewayUploader::~GatewayUploader() { if (session_context_) { delete session_context_; } } bool GatewayUploader::Initialize() { if (!AbstractUploader::Initialize()) { return false; } std::string session_token; if (!ReadSessionTokenFile(config_.session_token_file, &session_token)) { return false; } return session_context_->Initialize(config_.api_url, session_token); } bool GatewayUploader::FinalizeSession() { return session_context_->Finalize(); } void GatewayUploader::WaitForUpload() const { session_context_->WaitForUpload(); } std::string GatewayUploader::name() const { return "HTTP"; } bool GatewayUploader::Remove(const std::string& /*file_to_delete*/) { return false; } bool GatewayUploader::Peek(const std::string& /*path*/) const { return false; } bool GatewayUploader::PlaceBootstrappingShortcut( const shash::Any& /*object*/) const { return false; } unsigned int GatewayUploader::GetNumberOfErrors() const { return atomic_read32(&num_errors_); } void GatewayUploader::FileUpload(const std::string& local_path, const std::string& remote_path, const CallbackTN* callback) { UniquePtr<GatewayStreamHandle> handle( new GatewayStreamHandle(callback, session_context_->NewBucket())); FILE* local_file = fopen(local_path.c_str(), "rb"); if (!local_file) { LogCvmfs(kLogUploadGateway, kLogStderr, "File upload - could not open local file."); BumpErrors(); Respond(callback, UploaderResults(1, local_path)); return; } std::vector<char> buf(1024); size_t read_bytes = 0; do { read_bytes = fread(&buf[0], buf.size(), 1, local_file); ObjectPack::AddToBucket(&buf[0], buf.size(), handle->bucket); } while (read_bytes == buf.size()); fclose(local_file); shash::Any content_hash(spooler_definition().hash_algorithm); shash::HashFile(local_path, &content_hash); if (!session_context_->CommitBucket(ObjectPack::kNamed, content_hash, handle->bucket, remote_path)) { LogCvmfs(kLogUploadGateway, kLogStderr, "File upload - could not commit bucket"); BumpErrors(); Respond(handle->commit_callback, UploaderResults(2, local_path)); return; } Respond(callback, UploaderResults(0, local_path)); } UploadStreamHandle* GatewayUploader::InitStreamedUpload( const CallbackTN* callback) { return new GatewayStreamHandle(callback, session_context_->NewBucket()); } void GatewayUploader::StreamedUpload(UploadStreamHandle* handle, CharBuffer* buffer, const CallbackTN* callback) { if (!buffer->IsInitialized()) { LogCvmfs(kLogUploadGateway, kLogStderr, "Streamed upload - input buffer is not initialized"); BumpErrors(); Respond(callback, UploaderResults(1, buffer)); return; } GatewayStreamHandle* hd = dynamic_cast<GatewayStreamHandle*>(handle); if (!hd) { LogCvmfs(kLogUploadGateway, kLogStderr, "Streamed upload - incompatible upload handle"); BumpErrors(); Respond(callback, UploaderResults(2, buffer)); return; } ObjectPack::AddToBucket(buffer->ptr(), buffer->used_bytes(), hd->bucket); Respond(callback, UploaderResults(0, buffer)); } void GatewayUploader::FinalizeStreamedUpload(UploadStreamHandle* handle, const shash::Any& content_hash) { GatewayStreamHandle* hd = dynamic_cast<GatewayStreamHandle*>(handle); if (!hd) { LogCvmfs(kLogUploadGateway, kLogStderr, "Finalize streamed upload - incompatible upload handle"); BumpErrors(); Respond(handle->commit_callback, UploaderResults(2)); return; } if (!session_context_->CommitBucket(ObjectPack::kCas, content_hash, hd->bucket, "")) { LogCvmfs(kLogUploadGateway, kLogStderr, "Finalize streamed upload - could not commit bucket"); BumpErrors(); Respond(handle->commit_callback, UploaderResults(4)); return; } Respond(handle->commit_callback, UploaderResults(0)); } bool GatewayUploader::ReadSessionTokenFile(const std::string& token_file_name, std::string* token) { if (!token) { return false; } FILE* token_file = std::fopen(token_file_name.c_str(), "r"); if (!token_file) { LogCvmfs(kLogUploadGateway, kLogStderr, "HTTP Uploader - Could not open session token " "file. Aborting."); return false; } return GetLineFile(token_file, token); } void GatewayUploader::BumpErrors() const { atomic_inc32(&num_errors_); } } // namespace upload <|endoftext|>
<commit_before>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <deque> #include "catch.hpp" #include "dll/dense_layer.hpp" #include "dll/dbn.hpp" #include "dll/dense_stochastic_gradient_descent.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" namespace { template<typename Dataset> void mnist_scale(Dataset& dataset){ for(auto& image : dataset.training_images){ for(auto& pixel : image){ pixel *= (1.0 / 256.0); } } for(auto& image : dataset.test_images){ for(auto& pixel : image){ pixel *= (1.0 / 256.0); } } } } //end of anonymous namespace TEST_CASE( "dense/sgd/1", "[dense][dbn][mnist][sgd]" ) { typedef dll::dbn_desc< dll::dbn_layers< dll::dense_desc<28 * 28, 100>::layer_t, dll::dense_desc<100, 10>::layer_t >, dll::trainer<dll::dense_sgd_trainer> >::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000); REQUIRE(!dataset.training_images.empty()); auto dbn = std::make_unique<dbn_t>(); dbn->learning_rate = 0.05; auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } TEST_CASE( "dense/sgd/2", "[dense][dbn][mnist][sgd]" ) { typedef dll::dbn_desc< dll::dbn_layers< dll::dense_desc<28 * 28, 100, dll::activation<dll::function::TANH>>::layer_t, dll::dense_desc<100, 10, dll::activation<dll::function::TANH>>::layer_t >, dll::trainer<dll::dense_sgd_trainer> >::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000); REQUIRE(!dataset.training_images.empty()); mnist_scale(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->learning_rate = 0.05; auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } TEST_CASE( "dense/sgd/3", "[dense][dbn][mnist][sgd]" ) { typedef dll::dbn_desc< dll::dbn_layers< dll::dense_desc<28 * 28, 100>::layer_t, dll::dense_desc<100, 10>::layer_t > , dll::momentum , dll::trainer<dll::dense_sgd_trainer> >::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000); REQUIRE(!dataset.training_images.empty()); mnist_scale(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->initial_momentum = 0.9; dbn->final_momentum = 0.9; dbn->learning_rate = 0.01; auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } TEST_CASE( "dense/sgd/4", "[dense][dbn][mnist][sgd]" ) { typedef dll::dbn_desc< dll::dbn_layers< dll::dense_desc<28 * 28, 100>::layer_t, dll::dense_desc<100, 10>::layer_t > , dll::momentum , dll::weight_decay<> , dll::trainer<dll::dense_sgd_trainer> >::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000); REQUIRE(!dataset.training_images.empty()); mnist_scale(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->initial_momentum = 0.9; dbn->final_momentum = 0.9; dbn->learning_rate = 0.01; auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } TEST_CASE( "dense/sgd/5", "[dense][dbn][mnist][sgd]" ) { typedef dll::dbn_desc< dll::dbn_layers< dll::dense_desc<28 * 28, 100, dll::activation<dll::function::TANH>>::layer_t, dll::dense_desc<100, 10, dll::activation<dll::function::TANH>>::layer_t > , dll::momentum , dll::weight_decay<> , dll::trainer<dll::dense_sgd_trainer> >::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000); REQUIRE(!dataset.training_images.empty()); mnist_scale(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->initial_momentum = 0.9; dbn->final_momentum = 0.9; dbn->learning_rate = 0.01; auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } <commit_msg>Test with identity function<commit_after>//======================================================================= // Copyright (c) 2014-2015 Baptiste Wicht // Distributed under the terms of the MIT License. // (See accompanying file LICENSE or copy at // http://opensource.org/licenses/MIT) //======================================================================= #include <deque> #include "catch.hpp" #include "dll/dense_layer.hpp" #include "dll/dbn.hpp" #include "dll/dense_stochastic_gradient_descent.hpp" #include "mnist/mnist_reader.hpp" #include "mnist/mnist_utils.hpp" namespace { template<typename Dataset> void mnist_scale(Dataset& dataset){ for(auto& image : dataset.training_images){ for(auto& pixel : image){ pixel *= (1.0 / 256.0); } } for(auto& image : dataset.test_images){ for(auto& pixel : image){ pixel *= (1.0 / 256.0); } } } } //end of anonymous namespace TEST_CASE( "dense/sgd/1", "[dense][dbn][mnist][sgd]" ) { typedef dll::dbn_desc< dll::dbn_layers< dll::dense_desc<28 * 28, 100>::layer_t, dll::dense_desc<100, 10>::layer_t >, dll::trainer<dll::dense_sgd_trainer> >::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000); REQUIRE(!dataset.training_images.empty()); auto dbn = std::make_unique<dbn_t>(); dbn->learning_rate = 0.05; auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } TEST_CASE( "dense/sgd/2", "[dense][dbn][mnist][sgd]" ) { typedef dll::dbn_desc< dll::dbn_layers< dll::dense_desc<28 * 28, 100, dll::activation<dll::function::TANH>>::layer_t, dll::dense_desc<100, 10, dll::activation<dll::function::TANH>>::layer_t >, dll::trainer<dll::dense_sgd_trainer> >::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000); REQUIRE(!dataset.training_images.empty()); mnist_scale(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->learning_rate = 0.05; auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } TEST_CASE( "dense/sgd/3", "[dense][dbn][mnist][sgd]" ) { typedef dll::dbn_desc< dll::dbn_layers< dll::dense_desc<28 * 28, 100>::layer_t, dll::dense_desc<100, 10>::layer_t > , dll::momentum , dll::trainer<dll::dense_sgd_trainer> >::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000); REQUIRE(!dataset.training_images.empty()); mnist_scale(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->initial_momentum = 0.9; dbn->final_momentum = 0.9; dbn->learning_rate = 0.01; auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } TEST_CASE( "dense/sgd/4", "[dense][dbn][mnist][sgd]" ) { typedef dll::dbn_desc< dll::dbn_layers< dll::dense_desc<28 * 28, 100>::layer_t, dll::dense_desc<100, 10>::layer_t > , dll::momentum , dll::weight_decay<> , dll::trainer<dll::dense_sgd_trainer> >::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000); REQUIRE(!dataset.training_images.empty()); mnist_scale(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->initial_momentum = 0.9; dbn->final_momentum = 0.9; dbn->learning_rate = 0.01; auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } TEST_CASE( "dense/sgd/5", "[dense][dbn][mnist][sgd]" ) { typedef dll::dbn_desc< dll::dbn_layers< dll::dense_desc<28 * 28, 100, dll::activation<dll::function::TANH>>::layer_t, dll::dense_desc<100, 10, dll::activation<dll::function::TANH>>::layer_t > , dll::momentum , dll::weight_decay<> , dll::trainer<dll::dense_sgd_trainer> >::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000); REQUIRE(!dataset.training_images.empty()); mnist_scale(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->initial_momentum = 0.9; dbn->final_momentum = 0.9; dbn->learning_rate = 0.01; auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.2); } TEST_CASE( "dense/sgd/6", "[dense][dbn][mnist][sgd]" ) { typedef dll::dbn_desc< dll::dbn_layers< dll::dense_desc<28 * 28, 100, dll::activation<dll::function::IDENTITY>>::layer_t, dll::dense_desc<100, 10, dll::activation<dll::function::IDENTITY>>::layer_t > , dll::momentum , dll::weight_decay<> , dll::trainer<dll::dense_sgd_trainer> >::dbn_t dbn_t; auto dataset = mnist::read_dataset<std::vector, std::vector, double>(1000); REQUIRE(!dataset.training_images.empty()); mnist_scale(dataset); auto dbn = std::make_unique<dbn_t>(); dbn->initial_momentum = 0.9; dbn->final_momentum = 0.9; dbn->learning_rate = 0.01; auto ft_error = dbn->fine_tune(dataset.training_images, dataset.training_labels, 100, 10); std::cout << "ft_error:" << ft_error << std::endl; CHECK(ft_error < 5e-2); auto test_error = dll::test_set(dbn, dataset.test_images, dataset.test_labels, dll::predictor()); std::cout << "test_error:" << test_error << std::endl; REQUIRE(test_error < 0.4); } <|endoftext|>
<commit_before>/* * Software License Agreement (BSD License) * * Copyright (c) 2011, Willow Garage, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of Willow Garage, Inc. nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. * * $Id$ * */ #include <sensor_msgs/PointCloud2.h> #include <pcl/ros/conversions.h> #include <pcl/io/pcd_io.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #include <pcl/console/time.h> #include <pcl/common/transforms.h> #include <cmath> using namespace pcl; using namespace pcl::io; using namespace pcl::console; void printHelp (int, char **argv) { print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]); print_info (" where options are:\n"); print_info (" -trans dx,dy,dz = the translation (default: "); print_value ("%0.1f, %0.1f, %0.1f", 0, 0, 0); print_info (")\n"); print_info (" -quat w,x,y,z = rotation as quaternion\n"); print_info (" -axisangle ax,ay,az,theta = rotation in axis-angle form\n"); print_info (" -matrix v1,v2,...,v8,v9 = a 3x3 affine transform\n"); print_info (" -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\n"); print_info (" Note: If a rotation is not specified, it will default to no rotation.\n"); print_info (" If redundant or conflicting transforms are specified, then:\n"); print_info (" -axisangle will override -quat\n"); print_info (" -matrix (3x3) will take override -axisangle and -quat\n"); print_info (" -matrix (4x4) will take override all other arguments\n"); } void printElapsedTimeAndNumberOfPoints (double t, int w, int h=1) { print_info ("[done, "); print_value ("%g", t); print_info (" ms : "); print_value ("%d", w*h); print_info (" points]\n"); } bool loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud) { TicToc tt; print_highlight ("Loading "); print_value ("%s ", filename.c_str ()); tt.tic (); if (loadPCDFile (filename, cloud) < 0) return (false); printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height); print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ()); return (true); } template <typename PointT> void transformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output, Eigen::Matrix4f &tform) { transformPointCloud (input, output, tform); } template <> void transformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output, Eigen::Matrix4f &tform) { transformPointCloudWithNormals (input, output, tform); } template <> void transformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input, PointCloud<PointXYZRGBNormal> & output, Eigen::Matrix4f &tform) { transformPointCloudWithNormals (input, output, tform); } template <typename PointT> void transformPointCloud2AsType (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output, Eigen::Matrix4f &tform) { PointCloud<PointT> cloud; fromROSMsg (input, cloud); transformPointCloudHelper (cloud, cloud, tform); toROSMsg (cloud, output); } void transformPointCloud2 (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output, Eigen::Matrix4f &tform) { // Check for 'rgb' and 'normals' fields bool has_rgb = false; bool has_normals = false; for (size_t i = 0; i < input.fields.size (); ++i) { if (input.fields[i].name == "rgb") has_rgb = true; if (input.fields[i].name == "normals") has_normals = true; } // Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal if (!has_rgb && !has_normals) transformPointCloud2AsType<PointXYZ> (input, output, tform); else if (has_rgb && !has_normals) transformPointCloud2AsType<PointXYZRGB> (input, output, tform); else if (!has_rgb && has_normals) transformPointCloud2AsType<PointNormal> (input, output, tform); else // (has_rgb && has_normals) transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform); } void compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output, Eigen::Matrix4f &tform) { TicToc tt; tt.tic (); print_highlight ("Transforming "); transformPointCloud2 (*input, output, tform); printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height); } void saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output) { TicToc tt; tt.tic (); print_highlight ("Saving "); print_value ("%s ", filename.c_str ()); pcl::io::savePCDFile (filename, output); printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height); } /* ---[ */ int main (int argc, char** argv) { print_info ("Transform a cloud. For more information, use: %s -h\n", argv[0]); if (argc < 3) { printHelp (argc, argv); return (-1); } // Parse the command line arguments for .pcd files std::vector<int> p_file_indices; p_file_indices = parse_file_extension_argument (argc, argv, ".pcd"); if (p_file_indices.size () != 2) { print_error ("Need one input PCD file and one output PCD file to continue.\n"); return (-1); } // Initialize the transformation matrix Eigen::Matrix4f tform; tform.setIdentity (); // Command line parsing float dx, dy, dz; std::vector<float> values; if (parse_3x_arguments (argc, argv, "-trans", dx, dy, dz) > -1) { tform (0, 3) = dx; tform (1, 3) = dy; tform (2, 3) = dz; } if (parse_x_arguments (argc, argv, "-quat", values) > -1) { if (values.size () == 4) { const float& x = values[0]; const float& y = values[1]; const float& z = values[2]; const float& w = values[3]; tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z)); } else { print_error ("Wrong number of values given (%zu): ", values.size ()); print_error ("The quaternion specified with -quat must contain 4 elements (w,x,y,z).\n"); } } if (parse_x_arguments (argc, argv, "-axisangle", values) > -1) { if (values.size () == 4) { const float& ax = values[0]; const float& ay = values[1]; const float& az = values[2]; const float& theta = values[3]; tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az))); } else { print_error ("Wrong number of values given (%zu): ", values.size ()); print_error ("The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\n"); } } if (parse_x_arguments (argc, argv, "-matrix", values) > -1) { if (values.size () == 9 || values.size () == 16) { int n = values.size () == 9 ? 3 : 4; for (int r = 0; r < n; ++r) for (int c = 0; c < n; ++c) tform (r, c) = values[n*r+c]; } else { print_error ("Wrong number of values given (%zu): ", values.size ()); print_error ("The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\n"); } } // Load the first file sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2); if (!loadCloud (argv[p_file_indices[0]], *cloud)) return (-1); // Apply the transform sensor_msgs::PointCloud2 output; compute (cloud, output, tform); // Save into the second file saveCloud (argv[p_file_indices[1]], output); } <commit_msg>added basic XYZ scaling<commit_after>/* * Software License Agreement (BSD License) * * Point Cloud Library (PCL) - www.pointclouds.org * Copyright (c) 2011-2012, Willow Garage, Inc. * Copyright (c) 2012-, Open Perception, Inc. * * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above * copyright notice, this list of conditions and the following * disclaimer in the documentation and/or other materials provided * with the distribution. * * Neither the name of the copyright holder(s) 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. * * $Id$ * */ #include <sensor_msgs/PointCloud2.h> #include <pcl/ros/conversions.h> #include <pcl/io/pcd_io.h> #include <pcl/console/print.h> #include <pcl/console/parse.h> #include <pcl/console/time.h> #include <pcl/common/transforms.h> #include <cmath> using namespace pcl; using namespace pcl::io; using namespace pcl::console; void printHelp (int, char **argv) { print_error ("Syntax is: %s input.pcd output.pcd <options>\n", argv[0]); print_info (" where options are:\n"); print_info (" -trans dx,dy,dz = the translation (default: "); print_value ("%0.1f, %0.1f, %0.1f", 0, 0, 0); print_info (")\n"); print_info (" -quat w,x,y,z = rotation as quaternion\n"); print_info (" -axisangle ax,ay,az,theta = rotation in axis-angle form\n"); print_info (" -scale x,y,z = scale each dimension with these values\n"); print_info (" -matrix v1,v2,...,v8,v9 = a 3x3 affine transform\n"); print_info (" -matrix v1,v2,...,v15,v16 = a 4x4 transformation matrix\n"); print_info (" Note: If a rotation is not specified, it will default to no rotation.\n"); print_info (" If redundant or conflicting transforms are specified, then:\n"); print_info (" -axisangle will override -quat\n"); print_info (" -matrix (3x3) will take override -axisangle and -quat\n"); print_info (" -matrix (4x4) will take override all other arguments\n"); } void printElapsedTimeAndNumberOfPoints (double t, int w, int h = 1) { print_info ("[done, "); print_value ("%g", t); print_info (" ms : "); print_value ("%d", w*h); print_info (" points]\n"); } bool loadCloud (const std::string &filename, sensor_msgs::PointCloud2 &cloud) { TicToc tt; print_highlight ("Loading "); print_value ("%s ", filename.c_str ()); tt.tic (); if (loadPCDFile (filename, cloud) < 0) return (false); printElapsedTimeAndNumberOfPoints (tt.toc (), cloud.width, cloud.height); print_info ("Available dimensions: "); print_value ("%s\n", pcl::getFieldsList (cloud).c_str ()); return (true); } template <typename PointT> void transformPointCloudHelper (PointCloud<PointT> & input, PointCloud<PointT> & output, Eigen::Matrix4f &tform) { transformPointCloud (input, output, tform); } template <> void transformPointCloudHelper (PointCloud<PointNormal> & input, PointCloud<PointNormal> & output, Eigen::Matrix4f &tform) { transformPointCloudWithNormals (input, output, tform); } template <> void transformPointCloudHelper<PointXYZRGBNormal> (PointCloud<PointXYZRGBNormal> & input, PointCloud<PointXYZRGBNormal> & output, Eigen::Matrix4f &tform) { transformPointCloudWithNormals (input, output, tform); } template <typename PointT> void transformPointCloud2AsType (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output, Eigen::Matrix4f &tform) { PointCloud<PointT> cloud; fromROSMsg (input, cloud); transformPointCloudHelper (cloud, cloud, tform); toROSMsg (cloud, output); } void transformPointCloud2 (const sensor_msgs::PointCloud2 &input, sensor_msgs::PointCloud2 &output, Eigen::Matrix4f &tform) { // Check for 'rgb' and 'normals' fields bool has_rgb = false; bool has_normals = false; for (size_t i = 0; i < input.fields.size (); ++i) { if (input.fields[i].name == "rgb") has_rgb = true; if (input.fields[i].name == "normals") has_normals = true; } // Handle the following four point types differently: PointXYZ, PointXYZRGB, PointNormal, PointXYZRGBNormal if (!has_rgb && !has_normals) transformPointCloud2AsType<PointXYZ> (input, output, tform); else if (has_rgb && !has_normals) transformPointCloud2AsType<PointXYZRGB> (input, output, tform); else if (!has_rgb && has_normals) transformPointCloud2AsType<PointNormal> (input, output, tform); else // (has_rgb && has_normals) transformPointCloud2AsType<PointXYZRGBNormal> (input, output, tform); } void compute (const sensor_msgs::PointCloud2::ConstPtr &input, sensor_msgs::PointCloud2 &output, Eigen::Matrix4f &tform) { TicToc tt; tt.tic (); print_highlight ("Transforming "); transformPointCloud2 (*input, output, tform); printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height); } void saveCloud (const std::string &filename, const sensor_msgs::PointCloud2 &output) { TicToc tt; tt.tic (); print_highlight ("Saving "); print_value ("%s ", filename.c_str ()); pcl::io::savePCDFile (filename, output); printElapsedTimeAndNumberOfPoints (tt.toc (), output.width, output.height); } template <typename T> void divide (sensor_msgs::PointCloud2 &cloud, int field_offset, double divider) { T val; memcpy (&val, &cloud.data[field_offset], sizeof (T)); val /= T (divider); memcpy (&cloud.data[field_offset], &val, sizeof (T)); } void scaleInPlace (sensor_msgs::PointCloud2 &cloud, double* divider) { // Obtain the x, y, and z indices int x_idx = pcl::getFieldIndex (cloud, "x"); int y_idx = pcl::getFieldIndex (cloud, "y"); int z_idx = pcl::getFieldIndex (cloud, "z"); Eigen::Array3i xyz_offset (cloud.fields[x_idx].offset, cloud.fields[y_idx].offset, cloud.fields[z_idx].offset); for (uint32_t cp = 0; cp < cloud.width * cloud.height; ++cp) { assert (cloud.fields[x_idx].datatype == cloud.fields[y_idx].datatype == cloud.fields[z_idx].datatype); // Assume all 3 fields are the same (XYZ) switch (cloud.fields[x_idx].datatype) { case sensor_msgs::PointField::INT8: for (int i = 0; i < 3; ++i) divide<int8_t> (cloud, xyz_offset[i], divider[i]); break; case sensor_msgs::PointField::UINT8: for (int i = 0; i < 3; ++i) divide<uint8_t> (cloud, xyz_offset[i], divider[i]); break; case sensor_msgs::PointField::INT16: for (int i = 0; i < 3; ++i) divide<int16_t> (cloud, xyz_offset[i], divider[i]); break; case sensor_msgs::PointField::UINT16: for (int i = 0; i < 3; ++i) divide<uint16_t> (cloud, xyz_offset[i], divider[i]); break; case sensor_msgs::PointField::INT32: for (int i = 0; i < 3; ++i) divide<int32_t> (cloud, xyz_offset[i], divider[i]); break; case sensor_msgs::PointField::UINT32: for (int i = 0; i < 3; ++i) divide<uint32_t> (cloud, xyz_offset[i], divider[i]); break; case sensor_msgs::PointField::FLOAT32: for (int i = 0; i < 3; ++i) divide<float> (cloud, xyz_offset[i], divider[i]); break; case sensor_msgs::PointField::FLOAT64: for (int i = 0; i < 3; ++i) divide<double> (cloud, xyz_offset[i], divider[i]); break; } xyz_offset += cloud.point_step; } } /* ---[ */ int main (int argc, char** argv) { print_info ("Transform a cloud. For more information, use: %s -h\n", argv[0]); bool help = false; parse_argument (argc, argv, "-h", help); if (argc < 3 || help) { printHelp (argc, argv); return (-1); } // Parse the command line arguments for .pcd files std::vector<int> p_file_indices; p_file_indices = parse_file_extension_argument (argc, argv, ".pcd"); if (p_file_indices.size () != 2) { print_error ("Need one input PCD file and one output PCD file to continue.\n"); return (-1); } // Initialize the transformation matrix Eigen::Matrix4f tform; tform.setIdentity (); // Command line parsing float dx, dy, dz; std::vector<float> values; if (parse_3x_arguments (argc, argv, "-trans", dx, dy, dz) > -1) { tform (0, 3) = dx; tform (1, 3) = dy; tform (2, 3) = dz; } if (parse_x_arguments (argc, argv, "-quat", values) > -1) { if (values.size () == 4) { const float& x = values[0]; const float& y = values[1]; const float& z = values[2]; const float& w = values[3]; tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::Quaternionf (w, x, y, z)); } else { print_error ("Wrong number of values given (%zu): ", values.size ()); print_error ("The quaternion specified with -quat must contain 4 elements (w,x,y,z).\n"); } } if (parse_x_arguments (argc, argv, "-axisangle", values) > -1) { if (values.size () == 4) { const float& ax = values[0]; const float& ay = values[1]; const float& az = values[2]; const float& theta = values[3]; tform.topLeftCorner (3, 3) = Eigen::Matrix3f (Eigen::AngleAxisf (theta, Eigen::Vector3f (ax, ay, az))); } else { print_error ("Wrong number of values given (%zu): ", values.size ()); print_error ("The rotation specified with -axisangle must contain 4 elements (ax,ay,az,theta).\n"); } } if (parse_x_arguments (argc, argv, "-matrix", values) > -1) { if (values.size () == 9 || values.size () == 16) { int n = values.size () == 9 ? 3 : 4; for (int r = 0; r < n; ++r) for (int c = 0; c < n; ++c) tform (r, c) = values[n*r+c]; } else { print_error ("Wrong number of values given (%zu): ", values.size ()); print_error ("The transformation specified with -matrix must be 3x3 (9) or 4x4 (16).\n"); } } // Load the first file sensor_msgs::PointCloud2::Ptr cloud (new sensor_msgs::PointCloud2); if (!loadCloud (argv[p_file_indices[0]], *cloud)) return (-1); // Apply the transform sensor_msgs::PointCloud2 output; compute (cloud, output, tform); // Check if a scaling parameter has been given double divider[3]; if (parse_3x_arguments (argc, argv, "-scale", divider[0], divider[1], divider[2]) > -1) { print_highlight ("Scaling XYZ data with the following values: %f, %f, %f\n", divider[0], divider[1], divider[2]); scaleInPlace (output, divider); } // Save into the second file saveCloud (argv[p_file_indices[1]], output); } <|endoftext|>
<commit_before>#include <iostream> #include <string> #include <vector> #include <set> #include <map> using namespace std; extern "C" { #include <getopt.h> #include <pbs_error.h> #include <pbs_ifl.h> } static char *progname; class Attribute { public: std::string name; std::string resource; std::string value; std::string dottedname(); Attribute(struct attrl *a); Attribute(std::string, std::string, std::string); Attribute(const Attribute &); }; Attribute::Attribute (std::string name, std::string resource, std::string value) { name = name; resource = resource; value = value; } Attribute::Attribute (const Attribute &a) { name = a.name; resource = a.resource; value = a.value; } Attribute::Attribute (struct attrl *a) { name.assign(a->name == NULL ? "" : a->name); resource.assign(a->resource == NULL ? "" : a->resource); value.assign(a->value == NULL ? "" : a->value); } std::string Attribute::dottedname () { return name + (resource == "" ? "" : "." + resource); } class Filter { public: std::string attribute; enum Symbol { AND, OR, EQ, NE, GE, GT, LE, LT }; Symbol op; std::string value; Filter (std::string); }; bool test (Attribute attribute, Filter filter) { switch (filter.op) { case Filter::EQ: return attribute.value == filter.value; break; case Filter::NE: return attribute.value != filter.value; break; default: cout << "Not yet supported"; exit(EXIT_FAILURE); break; } return false; } Filter::Filter (std::string filter) { size_t offset = filter.length(); std::map<std::string, Filter::Symbol> lookup; lookup["="] = Filter::EQ; lookup[">"] = Filter::GT; lookup["<"] = Filter::LT; lookup["!="] = Filter::NE; lookup[">="] = Filter::GE; lookup["<="] = Filter::LE; std::string winner; for (auto i = lookup.begin(); i != lookup.end(); ++i) { auto j = filter.find( i->first ); if (j < offset) { winner = i->first; offset = j; } } if (offset == 0) { cout << "Failed to find operator in filter: " + filter << endl; exit(EXIT_FAILURE); } attribute = filter.substr(0, offset); op = lookup.find(winner)->second; value = filter.substr(offset + winner.length()); } class Config { public: bool help; std::string server; std::string output; std::set<string> outattr; std::vector<Filter> filters; enum Output { DEFAULT, XML, JSON, QSTAT, PERL }; Output outstyle; Config (int, char **); }; class BatchStatus { public: std::string name; std::string text; std::vector<Attribute> attributes; BatchStatus(struct batch_status *); BatchStatus(std::string, std::string); }; std::vector<BatchStatus> bs2BatchStatus (struct batch_status *bs) { std::vector<BatchStatus> status; if (bs == NULL) { return status; } while (bs != NULL) { status.push_back(BatchStatus(bs)); bs = bs->next; } return status; } BatchStatus::BatchStatus (std::string n, std::string t) { name = n; text = t; } BatchStatus::BatchStatus (struct batch_status *bs) { if (bs == NULL) { return; } name.assign(bs->name == NULL ? "" : bs->name); text.assign(bs->text == NULL ? "" : bs->text); auto attr = bs->attribs; while (attr != NULL) { attributes.push_back( Attribute(attr) ); attr = attr->next; } } void xml_out (std::vector<BatchStatus> jobs) { cout << "<Data>"; for (decltype(jobs.size()) i = 0; i < jobs.size(); i++) { auto job = jobs[i]; cout << "<Job>"; cout << "<JobId>" + job.name + "</JobId>"; for (decltype(job.attributes.size()) j = 0; j < job.attributes.size(); j++) { auto a = job.attributes[j]; cout << "<" + a.dottedname() + ">" + a.value + "</" + a.dottedname() + ">"; } cout << "</Job>"; } cout << "</Data>"; } void json_out (std::vector<BatchStatus> jobs, std::string sep) { cout << "[" << endl; for (decltype(jobs.size()) i = 0; i < jobs.size(); i++) { auto job = jobs[i]; cout << " {" << endl; cout << " \"name\" " + sep + " \"" + job.name + '"'; if (job.attributes.size() != 0) { cout << ','; } cout << endl; for (decltype(job.attributes.size()) j = 0; j < job.attributes.size(); j++) { auto attr = job.attributes[j]; cout << " \"" + attr.dottedname() + "\" " + sep + " \"" + attr.value + '"'; if (j+1 != job.attributes.size()) { cout << ','; } cout << endl; } cout << " }"; if (i + 1 != jobs.size()) cout << ','; cout << endl; } cout << "]" << endl; } void txt_out (std::vector<BatchStatus> jobs) { for (auto j = jobs.begin(); j != jobs.end(); ++j) { cout << j->name << endl; for (auto i = j->attributes.begin(); i != j->attributes.end(); ++i) { std::string indent = i->resource != "" ? " " : " "; cout << indent + i->dottedname() + ": " + i->value << endl; } } } std::string line(size_t length) { std::string line; for (size_t i = 0; i < length; i++) { line.append("-"); } return line; } // FIXME: This is broken for jobs that don't have the same attributes in the same order void qstat_out (std::vector<BatchStatus> jobs) { std::string id = "Job id"; auto idWidth = id.length(); std::vector<size_t> colWidths; // No jobs, don't output anything if (jobs.size() == 0) { return; } // Get column heading widths for (decltype(jobs[0].attributes.size()) i = 0; i < jobs[0].attributes.size(); i++) { colWidths.push_back(jobs[0].attributes[i].dottedname().length()); } // Get column widths for job attribute values for (decltype(jobs.size()) i = 0; i < jobs.size(); i++) { if (jobs[i].name.length() > idWidth) idWidth = jobs[i].name.length(); for (decltype(jobs[i].attributes.size()) j = 0; j < jobs[i].attributes.size(); j++) { if (jobs[i].attributes[j].value.length() > colWidths[j]) colWidths[j] = jobs[i].attributes[j].value.length(); } } // Print header printf("%-*s ", (int) idWidth, id.c_str()); for (decltype(colWidths.size()) i = 0; i < colWidths.size(); i++) { printf("%-*s", (int) colWidths[i], jobs[0].attributes[i].dottedname().c_str()); if (i + 1 < jobs[0].attributes.size()) cout << " "; } cout << endl; cout << line(idWidth) + " "; for (decltype(colWidths.size()) i = 0; i < colWidths.size(); i++) { cout << line(colWidths[i]); if (i + 1 < jobs[0].attributes.size()) cout << " "; } cout << endl; // Print job attributes for (decltype(colWidths.size()) i = 0; i < jobs.size(); i++) { printf("%-*s ", (int) idWidth, jobs[i].name.c_str()); for (decltype(jobs[i].attributes.size()) j = 0; j < jobs[i].attributes.size(); j++) { printf("%-*s", (int) colWidths[j], jobs[i].attributes[j].value.c_str()); if (j + 1 < jobs[i].attributes.size()) { cout << " "; } } cout << endl; } } // From http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html void Tokenize(const std::string &str, std::set<string>& tokens, const std::string& delimiters = " ") { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.insert(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } Config::Config (int argc, char **argv) { outstyle = Config::DEFAULT; output = "Job_Name,Job_Owner,resources_used,job_state,queue"; help = false; /* cfg->filters = NULL; cfg->server = NULL; cfg->output = NULL; cfg->outattr = NULL; cfg->list = 0; cfg->outstyle = Config::DEFAULT; */ int opt; std::string outformat, filter_str; while ((opt = getopt(argc, argv, "hs:o:a:f:")) != -1) { switch (opt) { case 'h': help = true; break; case 's': server.assign(optarg); break; case 'o': outformat.assign(optarg); break; case 'a': output.assign(optarg); break; case 'f': filter_str.assign(optarg); break; } } if (outformat == "") { outstyle = Config::DEFAULT; } else if (outformat == "xml") { outstyle = Config::XML; } else if (outformat == "perl") { outstyle = Config::PERL; } else if (outformat == "json") { outstyle = Config::JSON; } else if (outformat == "qstat") { outstyle = Config::QSTAT; } else { cout << "Unknown output format: " + outformat << endl; exit(EXIT_FAILURE); } std::set<string> l_filters; Tokenize(filter_str, l_filters, ","); for (auto i = l_filters.begin(); i != l_filters.end(); ++i) { filters.push_back(Filter(*i)); } Tokenize(output, outattr, ","); } // Return a new std::vector<BatchStatus> with the same jobs as s with only // the attributes specified by attr std::vector<BatchStatus> filter_attributes (std::vector<BatchStatus> s, std::set<string> attr) { std::vector<BatchStatus> filtered; bool all = false; if (attr.find("all") != attr.end()) { all = true; } for (auto i = s.begin(); i != s.end(); ++i) { auto bs = BatchStatus(i->name, i->text); for (auto j = i->attributes.begin(); j != i->attributes.end(); ++j) { if (all || attr.find(j->name) != attr.end()) { bs.attributes.push_back(Attribute(*j)); } } filtered.push_back(bs); } return filtered; } std::vector<BatchStatus> filter_jobs (std::vector<BatchStatus> s, std::vector<Filter> f) { std::vector<BatchStatus> filtered; for (auto i = s.begin(); i != s.end(); ++i) { for (auto j = i->attributes.begin(); j != i->attributes.end(); ++j) { for (auto k = f.begin(); k != f.end(); ++k) { if (k->attribute == j->name) { if (test(*j, *k)) { filtered.push_back(*i); } } } } } return filtered; } void show_usage() { fprintf(stderr, "usage: %s [-h] [-s server] [-o xml|json|perl|qstat] [-a attr1,attr2] [-f attr3=foo]\n", progname); } void show_help () { fprintf(stderr, "qps, built from %s\n\n", VERSION); show_usage(); fprintf(stderr, "\n"); fprintf(stderr, " h : show help\n"); fprintf(stderr, " s : server to connect to\n"); fprintf(stderr, " o : output format (xml|perl|qstat|json)\n"); fprintf(stderr, " a : job attributes to display ('all' for all attributes)\n"); fprintf(stderr, " f : attributes=value to filter jobs (e.g. -f job_state=R)\n"); } int main(int argc, char **argv) { progname = argv[0]; auto cfg = Config(argc, argv); if (cfg.help) { show_help(); exit(EXIT_SUCCESS); } // pbs_connect() breaks it's contract and can return large +ve numbers // which appear to be errno's, so set pbs_errno and check it as well. pbs_errno = 0; int h = pbs_connect((char *) cfg.server.c_str()); if (h <= 0) { char *err = pbs_geterrmsg(h); printf("Failed to connect to server: %s\n", err == NULL ? "Unknown reason" : err); exit(EXIT_FAILURE); } else if (pbs_errno != 0) { char *err = pbs_strerror(pbs_errno); printf("Failed to connect to server: %s\n", err == NULL ? "Unknown reason" : err); exit(EXIT_FAILURE); } auto bs = pbs_statjob(h, (char *) "", NULL, (char *) ""); if (bs == NULL) { pbs_disconnect(h); cout << "failed to get status" << endl; exit(EXIT_FAILURE); } auto jobs = bs2BatchStatus(bs); pbs_statfree(bs); pbs_disconnect(h); std::vector<BatchStatus> filtered; if (cfg.filters.size()) { filtered = filter_jobs(jobs, cfg.filters); } else { filtered = jobs; } auto finaljobs = filter_attributes(filtered, cfg.outattr); switch (cfg.outstyle) { case Config::XML: xml_out(finaljobs); break; case Config::JSON: json_out(finaljobs, ":"); break; case Config::PERL: json_out(finaljobs, "=>"); break; case Config::QSTAT: qstat_out(finaljobs); break; case Config::DEFAULT: txt_out(finaljobs); break; default: cout << "Unknown format: " << endl; exit(EXIT_FAILURE); break; } } <commit_msg>Don't report an error if there were no jobs found<commit_after>#include <iostream> #include <string> #include <vector> #include <set> #include <map> using namespace std; extern "C" { #include <getopt.h> #include <pbs_error.h> #include <pbs_ifl.h> } static char *progname; class Attribute { public: std::string name; std::string resource; std::string value; std::string dottedname(); Attribute(struct attrl *a); Attribute(std::string, std::string, std::string); Attribute(const Attribute &); }; Attribute::Attribute (std::string name, std::string resource, std::string value) { name = name; resource = resource; value = value; } Attribute::Attribute (const Attribute &a) { name = a.name; resource = a.resource; value = a.value; } Attribute::Attribute (struct attrl *a) { name.assign(a->name == NULL ? "" : a->name); resource.assign(a->resource == NULL ? "" : a->resource); value.assign(a->value == NULL ? "" : a->value); } std::string Attribute::dottedname () { return name + (resource == "" ? "" : "." + resource); } class Filter { public: std::string attribute; enum Symbol { AND, OR, EQ, NE, GE, GT, LE, LT }; Symbol op; std::string value; Filter (std::string); }; bool test (Attribute attribute, Filter filter) { switch (filter.op) { case Filter::EQ: return attribute.value == filter.value; break; case Filter::NE: return attribute.value != filter.value; break; default: cout << "Not yet supported"; exit(EXIT_FAILURE); break; } return false; } Filter::Filter (std::string filter) { size_t offset = filter.length(); std::map<std::string, Filter::Symbol> lookup; lookup["="] = Filter::EQ; lookup[">"] = Filter::GT; lookup["<"] = Filter::LT; lookup["!="] = Filter::NE; lookup[">="] = Filter::GE; lookup["<="] = Filter::LE; std::string winner; for (auto i = lookup.begin(); i != lookup.end(); ++i) { auto j = filter.find( i->first ); if (j < offset) { winner = i->first; offset = j; } } if (offset == 0) { cout << "Failed to find operator in filter: " + filter << endl; exit(EXIT_FAILURE); } attribute = filter.substr(0, offset); op = lookup.find(winner)->second; value = filter.substr(offset + winner.length()); } class Config { public: bool help; std::string server; std::string output; std::set<string> outattr; std::vector<Filter> filters; enum Output { DEFAULT, XML, JSON, QSTAT, PERL }; Output outstyle; Config (int, char **); }; class BatchStatus { public: std::string name; std::string text; std::vector<Attribute> attributes; BatchStatus(struct batch_status *); BatchStatus(std::string, std::string); }; std::vector<BatchStatus> bs2BatchStatus (struct batch_status *bs) { std::vector<BatchStatus> status; if (bs == NULL) { return status; } while (bs != NULL) { status.push_back(BatchStatus(bs)); bs = bs->next; } return status; } BatchStatus::BatchStatus (std::string n, std::string t) { name = n; text = t; } BatchStatus::BatchStatus (struct batch_status *bs) { if (bs == NULL) { return; } name.assign(bs->name == NULL ? "" : bs->name); text.assign(bs->text == NULL ? "" : bs->text); auto attr = bs->attribs; while (attr != NULL) { attributes.push_back( Attribute(attr) ); attr = attr->next; } } void xml_out (std::vector<BatchStatus> jobs) { cout << "<Data>"; for (decltype(jobs.size()) i = 0; i < jobs.size(); i++) { auto job = jobs[i]; cout << "<Job>"; cout << "<JobId>" + job.name + "</JobId>"; for (decltype(job.attributes.size()) j = 0; j < job.attributes.size(); j++) { auto a = job.attributes[j]; cout << "<" + a.dottedname() + ">" + a.value + "</" + a.dottedname() + ">"; } cout << "</Job>"; } cout << "</Data>"; } void json_out (std::vector<BatchStatus> jobs, std::string sep) { cout << "[" << endl; for (decltype(jobs.size()) i = 0; i < jobs.size(); i++) { auto job = jobs[i]; cout << " {" << endl; cout << " \"name\" " + sep + " \"" + job.name + '"'; if (job.attributes.size() != 0) { cout << ','; } cout << endl; for (decltype(job.attributes.size()) j = 0; j < job.attributes.size(); j++) { auto attr = job.attributes[j]; cout << " \"" + attr.dottedname() + "\" " + sep + " \"" + attr.value + '"'; if (j+1 != job.attributes.size()) { cout << ','; } cout << endl; } cout << " }"; if (i + 1 != jobs.size()) cout << ','; cout << endl; } cout << "]" << endl; } void txt_out (std::vector<BatchStatus> jobs) { for (auto j = jobs.begin(); j != jobs.end(); ++j) { cout << j->name << endl; for (auto i = j->attributes.begin(); i != j->attributes.end(); ++i) { std::string indent = i->resource != "" ? " " : " "; cout << indent + i->dottedname() + ": " + i->value << endl; } } } std::string line(size_t length) { std::string line; for (size_t i = 0; i < length; i++) { line.append("-"); } return line; } // FIXME: This is broken for jobs that don't have the same attributes in the same order void qstat_out (std::vector<BatchStatus> jobs) { std::string id = "Job id"; auto idWidth = id.length(); std::vector<size_t> colWidths; // No jobs, don't output anything if (jobs.size() == 0) { return; } // Get column heading widths for (decltype(jobs[0].attributes.size()) i = 0; i < jobs[0].attributes.size(); i++) { colWidths.push_back(jobs[0].attributes[i].dottedname().length()); } // Get column widths for job attribute values for (decltype(jobs.size()) i = 0; i < jobs.size(); i++) { if (jobs[i].name.length() > idWidth) idWidth = jobs[i].name.length(); for (decltype(jobs[i].attributes.size()) j = 0; j < jobs[i].attributes.size(); j++) { if (jobs[i].attributes[j].value.length() > colWidths[j]) colWidths[j] = jobs[i].attributes[j].value.length(); } } // Print header printf("%-*s ", (int) idWidth, id.c_str()); for (decltype(colWidths.size()) i = 0; i < colWidths.size(); i++) { printf("%-*s", (int) colWidths[i], jobs[0].attributes[i].dottedname().c_str()); if (i + 1 < jobs[0].attributes.size()) cout << " "; } cout << endl; cout << line(idWidth) + " "; for (decltype(colWidths.size()) i = 0; i < colWidths.size(); i++) { cout << line(colWidths[i]); if (i + 1 < jobs[0].attributes.size()) cout << " "; } cout << endl; // Print job attributes for (decltype(colWidths.size()) i = 0; i < jobs.size(); i++) { printf("%-*s ", (int) idWidth, jobs[i].name.c_str()); for (decltype(jobs[i].attributes.size()) j = 0; j < jobs[i].attributes.size(); j++) { printf("%-*s", (int) colWidths[j], jobs[i].attributes[j].value.c_str()); if (j + 1 < jobs[i].attributes.size()) { cout << " "; } } cout << endl; } } // From http://oopweb.com/CPP/Documents/CPPHOWTO/Volume/C++Programming-HOWTO-7.html void Tokenize(const std::string &str, std::set<string>& tokens, const std::string& delimiters = " ") { // Skip delimiters at beginning. string::size_type lastPos = str.find_first_not_of(delimiters, 0); // Find first "non-delimiter". string::size_type pos = str.find_first_of(delimiters, lastPos); while (string::npos != pos || string::npos != lastPos) { // Found a token, add it to the vector. tokens.insert(str.substr(lastPos, pos - lastPos)); // Skip delimiters. Note the "not_of" lastPos = str.find_first_not_of(delimiters, pos); // Find next "non-delimiter" pos = str.find_first_of(delimiters, lastPos); } } Config::Config (int argc, char **argv) { outstyle = Config::DEFAULT; output = "Job_Name,Job_Owner,resources_used,job_state,queue"; help = false; /* cfg->filters = NULL; cfg->server = NULL; cfg->output = NULL; cfg->outattr = NULL; cfg->list = 0; cfg->outstyle = Config::DEFAULT; */ int opt; std::string outformat, filter_str; while ((opt = getopt(argc, argv, "hs:o:a:f:")) != -1) { switch (opt) { case 'h': help = true; break; case 's': server.assign(optarg); break; case 'o': outformat.assign(optarg); break; case 'a': output.assign(optarg); break; case 'f': filter_str.assign(optarg); break; } } if (outformat == "") { outstyle = Config::DEFAULT; } else if (outformat == "xml") { outstyle = Config::XML; } else if (outformat == "perl") { outstyle = Config::PERL; } else if (outformat == "json") { outstyle = Config::JSON; } else if (outformat == "qstat") { outstyle = Config::QSTAT; } else { cout << "Unknown output format: " + outformat << endl; exit(EXIT_FAILURE); } std::set<string> l_filters; Tokenize(filter_str, l_filters, ","); for (auto i = l_filters.begin(); i != l_filters.end(); ++i) { filters.push_back(Filter(*i)); } Tokenize(output, outattr, ","); } // Return a new std::vector<BatchStatus> with the same jobs as s with only // the attributes specified by attr std::vector<BatchStatus> filter_attributes (std::vector<BatchStatus> s, std::set<string> attr) { std::vector<BatchStatus> filtered; bool all = false; if (attr.find("all") != attr.end()) { all = true; } for (auto i = s.begin(); i != s.end(); ++i) { auto bs = BatchStatus(i->name, i->text); for (auto j = i->attributes.begin(); j != i->attributes.end(); ++j) { if (all || attr.find(j->name) != attr.end()) { bs.attributes.push_back(Attribute(*j)); } } filtered.push_back(bs); } return filtered; } std::vector<BatchStatus> filter_jobs (std::vector<BatchStatus> s, std::vector<Filter> f) { std::vector<BatchStatus> filtered; for (auto i = s.begin(); i != s.end(); ++i) { for (auto j = i->attributes.begin(); j != i->attributes.end(); ++j) { for (auto k = f.begin(); k != f.end(); ++k) { if (k->attribute == j->name) { if (test(*j, *k)) { filtered.push_back(*i); } } } } } return filtered; } void show_usage() { fprintf(stderr, "usage: %s [-h] [-s server] [-o xml|json|perl|qstat] [-a attr1,attr2] [-f attr3=foo]\n", progname); } void show_help () { fprintf(stderr, "qps, built from %s\n\n", VERSION); show_usage(); fprintf(stderr, "\n"); fprintf(stderr, " h : show help\n"); fprintf(stderr, " s : server to connect to\n"); fprintf(stderr, " o : output format (xml|perl|qstat|json)\n"); fprintf(stderr, " a : job attributes to display ('all' for all attributes)\n"); fprintf(stderr, " f : attributes=value to filter jobs (e.g. -f job_state=R)\n"); } int main(int argc, char **argv) { progname = argv[0]; auto cfg = Config(argc, argv); if (cfg.help) { show_help(); exit(EXIT_SUCCESS); } // pbs_connect() breaks it's contract and can return large +ve numbers // which appear to be errno's, so set pbs_errno and check it as well. pbs_errno = 0; int h = pbs_connect((char *) cfg.server.c_str()); if (h <= 0) { char *err = pbs_geterrmsg(h); printf("Failed to connect to server: %s\n", err == NULL ? "Unknown reason" : err); exit(EXIT_FAILURE); } else if (pbs_errno != 0) { char *err = pbs_strerror(pbs_errno); printf("Failed to connect to server: %s\n", err == NULL ? "Unknown reason" : err); exit(EXIT_FAILURE); } auto bs = pbs_statjob(h, (char *) "", NULL, (char *) ""); if (bs == NULL) { pbs_disconnect(h); // FIXME: This can mean either that we failed to get any jobs, or that // there were no jobs to query. Assume that everything was fine exit(EXIT_SUCCESS); } auto jobs = bs2BatchStatus(bs); pbs_statfree(bs); pbs_disconnect(h); std::vector<BatchStatus> filtered; if (cfg.filters.size()) { filtered = filter_jobs(jobs, cfg.filters); } else { filtered = jobs; } auto finaljobs = filter_attributes(filtered, cfg.outattr); switch (cfg.outstyle) { case Config::XML: xml_out(finaljobs); break; case Config::JSON: json_out(finaljobs, ":"); break; case Config::PERL: json_out(finaljobs, "=>"); break; case Config::QSTAT: qstat_out(finaljobs); break; case Config::DEFAULT: txt_out(finaljobs); break; default: cout << "Unknown format: " << endl; exit(EXIT_FAILURE); break; } } <|endoftext|>