<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: YColumns.cxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 06:31:28 $
 *
 *  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 "mysql/YColumns.hxx"

#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif

using namespace ::comphelper;
using namespace connectivity::mysql;
using namespace connectivity::sdbcx;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;

OMySQLColumns::OMySQLColumns(   ::cppu::OWeakObject& _rParent
                                ,sal_Bool _bCase
                                ,::osl::Mutex& _rMutex
                                ,const TStringVector &_rVector
                                ,sal_Bool _bUseHardRef
            ) : OColumnsHelper(_rParent,_bCase,_rMutex,_rVector,_bUseHardRef)
{
}
// -----------------------------------------------------------------------------
Reference< XPropertySet > OMySQLColumns::createEmptyObject()
{
    return new OMySQLColumn(sal_True);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
OMySQLColumn::OMySQLColumn( sal_Bool    _bCase)
    : connectivity::sdbcx::OColumn( _bCase )
{
    construct();
}
// -------------------------------------------------------------------------
void OMySQLColumn::construct()
{
    m_sAutoIncrement = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("auto_increment"));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_AUTOINCREMENTCREATION),PROPERTY_ID_AUTOINCREMENTCREATION,0,&m_sAutoIncrement, ::getCppuType(&m_sAutoIncrement));
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OMySQLColumn::createArrayHelper( sal_Int32 _nId) const
{
    Sequence< ::com::sun::star::beans::Property > aProps;
    describeProperties(aProps);
    changePropertyAttributte(aProps);
    return new ::cppu::OPropertyArrayHelper(aProps);
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper & SAL_CALL OMySQLColumn::getInfoHelper()
{
    return *OMySQLColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL OMySQLColumn::getSupportedServiceNames(  ) throw(RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(1);
    aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Column");

    return aSupported;
}
// -----------------------------------------------------------------------------
<commit_msg>INTEGRATION: CWS warnings01 (1.3.30); FILE MERGED 2006/06/14 10:56:22 fs 1.3.30.2: #i66367# reverted previous changes related to replacing IdPropertyArrayHelper with PropertyArrayHelper - there's a subtle difference between both ids ... 2005/11/16 12:59:17 fs 1.3.30.1: #i57457# warning free code<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: YColumns.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 01:52:53 $
 *
 *  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 "mysql/YColumns.hxx"

#ifndef CONNECTIVITY_CONNECTION_HXX
#include "TConnection.hxx"
#endif

using namespace ::comphelper;
using namespace connectivity::mysql;
using namespace connectivity::sdbcx;
using namespace connectivity;
using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::beans;
using namespace ::com::sun::star::sdbcx;
using namespace ::com::sun::star::sdbc;
using namespace ::com::sun::star::container;
using namespace ::com::sun::star::lang;

OMySQLColumns::OMySQLColumns(   ::cppu::OWeakObject& _rParent
                                ,sal_Bool _bCase
                                ,::osl::Mutex& _rMutex
                                ,const TStringVector &_rVector
                                ,sal_Bool _bUseHardRef
            ) : OColumnsHelper(_rParent,_bCase,_rMutex,_rVector,_bUseHardRef)
{
}
// -----------------------------------------------------------------------------
Reference< XPropertySet > OMySQLColumns::createEmptyObject()
{
    return new OMySQLColumn(sal_True);
}
// -----------------------------------------------------------------------------
// -----------------------------------------------------------------------------
OMySQLColumn::OMySQLColumn( sal_Bool    _bCase)
    : connectivity::sdbcx::OColumn( _bCase )
{
    construct();
}
// -------------------------------------------------------------------------
void OMySQLColumn::construct()
{
    m_sAutoIncrement = ::rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("auto_increment"));
    registerProperty(OMetaConnection::getPropMap().getNameByIndex(PROPERTY_ID_AUTOINCREMENTCREATION),PROPERTY_ID_AUTOINCREMENTCREATION,0,&m_sAutoIncrement, ::getCppuType(&m_sAutoIncrement));
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper* OMySQLColumn::createArrayHelper( sal_Int32 /*_nId*/ ) const
{
    return doCreateArrayHelper();
}
// -----------------------------------------------------------------------------
::cppu::IPropertyArrayHelper & SAL_CALL OMySQLColumn::getInfoHelper()
{
    return *OMySQLColumn_PROP::getArrayHelper(isNew() ? 1 : 0);
}
// -----------------------------------------------------------------------------
Sequence< ::rtl::OUString > SAL_CALL OMySQLColumn::getSupportedServiceNames(  ) throw(RuntimeException)
{
    Sequence< ::rtl::OUString > aSupported(1);
    aSupported[0] = ::rtl::OUString::createFromAscii("com.sun.star.sdbcx.Column");

    return aSupported;
}
// -----------------------------------------------------------------------------
<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include "cling/UserInterface/UserInterface.h"

#include "cling/UserInterface/CompilationException.h"
#include "cling/Interpreter/RuntimeException.h"
#include "cling/Interpreter/StoredValueRef.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "textinput/TextInput.h"
#include "textinput/StreamReader.h"
#include "textinput/TerminalDisplay.h"

#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/PathV1.h"
#include "llvm/Config/config.h"

// Fragment copied from LLVM's raw_ostream.cpp
#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif

#if defined(_MSC_VER)
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#endif

namespace {
  // Handle fatal llvm errors by throwing an exception..
  // Yes, throwing exceptions in error handlers is bad.
  // Doing nothing is pretty terrible, too.
  void exceptionErrorHandler(void * /*user_data*/,
                             const std::string& reason,
                             bool /*gen_crash_diag*/) {
    throw cling::CompilationException(reason);
  }
}

namespace cling {
  // Declared in CompilationException.h; vtable pinned here.
  CompilationException::~CompilationException() throw() {}

  UserInterface::UserInterface(Interpreter& interp) {
    // We need stream that doesn't close its file descriptor, thus we are not
    // using llvm::outs. Keeping file descriptor open we will be able to use
    // the results in pipes (Savannah #99234).
    static llvm::raw_fd_ostream m_MPOuts (STDOUT_FILENO, /*ShouldClose*/false);
    m_MetaProcessor.reset(new MetaProcessor(interp, m_MPOuts));
    llvm::install_fatal_error_handler(&exceptionErrorHandler);
  }

  UserInterface::~UserInterface() {}

  void UserInterface::runInteractively(bool nologo /* = false */) {
    if (!nologo) {
      PrintLogo();
    }

    // History file is $HOME/.cling_history
    static const char* histfile = ".cling_history";
    llvm::sys::Path histfilePath = llvm::sys::Path::GetUserHomeDirectory();
    histfilePath.appendComponent(histfile);

    using namespace textinput;
    StreamReader* R = StreamReader::Create();
    TerminalDisplay* D = TerminalDisplay::Create();
    TextInput TI(*R, *D, histfilePath.c_str());

    TI.SetPrompt("[cling]$ ");
    std::string line;
    while (true) {
      try {
        m_MetaProcessor->getOuts().flush();
        TextInput::EReadResult RR = TI.ReadInput();
        TI.TakeInput(line);
        if (RR == TextInput::kRREOF) {
          break;
        }

        cling::Interpreter::CompilationResult compRes;
        int indent
          = m_MetaProcessor->process(line.c_str(), compRes, 0/*result*/);
        // Quit requested
        if (indent < 0)
          break;
        std::string Prompt = "[cling]";
        if (m_MetaProcessor->getInterpreter().isRawInputEnabled())
          Prompt.append("! ");
        else
          Prompt.append("$ ");

        if (indent > 0)
          // Continuation requested.
          Prompt.append('?' + std::string(indent * 3, ' '));

        TI.SetPrompt(Prompt.c_str());

      }
      catch(runtime::NullDerefException& e) {
        e.diagnose();
      }
      catch(runtime::InterpreterException& e) {
        llvm::errs() << e.what();
      }
      catch(...) {
        llvm::errs() << "Exception occurred. Recovering...\n";
      }
    }
  }

  void UserInterface::PrintLogo() {
    llvm::raw_ostream& outs = m_MetaProcessor->getOuts();
    outs << "\n";
    outs << "****************** CLING ******************" << "\n";
    outs << "* Type C++ code and press enter to run it *" << "\n";
    outs << "*             Type .q to exit             *" << "\n";
    outs << "*******************************************" << "\n";
  }
} // end namespace cling
<commit_msg>Improve exception reporting.<commit_after>//------------------------------------------------------------------------------
// CLING - the C++ LLVM-based InterpreterG :)
// version: $Id$
// author:  Axel Naumann <axel@cern.ch>
//------------------------------------------------------------------------------

#include "cling/UserInterface/UserInterface.h"

#include "cling/UserInterface/CompilationException.h"
#include "cling/Interpreter/RuntimeException.h"
#include "cling/Interpreter/StoredValueRef.h"
#include "cling/MetaProcessor/MetaProcessor.h"
#include "textinput/TextInput.h"
#include "textinput/StreamReader.h"
#include "textinput/TerminalDisplay.h"

#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/Support/PathV1.h"
#include "llvm/Config/config.h"

// Fragment copied from LLVM's raw_ostream.cpp
#if defined(HAVE_UNISTD_H)
# include <unistd.h>
#endif

#if defined(_MSC_VER)
#ifndef STDIN_FILENO
# define STDIN_FILENO 0
#endif
#ifndef STDOUT_FILENO
# define STDOUT_FILENO 1
#endif
#ifndef STDERR_FILENO
# define STDERR_FILENO 2
#endif
#endif

namespace {
  // Handle fatal llvm errors by throwing an exception..
  // Yes, throwing exceptions in error handlers is bad.
  // Doing nothing is pretty terrible, too.
  void exceptionErrorHandler(void * /*user_data*/,
                             const std::string& reason,
                             bool /*gen_crash_diag*/) {
    throw cling::CompilationException(reason);
  }
}

namespace cling {
  // Declared in CompilationException.h; vtable pinned here.
  CompilationException::~CompilationException() throw() {}

  UserInterface::UserInterface(Interpreter& interp) {
    // We need stream that doesn't close its file descriptor, thus we are not
    // using llvm::outs. Keeping file descriptor open we will be able to use
    // the results in pipes (Savannah #99234).
    static llvm::raw_fd_ostream m_MPOuts (STDOUT_FILENO, /*ShouldClose*/false);
    m_MetaProcessor.reset(new MetaProcessor(interp, m_MPOuts));
    llvm::install_fatal_error_handler(&exceptionErrorHandler);
  }

  UserInterface::~UserInterface() {}

  void UserInterface::runInteractively(bool nologo /* = false */) {
    if (!nologo) {
      PrintLogo();
    }

    // History file is $HOME/.cling_history
    static const char* histfile = ".cling_history";
    llvm::sys::Path histfilePath = llvm::sys::Path::GetUserHomeDirectory();
    histfilePath.appendComponent(histfile);

    using namespace textinput;
    StreamReader* R = StreamReader::Create();
    TerminalDisplay* D = TerminalDisplay::Create();
    TextInput TI(*R, *D, histfilePath.c_str());

    TI.SetPrompt("[cling]$ ");
    std::string line;
    while (true) {
      try {
        m_MetaProcessor->getOuts().flush();
        TextInput::EReadResult RR = TI.ReadInput();
        TI.TakeInput(line);
        if (RR == TextInput::kRREOF) {
          break;
        }

        cling::Interpreter::CompilationResult compRes;
        int indent
          = m_MetaProcessor->process(line.c_str(), compRes, 0/*result*/);
        // Quit requested
        if (indent < 0)
          break;
        std::string Prompt = "[cling]";
        if (m_MetaProcessor->getInterpreter().isRawInputEnabled())
          Prompt.append("! ");
        else
          Prompt.append("$ ");

        if (indent > 0)
          // Continuation requested.
          Prompt.append('?' + std::string(indent * 3, ' '));

        TI.SetPrompt(Prompt.c_str());

      }
      catch(runtime::NullDerefException& e) {
        e.diagnose();
      }
      catch(runtime::InterpreterException& e) {
        llvm::errs() << ">>> Caught an interpreter exception!\n"
                     << ">>> " << e.what() << '\n';
      }
      catch(std::exception& e) {
        llvm::errs() << ">>> Caught a std::exception!\n"
                     << ">>> " << e.what() << '\n';
      }
      catch(...) {
        llvm::errs() << "Exception occurred. Recovering...\n";
      }
    }
  }

  void UserInterface::PrintLogo() {
    llvm::raw_ostream& outs = m_MetaProcessor->getOuts();
    outs << "\n";
    outs << "****************** CLING ******************" << "\n";
    outs << "* Type C++ code and press enter to run it *" << "\n";
    outs << "*             Type .q to exit             *" << "\n";
    outs << "*******************************************" << "\n";
  }
} // end namespace cling
<|endoftext|>


<commit_before>#include "UnitTest.h"
#include "../Source/Utility/Buffer.h"

using namespace vl;
using namespace vl::database;
using namespace vl::collections;

extern WString GetTempFolder();
#define TEMP_DIR GetTempFolder()+
#define KB *1024
#define MB *1024*1024

TEST_CASE(Utility_Buffer_AddRemoveSource)
{
	BufferManager bm(64 KB, 16);
	TEST_ASSERT(bm.GetPageSize() == 64 KB);
	TEST_ASSERT(bm.GetCacheSize() == 1 MB);
	TEST_ASSERT(bm.GetCachePageCount() == 16);

	auto a = bm.LoadMemorySource();
	auto b = bm.LoadFileSource(TEMP_DIR L"db.bin", true);
	TEST_ASSERT(bm.GetSourceFileName(a) == L"");
	TEST_ASSERT(bm.GetSourceFileName(b) == TEMP_DIR L"db.bin");

	bm.UnloadSource(a);
	bm.UnloadSource(b);
	TEST_ASSERT(bm.GetSourceFileName(a) == L"");
	TEST_ASSERT(bm.GetSourceFileName(b) == L"");

	a = bm.LoadMemorySource();
	b = bm.LoadFileSource(TEMP_DIR L"db.bin", true);
	TEST_ASSERT(bm.GetSourceFileName(a) == L"");
	TEST_ASSERT(bm.GetSourceFileName(b) == TEMP_DIR L"db.bin");
}

#define TEST_CASE_SOURCE(NAME)														\
extern void TestCase_Utility_Buffer_##NAME(BufferManager& bm, BufferSource source);	\
TEST_CASE(Utility_Buffer_InMemory_##NAME)											\
{																					\
	BufferManager bm(64 KB, 16);													\
	auto source = bm.LoadMemorySource();											\
	TestCase_Utility_Buffer_##NAME(bm, source);										\
}																					\
TEST_CASE(Utility_Buffer_File_##NAME)												\
{																					\
	BufferManager bm(64 KB, 16);													\
	auto source = bm.LoadFileSource(TEMP_DIR L"db.bin", true);						\
	TestCase_Utility_Buffer_##NAME(bm, source);										\
}																					\
void TestCase_Utility_Buffer_##NAME(BufferManager& bm, BufferSource source)			\

TEST_CASE_SOURCE(LockUnlockPage)
{
	auto page = bm.AllocatePage(source);
	TEST_ASSERT(page.IsValid());

	auto addr = bm.LockPage(source, page);
	TEST_ASSERT(addr != nullptr);
	TEST_ASSERT(bm.LockPage(source, page) == nullptr);

	TEST_ASSERT(bm.FreePage(source, page) == false);
	TEST_ASSERT(bm.UnlockPage(source, page, (char*)addr + 1, false) == false);
	TEST_ASSERT(bm.UnlockPage(source, page, addr, false) == true);
	TEST_ASSERT(bm.UnlockPage(source, page, addr, false) == false);

	TEST_ASSERT(bm.FreePage(source, page) == true);
	TEST_ASSERT(bm.UnlockPage(source, page, (char*)addr + 1, false) == false);
	TEST_ASSERT(bm.UnlockPage(source, page, addr, false) == false);
	TEST_ASSERT(bm.UnlockPage(source, page, addr, false) == false);
}

TEST_CASE_SOURCE(AllocateFreePage)
{
	auto indexPage = bm.GetIndexPage(source);
	TEST_ASSERT(indexPage.IsValid());

	auto page1 = bm.AllocatePage(source);
	TEST_ASSERT(page1.IsValid());
	TEST_ASSERT(page1.index != indexPage.index);
	auto page2 = bm.AllocatePage(source);
	TEST_ASSERT(page2.IsValid());
	TEST_ASSERT(page2.index != page1.index);
	TEST_ASSERT(page2.index != indexPage.index);

	auto addr0 = bm.LockPage(source, indexPage);
	TEST_ASSERT(addr0 != nullptr);
	TEST_ASSERT(bm.UnlockPage(source, indexPage, addr0, false)== true);
	TEST_ASSERT(bm.FreePage(source, indexPage) == false);

	auto addr1 = bm.LockPage(source, page1);
	TEST_ASSERT(addr1 != nullptr);
	auto addr2 = bm.LockPage(source, page2);
	TEST_ASSERT(addr2 != nullptr);

	TEST_ASSERT(bm.UnlockPage(source, page1, addr1, false) == true);
	TEST_ASSERT(bm.FreePage(source, page1) == true);
	TEST_ASSERT(bm.LockPage(source, page1) == nullptr);

	strcpy((char*)addr2, "This is page 2");
	TEST_ASSERT(bm.UnlockPage(source, page2, addr2, true) == true);

	addr2 = bm.LockPage(source, page2);
	TEST_ASSERT(addr2 != nullptr);
	TEST_ASSERT(strcmp((char*)addr2, "This is page 2") == 0);
	TEST_ASSERT(bm.UnlockPage(source, page2, addr2, false) == true);

	auto page3 = bm.AllocatePage(source);
	TEST_ASSERT(page3.index == page1.index);
	auto addr3 = bm.LockPage(source, page3);
	TEST_ASSERT(addr3 != nullptr);

	strcpy((char*)addr3, "This is page 3");
	TEST_ASSERT(bm.UnlockPage(source, page3, addr3, true) == true);

	addr2 = bm.LockPage(source, page2);
	TEST_ASSERT(addr2 != nullptr);
	addr3 = bm.LockPage(source, page3);
	TEST_ASSERT(addr3 != nullptr);
	TEST_ASSERT(strcmp((char*)addr2, "This is page 2") == 0);
	TEST_ASSERT(strcmp((char*)addr3, "This is page 3") == 0);

	TEST_ASSERT(bm.LockPage(source, page2) == nullptr);
	TEST_ASSERT(bm.UnlockPage(source, page2, addr2, true) == true);
	TEST_ASSERT(bm.LockPage(source, page3) == nullptr);
	TEST_ASSERT(bm.UnlockPage(source, page3, addr3, true) == true);
}

#define TEST_ASSERT_CACHE														\
	console::Console::Write(L"    <CACHED-PAGE-COUNT>: ");						\
	console::Console::WriteLine(itow(bm.GetCurrentlyCachedPageCount()));		\
	TEST_ASSERT(bm.GetCurrentlyCachedPageCount() <= bm.GetCachePageCount());	\

TEST_CASE(Utility_Buffer_AllocateAndSwap)
{
	BufferManager bm(4 KB, 8);
	auto s1 = bm.LoadFileSource(TEMP_DIR L"db1.bin", true);
	auto s2 = bm.LoadFileSource(TEMP_DIR L"db2.bin", true);
	BufferSource sources[] = {s1, s2};
	const wchar_t* sourceNames[] = {L"db1.bin ", L"db2.bin "};
	TEST_ASSERT(bm.GetCachePageCount() == 8);
	List<BufferPage> pages;

	for (vint i = 0; i < 16; i++)
	{
		for(vint j = 0; j < 2; j++)
		{
			auto source = sources[j];
			console::Console::WriteLine(WString(L"Allocate ") + sourceNames[j] + itow(i + 1));
			auto page = bm.AllocatePage(source);
			pages.Add(page);
			TEST_ASSERT(page.IsValid());
			TEST_ASSERT_CACHE;
			auto address = (wchar_t*)bm.LockPage(source, page);
			TEST_ASSERT(address != nullptr);
			TEST_ASSERT_CACHE;
			wcscpy(address, (WString(sourceNames[j]) + itow(i + 1)).Buffer());
			TEST_ASSERT(bm.UnlockPage(source, page, address, true));
			TEST_ASSERT_CACHE;
		}
	}

	for (vint i = 0; i < 16; i++)
	{
		for(vint j = 0; j < 2; j++)
		{
			auto source = sources[j];
			console::Console::WriteLine(WString(L"Testing ") + sourceNames[j] + itow(i + 1));
			auto page = pages[i * 2 + j];
			auto address = (wchar_t*)bm.LockPage(source, page);
			TEST_ASSERT(address != nullptr);
			TEST_ASSERT_CACHE;
			TEST_ASSERT(wcscmp(address, (WString(sourceNames[j]) + itow(i + 1)).Buffer()) == 0);
			TEST_ASSERT(bm.UnlockPage(source, page, address, true));
			TEST_ASSERT_CACHE;
		}
	}
}

// Only enable this test case when refactor BufferManager
/*
TEST_CASE(Utility_Buffer_File_AllocateFreeManyTimes)
{
	BufferManager bm(4 KB, 16);
	auto source = bm.LoadFileSource(TEMP_DIR L"db.bin", true);
	List<BufferPage> pages;
	const vint TotalCount = 1024;

	for (vint i = 0; i < TotalCount; i++)
	{
		console::Console::Write(L"Allocating " + itow(i) + L" ... ");
		auto page = bm.AllocatePage(source);
		console::Console::WriteLine(L" => page " + itow(page.index));

		if (!page.IsValid()) throw 0;
		pages.Add(page);
	}

	for (vint i = 0; i < TotalCount; i++)
	{
		console::Console::WriteLine(L"Freeing " + itow(i) + L" ... ");
		auto page = pages[i];
		if (!bm.FreePage(source, page)) throw 0;
	}

	for (vint i = 0; i < TotalCount; i++)
	{
		console::Console::Write(L"Allocating " + itow(i) + L" ... ");
		auto page = bm.AllocatePage(source);
		auto expecting = pages[TotalCount - i - 1];
		console::Console::WriteLine(L" => page " + itow(page.index) + L", expecting " + itow(expecting.index));

		if (!page.IsValid()) throw 0;
		if (page.index != expecting.index) throw 0;
	}
}
*/
<commit_msg>Use SSD to run high pressure test cases<commit_after>#include "UnitTest.h"
#include "../Source/Utility/Buffer.h"

using namespace vl;
using namespace vl::database;
using namespace vl::collections;

extern WString GetTempFolder();
#define TEMP_DIR GetTempFolder()+
#define KB *1024
#define MB *1024*1024

TEST_CASE(Utility_Buffer_AddRemoveSource)
{
	BufferManager bm(64 KB, 16);
	TEST_ASSERT(bm.GetPageSize() == 64 KB);
	TEST_ASSERT(bm.GetCacheSize() == 1 MB);
	TEST_ASSERT(bm.GetCachePageCount() == 16);

	auto a = bm.LoadMemorySource();
	auto b = bm.LoadFileSource(TEMP_DIR L"db.bin", true);
	TEST_ASSERT(bm.GetSourceFileName(a) == L"");
	TEST_ASSERT(bm.GetSourceFileName(b) == TEMP_DIR L"db.bin");

	bm.UnloadSource(a);
	bm.UnloadSource(b);
	TEST_ASSERT(bm.GetSourceFileName(a) == L"");
	TEST_ASSERT(bm.GetSourceFileName(b) == L"");

	a = bm.LoadMemorySource();
	b = bm.LoadFileSource(TEMP_DIR L"db.bin", true);
	TEST_ASSERT(bm.GetSourceFileName(a) == L"");
	TEST_ASSERT(bm.GetSourceFileName(b) == TEMP_DIR L"db.bin");
}

#define TEST_CASE_SOURCE(NAME)														\
extern void TestCase_Utility_Buffer_##NAME(BufferManager& bm, BufferSource source);	\
TEST_CASE(Utility_Buffer_InMemory_##NAME)											\
{																					\
	BufferManager bm(64 KB, 16);													\
	auto source = bm.LoadMemorySource();											\
	TestCase_Utility_Buffer_##NAME(bm, source);										\
}																					\
TEST_CASE(Utility_Buffer_File_##NAME)												\
{																					\
	BufferManager bm(64 KB, 16);													\
	auto source = bm.LoadFileSource(TEMP_DIR L"db.bin", true);						\
	TestCase_Utility_Buffer_##NAME(bm, source);										\
}																					\
void TestCase_Utility_Buffer_##NAME(BufferManager& bm, BufferSource source)			\

TEST_CASE_SOURCE(LockUnlockPage)
{
	auto page = bm.AllocatePage(source);
	TEST_ASSERT(page.IsValid());

	auto addr = bm.LockPage(source, page);
	TEST_ASSERT(addr != nullptr);
	TEST_ASSERT(bm.LockPage(source, page) == nullptr);

	TEST_ASSERT(bm.FreePage(source, page) == false);
	TEST_ASSERT(bm.UnlockPage(source, page, (char*)addr + 1, false) == false);
	TEST_ASSERT(bm.UnlockPage(source, page, addr, false) == true);
	TEST_ASSERT(bm.UnlockPage(source, page, addr, false) == false);

	TEST_ASSERT(bm.FreePage(source, page) == true);
	TEST_ASSERT(bm.UnlockPage(source, page, (char*)addr + 1, false) == false);
	TEST_ASSERT(bm.UnlockPage(source, page, addr, false) == false);
	TEST_ASSERT(bm.UnlockPage(source, page, addr, false) == false);
}

TEST_CASE_SOURCE(AllocateFreePage)
{
	auto indexPage = bm.GetIndexPage(source);
	TEST_ASSERT(indexPage.IsValid());

	auto page1 = bm.AllocatePage(source);
	TEST_ASSERT(page1.IsValid());
	TEST_ASSERT(page1.index != indexPage.index);
	auto page2 = bm.AllocatePage(source);
	TEST_ASSERT(page2.IsValid());
	TEST_ASSERT(page2.index != page1.index);
	TEST_ASSERT(page2.index != indexPage.index);

	auto addr0 = bm.LockPage(source, indexPage);
	TEST_ASSERT(addr0 != nullptr);
	TEST_ASSERT(bm.UnlockPage(source, indexPage, addr0, false)== true);
	TEST_ASSERT(bm.FreePage(source, indexPage) == false);

	auto addr1 = bm.LockPage(source, page1);
	TEST_ASSERT(addr1 != nullptr);
	auto addr2 = bm.LockPage(source, page2);
	TEST_ASSERT(addr2 != nullptr);

	TEST_ASSERT(bm.UnlockPage(source, page1, addr1, false) == true);
	TEST_ASSERT(bm.FreePage(source, page1) == true);
	TEST_ASSERT(bm.LockPage(source, page1) == nullptr);

	strcpy((char*)addr2, "This is page 2");
	TEST_ASSERT(bm.UnlockPage(source, page2, addr2, true) == true);

	addr2 = bm.LockPage(source, page2);
	TEST_ASSERT(addr2 != nullptr);
	TEST_ASSERT(strcmp((char*)addr2, "This is page 2") == 0);
	TEST_ASSERT(bm.UnlockPage(source, page2, addr2, false) == true);

	auto page3 = bm.AllocatePage(source);
	TEST_ASSERT(page3.index == page1.index);
	auto addr3 = bm.LockPage(source, page3);
	TEST_ASSERT(addr3 != nullptr);

	strcpy((char*)addr3, "This is page 3");
	TEST_ASSERT(bm.UnlockPage(source, page3, addr3, true) == true);

	addr2 = bm.LockPage(source, page2);
	TEST_ASSERT(addr2 != nullptr);
	addr3 = bm.LockPage(source, page3);
	TEST_ASSERT(addr3 != nullptr);
	TEST_ASSERT(strcmp((char*)addr2, "This is page 2") == 0);
	TEST_ASSERT(strcmp((char*)addr3, "This is page 3") == 0);

	TEST_ASSERT(bm.LockPage(source, page2) == nullptr);
	TEST_ASSERT(bm.UnlockPage(source, page2, addr2, true) == true);
	TEST_ASSERT(bm.LockPage(source, page3) == nullptr);
	TEST_ASSERT(bm.UnlockPage(source, page3, addr3, true) == true);
}

#define TEST_ASSERT_CACHE														\
	console::Console::Write(L"    <CACHED-PAGE-COUNT>: ");						\
	console::Console::WriteLine(itow(bm.GetCurrentlyCachedPageCount()));		\
	TEST_ASSERT(bm.GetCurrentlyCachedPageCount() <= bm.GetCachePageCount());	\

TEST_CASE(Utility_Buffer_AllocateAndSwap)
{
	BufferManager bm(4 KB, 8);
	auto s1 = bm.LoadFileSource(TEMP_DIR L"db1.bin", true);
	auto s2 = bm.LoadFileSource(TEMP_DIR L"db2.bin", true);
	BufferSource sources[] = {s1, s2};
	const wchar_t* sourceNames[] = {L"db1.bin ", L"db2.bin "};
	TEST_ASSERT(bm.GetCachePageCount() == 8);
	List<BufferPage> pages;

	for (vint i = 0; i < 16; i++)
	{
		for(vint j = 0; j < 2; j++)
		{
			auto source = sources[j];
			console::Console::WriteLine(WString(L"Allocate ") + sourceNames[j] + itow(i + 1));
			auto page = bm.AllocatePage(source);
			pages.Add(page);
			TEST_ASSERT(page.IsValid());
			TEST_ASSERT_CACHE;
			auto address = (wchar_t*)bm.LockPage(source, page);
			TEST_ASSERT(address != nullptr);
			TEST_ASSERT_CACHE;
			wcscpy(address, (WString(sourceNames[j]) + itow(i + 1)).Buffer());
			TEST_ASSERT(bm.UnlockPage(source, page, address, true));
			TEST_ASSERT_CACHE;
		}
	}

	for (vint i = 0; i < 16; i++)
	{
		for(vint j = 0; j < 2; j++)
		{
			auto source = sources[j];
			console::Console::WriteLine(WString(L"Testing ") + sourceNames[j] + itow(i + 1));
			auto page = pages[i * 2 + j];
			auto address = (wchar_t*)bm.LockPage(source, page);
			TEST_ASSERT(address != nullptr);
			TEST_ASSERT_CACHE;
			TEST_ASSERT(wcscmp(address, (WString(sourceNames[j]) + itow(i + 1)).Buffer()) == 0);
			TEST_ASSERT(bm.UnlockPage(source, page, address, true));
			TEST_ASSERT_CACHE;
		}
	}
}

// Only enable this test case when refactor BufferManager
TEST_CASE(Utility_Buffer_File_AllocateFreeManyTimes)
{
	BufferManager bm(4 KB, 16);
	auto source = bm.LoadFileSource(TEMP_DIR L"db.bin", true);
	List<BufferPage> pages;
	const vint TotalCount = 1024;

	for (vint i = 0; i < TotalCount; i++)
	{
		console::Console::Write(L"Allocating " + itow(i) + L" ... ");
		auto page = bm.AllocatePage(source);
		console::Console::WriteLine(L" => page " + itow(page.index));

		if (!page.IsValid()) throw 0;
		pages.Add(page);
	}

	for (vint i = 0; i < TotalCount; i++)
	{
		console::Console::WriteLine(L"Freeing " + itow(i) + L" ... ");
		auto page = pages[i];
		if (!bm.FreePage(source, page)) throw 0;
	}

	for (vint i = 0; i < TotalCount; i++)
	{
		console::Console::Write(L"Allocating " + itow(i) + L" ... ");
		auto page = bm.AllocatePage(source);
		auto expecting = pages[TotalCount - i - 1];
		console::Console::WriteLine(L" => page " + itow(page.index) + L", expecting " + itow(expecting.index));

		if (!page.IsValid()) throw 0;
		if (page.index != expecting.index) throw 0;
	}
}
<|endoftext|>


<commit_before>/****************************************************************************
 *
 *   Copyright (c) 2019 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 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.
 *
 ****************************************************************************/

/**
 * @file ObstacleAvoidance.hpp
 * This class is used to inject the setpoints of an obstacle avoidance system
 * into the FlightTasks
 *
 * @author Martina Rivizzigno
 */

#pragma once

#include <px4_defines.h>
#include <px4_module_params.h>
#include <commander/px4_custom_mode.h>
#include <drivers/drv_hrt.h>

#include <uORB/topics/position_controller_status.h>
#include <uORB/topics/vehicle_command.h>
#include <uORB/topics/vehicle_status.h>
#include <uORB/topics/vehicle_trajectory_waypoint.h>

#include <matrix/matrix/math.hpp>

#include <SubscriptionArray.hpp>

class ObstacleAvoidance : public ModuleParams
{
public:
	ObstacleAvoidance(ModuleParams *parent);
	~ObstacleAvoidance();

	bool initializeSubscriptions(SubscriptionArray &subscription_array);

	/**
	 * Inject setpoints from obstacle avoidance system into FLightTasks.
	 * @param pos_sp, position setpoint
	 * @param vel_sp, velocity setpoint
	 * @param yaw_sp, yaw setpoint
	 * @param yaw_speed_sp, yaw speed setpoint
	 */
	void prepareAvoidanceSetpoints(matrix::Vector3f &pos_sp, matrix::Vector3f &vel_sp, float &yaw_sp, float &yaw_speed_sp);

	/**
	 * Updates the desired waypoints to send to the obstacle avoidance system.
	 * @param curr_wp, current position triplet
	 * @param curr_yaw, current yaw triplet
	 * @param curr_yawspeed, current yaw speed triplet
	 * @param next_wp, next position triplet
	 * @param next_yaw, next yaw triplet
	 * @param next_yawspeed, next yaw speed triplet
	 */
	void updateAvoidanceDesiredWaypoints(const matrix::Vector3f &curr_wp, const float curr_yaw, const float curr_yawspeed,
					     const matrix::Vector3f &next_wp, const float next_yaw, const float next_yawspeed);
	/**
	 * Updates the desired setpoints to send to the obstacle avoidance system.
	 * @param pos_sp, desired position setpoint computed by the active FlightTask
	 * @param vel_sp, desired velocity setpoint computed by the active FlightTask
	 */
	void updateAvoidanceDesiredSetpoints(const matrix::Vector3f &pos_sp, const matrix::Vector3f &vel_sp);

	/**
	 * Checks the vehicle progress between previous and current position triplet.
	 * @param pos, vehicle position
	 * @param prev_wp, previous position triplet
	 * @param target_acceptance_radius, current position triplet xy acceptance radius
	 * @param closest_pt, closest point to the vehicle on the line previous-current position triplet
	 */
	void checkAvoidanceProgress(const matrix::Vector3f &pos, const matrix::Vector3f &prev_wp,
				    float target_acceptance_radius, const matrix::Vector2f &closest_pt);

private:

	uORB::Subscription<vehicle_trajectory_waypoint_s> *_sub_vehicle_trajectory_waypoint{nullptr}; /**< vehicle trajectory waypoint subscription */
	uORB::Subscription<vehicle_status_s> *_sub_vehicle_status{nullptr}; /**< vehicle status subscription */

  DEFINE_PARAMETERS(
    (ParamInt<px4::params::COM_OBS_AVOID>) COM_OBS_AVOID,             /**< obstacle avoidance enabled */
		(ParamFloat<px4::params::NAV_MC_ALT_RAD>) NAV_MC_ALT_RAD          /**< Acceptance radius for multicopter altitude */
  );

	vehicle_trajectory_waypoint_s _desired_waypoint = {};  /**< desired vehicle trajectory waypoint to be sent to OA */
	orb_advert_t _pub_traj_wp_avoidance_desired{nullptr}; /**< trajectory waypoint desired publication */
	orb_advert_t _pub_pos_control_status{nullptr}; /**< position controller status publication */
	orb_advert_t _pub_vehicle_command{nullptr}; /**< vehicle command do publication */

	matrix::Vector3f _curr_wp = {}; /**< current position triplet */

	/**
	 * Publishes vehicle trajectory waypoint desired.
	 */
	void _publish_avoidance_desired_waypoint();

	/**
	 * Publishes vehicle vehicle command.
	 */
	void _publish_vehicle_cmd_do_loiter();

};
<commit_msg>make format<commit_after>/****************************************************************************
 *
 *   Copyright (c) 2019 PX4 Development Team. All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 * 3. Neither the name PX4 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.
 *
 ****************************************************************************/

/**
 * @file ObstacleAvoidance.hpp
 * This class is used to inject the setpoints of an obstacle avoidance system
 * into the FlightTasks
 *
 * @author Martina Rivizzigno
 */

#pragma once

#include <px4_defines.h>
#include <px4_module_params.h>
#include <commander/px4_custom_mode.h>
#include <drivers/drv_hrt.h>

#include <uORB/topics/position_controller_status.h>
#include <uORB/topics/vehicle_command.h>
#include <uORB/topics/vehicle_status.h>
#include <uORB/topics/vehicle_trajectory_waypoint.h>

#include <matrix/matrix/math.hpp>

#include <SubscriptionArray.hpp>

class ObstacleAvoidance : public ModuleParams
{
public:
	ObstacleAvoidance(ModuleParams *parent);
	~ObstacleAvoidance();

	bool initializeSubscriptions(SubscriptionArray &subscription_array);

	/**
	 * Inject setpoints from obstacle avoidance system into FLightTasks.
	 * @param pos_sp, position setpoint
	 * @param vel_sp, velocity setpoint
	 * @param yaw_sp, yaw setpoint
	 * @param yaw_speed_sp, yaw speed setpoint
	 */
	void prepareAvoidanceSetpoints(matrix::Vector3f &pos_sp, matrix::Vector3f &vel_sp, float &yaw_sp, float &yaw_speed_sp);

	/**
	 * Updates the desired waypoints to send to the obstacle avoidance system.
	 * @param curr_wp, current position triplet
	 * @param curr_yaw, current yaw triplet
	 * @param curr_yawspeed, current yaw speed triplet
	 * @param next_wp, next position triplet
	 * @param next_yaw, next yaw triplet
	 * @param next_yawspeed, next yaw speed triplet
	 */
	void updateAvoidanceDesiredWaypoints(const matrix::Vector3f &curr_wp, const float curr_yaw, const float curr_yawspeed,
					     const matrix::Vector3f &next_wp, const float next_yaw, const float next_yawspeed);
	/**
	 * Updates the desired setpoints to send to the obstacle avoidance system.
	 * @param pos_sp, desired position setpoint computed by the active FlightTask
	 * @param vel_sp, desired velocity setpoint computed by the active FlightTask
	 */
	void updateAvoidanceDesiredSetpoints(const matrix::Vector3f &pos_sp, const matrix::Vector3f &vel_sp);

	/**
	 * Checks the vehicle progress between previous and current position triplet.
	 * @param pos, vehicle position
	 * @param prev_wp, previous position triplet
	 * @param target_acceptance_radius, current position triplet xy acceptance radius
	 * @param closest_pt, closest point to the vehicle on the line previous-current position triplet
	 */
	void checkAvoidanceProgress(const matrix::Vector3f &pos, const matrix::Vector3f &prev_wp,
				    float target_acceptance_radius, const matrix::Vector2f &closest_pt);

private:

	uORB::Subscription<vehicle_trajectory_waypoint_s> *_sub_vehicle_trajectory_waypoint{nullptr}; /**< vehicle trajectory waypoint subscription */
	uORB::Subscription<vehicle_status_s> *_sub_vehicle_status{nullptr}; /**< vehicle status subscription */

	DEFINE_PARAMETERS(
		(ParamInt<px4::params::COM_OBS_AVOID>) COM_OBS_AVOID,             /**< obstacle avoidance enabled */
		(ParamFloat<px4::params::NAV_MC_ALT_RAD>) NAV_MC_ALT_RAD          /**< Acceptance radius for multicopter altitude */
	);

	vehicle_trajectory_waypoint_s _desired_waypoint = {};  /**< desired vehicle trajectory waypoint to be sent to OA */
	orb_advert_t _pub_traj_wp_avoidance_desired{nullptr}; /**< trajectory waypoint desired publication */
	orb_advert_t _pub_pos_control_status{nullptr}; /**< position controller status publication */
	orb_advert_t _pub_vehicle_command{nullptr}; /**< vehicle command do publication */

	matrix::Vector3f _curr_wp = {}; /**< current position triplet */

	/**
	 * Publishes vehicle trajectory waypoint desired.
	 */
	void _publish_avoidance_desired_waypoint();

	/**
	 * Publishes vehicle vehicle command.
	 */
	void _publish_vehicle_cmd_do_loiter();

};
<|endoftext|>


<commit_before>//
// Copyright 2019 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SecondaryCommandBuffer:
//    CPU-side storage of commands to delay GPU-side allocation until commands are submitted.
//

#include "libANGLE/renderer/vulkan/SecondaryCommandBuffer.h"
#include "common/debug.h"

namespace rx
{
namespace vk
{
namespace priv
{

ANGLE_INLINE const CommandHeader *NextCommand(const CommandHeader *command)
{
    return reinterpret_cast<const CommandHeader *>(reinterpret_cast<const uint8_t *>(command) +
                                                   command->size);
}

// Parse the cmds in this cmd buffer into given primary cmd buffer
void SecondaryCommandBuffer::executeCommands(VkCommandBuffer cmdBuffer)
{
    for (const CommandHeader *command : mCommands)
    {
        for (const CommandHeader *currentCommand                      = command;
             currentCommand->id != CommandID::Invalid; currentCommand = NextCommand(currentCommand))
        {
            switch (currentCommand->id)
            {
                case CommandID::BeginQuery:
                {
                    const BeginQueryParams *params = getParamPtr<BeginQueryParams>(currentCommand);
                    vkCmdBeginQuery(cmdBuffer, params->queryPool, params->query, params->flags);
                    break;
                }
                case CommandID::BindComputePipeline:
                {
                    const BindPipelineParams *params =
                        getParamPtr<BindPipelineParams>(currentCommand);
                    vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, params->pipeline);
                    break;
                }
                case CommandID::BindDescriptorSets:
                {
                    const BindDescriptorSetParams *params =
                        getParamPtr<BindDescriptorSetParams>(currentCommand);
                    const VkDescriptorSet *descriptorSets =
                        Offset<VkDescriptorSet>(params, sizeof(BindDescriptorSetParams));
                    const uint32_t *dynamicOffsets = Offset<uint32_t>(
                        descriptorSets, sizeof(VkDescriptorSet) * params->descriptorSetCount);
                    vkCmdBindDescriptorSets(cmdBuffer, params->pipelineBindPoint, params->layout,
                                            params->firstSet, params->descriptorSetCount,
                                            descriptorSets, params->dynamicOffsetCount,
                                            dynamicOffsets);
                    break;
                }
                case CommandID::BindGraphicsPipeline:
                {
                    const BindPipelineParams *params =
                        getParamPtr<BindPipelineParams>(currentCommand);
                    vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, params->pipeline);
                    break;
                }
                case CommandID::BindIndexBuffer:
                {
                    const BindIndexBufferParams *params =
                        getParamPtr<BindIndexBufferParams>(currentCommand);
                    vkCmdBindIndexBuffer(cmdBuffer, params->buffer, params->offset,
                                         params->indexType);
                    break;
                }
                case CommandID::BindVertexBuffers:
                {
                    const BindVertexBuffersParams *params =
                        getParamPtr<BindVertexBuffersParams>(currentCommand);
                    const VkBuffer *buffers =
                        Offset<VkBuffer>(params, sizeof(BindVertexBuffersParams));
                    const VkDeviceSize *offsets =
                        Offset<VkDeviceSize>(buffers, sizeof(VkBuffer) * params->bindingCount);
                    vkCmdBindVertexBuffers(cmdBuffer, 0, params->bindingCount, buffers, offsets);
                    break;
                }
                case CommandID::BlitImage:
                {
                    const BlitImageParams *params = getParamPtr<BlitImageParams>(currentCommand);
                    vkCmdBlitImage(cmdBuffer, params->srcImage,
                                   VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, params->dstImage,
                                   VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &params->region,
                                   params->filter);
                    break;
                }
                case CommandID::ClearAttachments:
                {
                    const ClearAttachmentsParams *params =
                        getParamPtr<ClearAttachmentsParams>(currentCommand);
                    const VkClearAttachment *attachments =
                        Offset<VkClearAttachment>(params, sizeof(ClearAttachmentsParams));
                    vkCmdClearAttachments(cmdBuffer, params->attachmentCount, attachments, 1,
                                          &params->rect);
                    break;
                }
                case CommandID::ClearColorImage:
                {
                    const ClearColorImageParams *params =
                        getParamPtr<ClearColorImageParams>(currentCommand);
                    vkCmdClearColorImage(cmdBuffer, params->image, params->imageLayout,
                                         &params->color, 1, &params->range);
                    break;
                }
                case CommandID::ClearDepthStencilImage:
                {
                    const ClearDepthStencilImageParams *params =
                        getParamPtr<ClearDepthStencilImageParams>(currentCommand);
                    vkCmdClearDepthStencilImage(cmdBuffer, params->image, params->imageLayout,
                                                &params->depthStencil, 1, &params->range);
                    break;
                }
                case CommandID::CopyBuffer:
                {
                    const CopyBufferParams *params = getParamPtr<CopyBufferParams>(currentCommand);
                    const VkBufferCopy *regions =
                        Offset<VkBufferCopy>(params, sizeof(CopyBufferParams));
                    vkCmdCopyBuffer(cmdBuffer, params->srcBuffer, params->destBuffer,
                                    params->regionCount, regions);
                    break;
                }
                case CommandID::CopyBufferToImage:
                {
                    const CopyBufferToImageParams *params =
                        getParamPtr<CopyBufferToImageParams>(currentCommand);
                    vkCmdCopyBufferToImage(cmdBuffer, params->srcBuffer, params->dstImage,
                                           params->dstImageLayout, 1, &params->region);
                    break;
                }
                case CommandID::CopyImage:
                {
                    const CopyImageParams *params = getParamPtr<CopyImageParams>(currentCommand);
                    vkCmdCopyImage(cmdBuffer, params->srcImage, params->srcImageLayout,
                                   params->dstImage, params->dstImageLayout, 1, &params->region);
                    break;
                }
                case CommandID::CopyImageToBuffer:
                {
                    const CopyImageToBufferParams *params =
                        getParamPtr<CopyImageToBufferParams>(currentCommand);
                    vkCmdCopyImageToBuffer(cmdBuffer, params->srcImage, params->srcImageLayout,
                                           params->dstBuffer, 1, &params->region);
                    break;
                }
                case CommandID::Dispatch:
                {
                    const DispatchParams *params = getParamPtr<DispatchParams>(currentCommand);
                    vkCmdDispatch(cmdBuffer, params->groupCountX, params->groupCountY,
                                  params->groupCountZ);
                    break;
                }
                case CommandID::DispatchIndirect:
                {
                    const DispatchIndirectParams *params =
                        getParamPtr<DispatchIndirectParams>(currentCommand);
                    vkCmdDispatchIndirect(cmdBuffer, params->buffer, params->offset);
                    break;
                }
                case CommandID::Draw:
                {
                    const DrawParams *params = getParamPtr<DrawParams>(currentCommand);
                    vkCmdDraw(cmdBuffer, params->vertexCount, 1, params->firstVertex, 0);
                    break;
                }
                case CommandID::DrawIndexed:
                {
                    const DrawIndexedParams *params =
                        getParamPtr<DrawIndexedParams>(currentCommand);
                    vkCmdDrawIndexed(cmdBuffer, params->indexCount, 1, 0, 0, 0);
                    break;
                }
                case CommandID::DrawIndexedInstanced:
                {
                    const DrawIndexedInstancedParams *params =
                        getParamPtr<DrawIndexedInstancedParams>(currentCommand);
                    vkCmdDrawIndexed(cmdBuffer, params->indexCount, params->instanceCount, 0, 0, 0);
                    break;
                }
                case CommandID::DrawIndexedInstancedBaseVertexBaseInstance:
                {
                    const DrawIndexedInstancedBaseVertexBaseInstanceParams *params =
                        getParamPtr<DrawIndexedInstancedBaseVertexBaseInstanceParams>(
                            currentCommand);
                    vkCmdDrawIndexed(cmdBuffer, params->indexCount, params->instanceCount,
                                     params->firstIndex, params->vertexOffset,
                                     params->firstInstance);
                    break;
                }
                case CommandID::DrawInstanced:
                {
                    const DrawInstancedParams *params =
                        getParamPtr<DrawInstancedParams>(currentCommand);
                    vkCmdDraw(cmdBuffer, params->vertexCount, params->instanceCount,
                              params->firstVertex, 0);
                    break;
                }
                case CommandID::DrawInstancedBaseInstance:
                {
                    const DrawInstancedBaseInstanceParams *params =
                        getParamPtr<DrawInstancedBaseInstanceParams>(currentCommand);
                    vkCmdDraw(cmdBuffer, params->vertexCount, params->instanceCount,
                              params->firstVertex, params->firstInstance);
                    break;
                }
                case CommandID::EndQuery:
                {
                    const EndQueryParams *params = getParamPtr<EndQueryParams>(currentCommand);
                    vkCmdEndQuery(cmdBuffer, params->queryPool, params->query);
                    break;
                }
                case CommandID::ExecutionBarrier:
                {
                    const ExecutionBarrierParams *params =
                        getParamPtr<ExecutionBarrierParams>(currentCommand);
                    vkCmdPipelineBarrier(cmdBuffer, params->stageMask, params->stageMask, 0, 0,
                                         nullptr, 0, nullptr, 0, nullptr);
                    break;
                }
                case CommandID::FillBuffer:
                {
                    const FillBufferParams *params = getParamPtr<FillBufferParams>(currentCommand);
                    vkCmdFillBuffer(cmdBuffer, params->dstBuffer, params->dstOffset, params->size,
                                    params->data);
                    break;
                }
                case CommandID::ImageBarrier:
                {
                    const ImageBarrierParams *params =
                        getParamPtr<ImageBarrierParams>(currentCommand);
                    vkCmdPipelineBarrier(cmdBuffer, params->srcStageMask, params->dstStageMask, 0,
                                         0, nullptr, 0, nullptr, 1, &params->imageMemoryBarrier);
                    break;
                }
                case CommandID::MemoryBarrier:
                {
                    const MemoryBarrierParams *params =
                        getParamPtr<MemoryBarrierParams>(currentCommand);
                    vkCmdPipelineBarrier(cmdBuffer, params->srcStageMask, params->dstStageMask, 0,
                                         1, &params->memoryBarrier, 0, nullptr, 0, nullptr);
                    break;
                }
                case CommandID::PipelineBarrier:
                {
                    const PipelineBarrierParams *params =
                        getParamPtr<PipelineBarrierParams>(currentCommand);
                    const VkMemoryBarrier *memoryBarriers =
                        Offset<VkMemoryBarrier>(params, sizeof(PipelineBarrierParams));
                    const VkBufferMemoryBarrier *bufferMemoryBarriers =
                        Offset<VkBufferMemoryBarrier>(
                            memoryBarriers, params->memoryBarrierCount * sizeof(VkMemoryBarrier));
                    const VkImageMemoryBarrier *imageMemoryBarriers = Offset<VkImageMemoryBarrier>(
                        bufferMemoryBarriers,
                        params->bufferMemoryBarrierCount * sizeof(VkBufferMemoryBarrier));
                    vkCmdPipelineBarrier(cmdBuffer, params->srcStageMask, params->dstStageMask,
                                         params->dependencyFlags, params->memoryBarrierCount,
                                         memoryBarriers, params->bufferMemoryBarrierCount,
                                         bufferMemoryBarriers, params->imageMemoryBarrierCount,
                                         imageMemoryBarriers);
                    break;
                }
                case CommandID::PushConstants:
                {
                    const PushConstantsParams *params =
                        getParamPtr<PushConstantsParams>(currentCommand);
                    const void *data = Offset<void>(params, sizeof(PushConstantsParams));
                    vkCmdPushConstants(cmdBuffer, params->layout, params->flag, params->offset,
                                       params->size, data);
                    break;
                }
                case CommandID::ResetEvent:
                {
                    const ResetEventParams *params = getParamPtr<ResetEventParams>(currentCommand);
                    vkCmdResetEvent(cmdBuffer, params->event, params->stageMask);
                    break;
                }
                case CommandID::ResetQueryPool:
                {
                    const ResetQueryPoolParams *params =
                        getParamPtr<ResetQueryPoolParams>(currentCommand);
                    vkCmdResetQueryPool(cmdBuffer, params->queryPool, params->firstQuery,
                                        params->queryCount);
                    break;
                }
                case CommandID::ResolveImage:
                {
                    const ResolveImageParams *params =
                        getParamPtr<ResolveImageParams>(currentCommand);
                    vkCmdResolveImage(cmdBuffer, params->srcImage,
                                      VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, params->dstImage,
                                      VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &params->region);
                    break;
                }
                case CommandID::SetEvent:
                {
                    const SetEventParams *params = getParamPtr<SetEventParams>(currentCommand);
                    vkCmdSetEvent(cmdBuffer, params->event, params->stageMask);
                    break;
                }
                case CommandID::WaitEvents:
                {
                    const WaitEventsParams *params = getParamPtr<WaitEventsParams>(currentCommand);
                    const VkEvent *events = Offset<VkEvent>(params, sizeof(WaitEventsParams));
                    const VkMemoryBarrier *memoryBarriers =
                        Offset<VkMemoryBarrier>(events, params->eventCount * sizeof(VkEvent));
                    const VkBufferMemoryBarrier *bufferMemoryBarriers =
                        Offset<VkBufferMemoryBarrier>(
                            memoryBarriers, params->memoryBarrierCount * sizeof(VkMemoryBarrier));
                    const VkImageMemoryBarrier *imageMemoryBarriers = Offset<VkImageMemoryBarrier>(
                        bufferMemoryBarriers,
                        params->bufferMemoryBarrierCount * sizeof(VkBufferMemoryBarrier));
                    vkCmdWaitEvents(cmdBuffer, params->eventCount, events, params->srcStageMask,
                                    params->dstStageMask, params->memoryBarrierCount,
                                    memoryBarriers, params->bufferMemoryBarrierCount,
                                    bufferMemoryBarriers, params->imageMemoryBarrierCount,
                                    imageMemoryBarriers);
                    break;
                }
                case CommandID::WriteTimestamp:
                {
                    const WriteTimestampParams *params =
                        getParamPtr<WriteTimestampParams>(currentCommand);
                    vkCmdWriteTimestamp(cmdBuffer, params->pipelineStage, params->queryPool,
                                        params->query);
                    break;
                }
                default:
                {
                    UNREACHABLE();
                    break;
                }
            }
        }
    }
}

std::string SecondaryCommandBuffer::dumpCommands(const char *separator) const
{
    std::string result;
    for (const CommandHeader *command : mCommands)
    {
        for (const CommandHeader *currentCommand                      = command;
             currentCommand->id != CommandID::Invalid; currentCommand = NextCommand(currentCommand))
        {
            result += separator;
            switch (currentCommand->id)
            {
                case CommandID::BeginQuery:
                    result += "BeginQuery";
                    break;
                case CommandID::BindComputePipeline:
                    result += "BindComputePipeline";
                    break;
                case CommandID::BindDescriptorSets:
                    result += "BindDescriptorSets";
                    break;
                case CommandID::BindGraphicsPipeline:
                    result += "BindGraphicsPipeline";
                    break;
                case CommandID::BindIndexBuffer:
                    result += "BindIndexBuffer";
                    break;
                case CommandID::BindVertexBuffers:
                    result += "BindVertexBuffers";
                    break;
                case CommandID::BlitImage:
                    result += "BlitImage";
                    break;
                case CommandID::ClearAttachments:
                    result += "ClearAttachments";
                    break;
                case CommandID::ClearColorImage:
                    result += "ClearColorImage";
                    break;
                case CommandID::ClearDepthStencilImage:
                    result += "ClearDepthStencilImage";
                    break;
                case CommandID::CopyBuffer:
                    result += "CopyBuffer";
                    break;
                case CommandID::CopyBufferToImage:
                    result += "CopyBufferToImage";
                    break;
                case CommandID::CopyImage:
                    result += "CopyImage";
                    break;
                case CommandID::CopyImageToBuffer:
                    result += "CopyImageToBuffer";
                    break;
                case CommandID::Dispatch:
                    result += "Dispatch";
                    break;
                case CommandID::Draw:
                    result += "Draw";
                    break;
                case CommandID::DrawIndexed:
                    result += "DrawIndexed";
                    break;
                case CommandID::DrawIndexedInstanced:
                    result += "DrawIndexedInstanced";
                    break;
                case CommandID::DrawInstanced:
                    result += "DrawInstanced";
                    break;
                case CommandID::EndQuery:
                    result += "EndQuery";
                    break;
                case CommandID::ExecutionBarrier:
                    result += "ExecutionBarrier";
                    break;
                case CommandID::FillBuffer:
                    result += "FillBuffer";
                    break;
                case CommandID::ImageBarrier:
                    result += "ImageBarrier";
                    break;
                case CommandID::MemoryBarrier:
                    result += "MemoryBarrier";
                    break;
                case CommandID::PipelineBarrier:
                    result += "PipelineBarrier";
                    break;
                case CommandID::PushConstants:
                    result += "PushConstants";
                    break;
                case CommandID::ResetEvent:
                    result += "ResetEvent";
                    break;
                case CommandID::ResetQueryPool:
                    result += "ResetQueryPool";
                    break;
                case CommandID::SetEvent:
                    result += "SetEvent";
                    break;
                case CommandID::WaitEvents:
                    result += "WaitEvents";
                    break;
                case CommandID::WriteTimestamp:
                    result += "WriteTimestamp";
                    break;
                default:
                {
                    UNREACHABLE();
                    result += "--invalid--";
                    break;
                }
            }
        }
    }
    return result;
}

}  // namespace priv
}  // namespace vk
}  // namespace rx
<commit_msg>Vulkan: DispatchIndirect in graph dump output<commit_after>//
// Copyright 2019 The ANGLE Project Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
//
// SecondaryCommandBuffer:
//    CPU-side storage of commands to delay GPU-side allocation until commands are submitted.
//

#include "libANGLE/renderer/vulkan/SecondaryCommandBuffer.h"
#include "common/debug.h"

namespace rx
{
namespace vk
{
namespace priv
{

ANGLE_INLINE const CommandHeader *NextCommand(const CommandHeader *command)
{
    return reinterpret_cast<const CommandHeader *>(reinterpret_cast<const uint8_t *>(command) +
                                                   command->size);
}

// Parse the cmds in this cmd buffer into given primary cmd buffer
void SecondaryCommandBuffer::executeCommands(VkCommandBuffer cmdBuffer)
{
    for (const CommandHeader *command : mCommands)
    {
        for (const CommandHeader *currentCommand                      = command;
             currentCommand->id != CommandID::Invalid; currentCommand = NextCommand(currentCommand))
        {
            switch (currentCommand->id)
            {
                case CommandID::BeginQuery:
                {
                    const BeginQueryParams *params = getParamPtr<BeginQueryParams>(currentCommand);
                    vkCmdBeginQuery(cmdBuffer, params->queryPool, params->query, params->flags);
                    break;
                }
                case CommandID::BindComputePipeline:
                {
                    const BindPipelineParams *params =
                        getParamPtr<BindPipelineParams>(currentCommand);
                    vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_COMPUTE, params->pipeline);
                    break;
                }
                case CommandID::BindDescriptorSets:
                {
                    const BindDescriptorSetParams *params =
                        getParamPtr<BindDescriptorSetParams>(currentCommand);
                    const VkDescriptorSet *descriptorSets =
                        Offset<VkDescriptorSet>(params, sizeof(BindDescriptorSetParams));
                    const uint32_t *dynamicOffsets = Offset<uint32_t>(
                        descriptorSets, sizeof(VkDescriptorSet) * params->descriptorSetCount);
                    vkCmdBindDescriptorSets(cmdBuffer, params->pipelineBindPoint, params->layout,
                                            params->firstSet, params->descriptorSetCount,
                                            descriptorSets, params->dynamicOffsetCount,
                                            dynamicOffsets);
                    break;
                }
                case CommandID::BindGraphicsPipeline:
                {
                    const BindPipelineParams *params =
                        getParamPtr<BindPipelineParams>(currentCommand);
                    vkCmdBindPipeline(cmdBuffer, VK_PIPELINE_BIND_POINT_GRAPHICS, params->pipeline);
                    break;
                }
                case CommandID::BindIndexBuffer:
                {
                    const BindIndexBufferParams *params =
                        getParamPtr<BindIndexBufferParams>(currentCommand);
                    vkCmdBindIndexBuffer(cmdBuffer, params->buffer, params->offset,
                                         params->indexType);
                    break;
                }
                case CommandID::BindVertexBuffers:
                {
                    const BindVertexBuffersParams *params =
                        getParamPtr<BindVertexBuffersParams>(currentCommand);
                    const VkBuffer *buffers =
                        Offset<VkBuffer>(params, sizeof(BindVertexBuffersParams));
                    const VkDeviceSize *offsets =
                        Offset<VkDeviceSize>(buffers, sizeof(VkBuffer) * params->bindingCount);
                    vkCmdBindVertexBuffers(cmdBuffer, 0, params->bindingCount, buffers, offsets);
                    break;
                }
                case CommandID::BlitImage:
                {
                    const BlitImageParams *params = getParamPtr<BlitImageParams>(currentCommand);
                    vkCmdBlitImage(cmdBuffer, params->srcImage,
                                   VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, params->dstImage,
                                   VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &params->region,
                                   params->filter);
                    break;
                }
                case CommandID::ClearAttachments:
                {
                    const ClearAttachmentsParams *params =
                        getParamPtr<ClearAttachmentsParams>(currentCommand);
                    const VkClearAttachment *attachments =
                        Offset<VkClearAttachment>(params, sizeof(ClearAttachmentsParams));
                    vkCmdClearAttachments(cmdBuffer, params->attachmentCount, attachments, 1,
                                          &params->rect);
                    break;
                }
                case CommandID::ClearColorImage:
                {
                    const ClearColorImageParams *params =
                        getParamPtr<ClearColorImageParams>(currentCommand);
                    vkCmdClearColorImage(cmdBuffer, params->image, params->imageLayout,
                                         &params->color, 1, &params->range);
                    break;
                }
                case CommandID::ClearDepthStencilImage:
                {
                    const ClearDepthStencilImageParams *params =
                        getParamPtr<ClearDepthStencilImageParams>(currentCommand);
                    vkCmdClearDepthStencilImage(cmdBuffer, params->image, params->imageLayout,
                                                &params->depthStencil, 1, &params->range);
                    break;
                }
                case CommandID::CopyBuffer:
                {
                    const CopyBufferParams *params = getParamPtr<CopyBufferParams>(currentCommand);
                    const VkBufferCopy *regions =
                        Offset<VkBufferCopy>(params, sizeof(CopyBufferParams));
                    vkCmdCopyBuffer(cmdBuffer, params->srcBuffer, params->destBuffer,
                                    params->regionCount, regions);
                    break;
                }
                case CommandID::CopyBufferToImage:
                {
                    const CopyBufferToImageParams *params =
                        getParamPtr<CopyBufferToImageParams>(currentCommand);
                    vkCmdCopyBufferToImage(cmdBuffer, params->srcBuffer, params->dstImage,
                                           params->dstImageLayout, 1, &params->region);
                    break;
                }
                case CommandID::CopyImage:
                {
                    const CopyImageParams *params = getParamPtr<CopyImageParams>(currentCommand);
                    vkCmdCopyImage(cmdBuffer, params->srcImage, params->srcImageLayout,
                                   params->dstImage, params->dstImageLayout, 1, &params->region);
                    break;
                }
                case CommandID::CopyImageToBuffer:
                {
                    const CopyImageToBufferParams *params =
                        getParamPtr<CopyImageToBufferParams>(currentCommand);
                    vkCmdCopyImageToBuffer(cmdBuffer, params->srcImage, params->srcImageLayout,
                                           params->dstBuffer, 1, &params->region);
                    break;
                }
                case CommandID::Dispatch:
                {
                    const DispatchParams *params = getParamPtr<DispatchParams>(currentCommand);
                    vkCmdDispatch(cmdBuffer, params->groupCountX, params->groupCountY,
                                  params->groupCountZ);
                    break;
                }
                case CommandID::DispatchIndirect:
                {
                    const DispatchIndirectParams *params =
                        getParamPtr<DispatchIndirectParams>(currentCommand);
                    vkCmdDispatchIndirect(cmdBuffer, params->buffer, params->offset);
                    break;
                }
                case CommandID::Draw:
                {
                    const DrawParams *params = getParamPtr<DrawParams>(currentCommand);
                    vkCmdDraw(cmdBuffer, params->vertexCount, 1, params->firstVertex, 0);
                    break;
                }
                case CommandID::DrawIndexed:
                {
                    const DrawIndexedParams *params =
                        getParamPtr<DrawIndexedParams>(currentCommand);
                    vkCmdDrawIndexed(cmdBuffer, params->indexCount, 1, 0, 0, 0);
                    break;
                }
                case CommandID::DrawIndexedInstanced:
                {
                    const DrawIndexedInstancedParams *params =
                        getParamPtr<DrawIndexedInstancedParams>(currentCommand);
                    vkCmdDrawIndexed(cmdBuffer, params->indexCount, params->instanceCount, 0, 0, 0);
                    break;
                }
                case CommandID::DrawIndexedInstancedBaseVertexBaseInstance:
                {
                    const DrawIndexedInstancedBaseVertexBaseInstanceParams *params =
                        getParamPtr<DrawIndexedInstancedBaseVertexBaseInstanceParams>(
                            currentCommand);
                    vkCmdDrawIndexed(cmdBuffer, params->indexCount, params->instanceCount,
                                     params->firstIndex, params->vertexOffset,
                                     params->firstInstance);
                    break;
                }
                case CommandID::DrawInstanced:
                {
                    const DrawInstancedParams *params =
                        getParamPtr<DrawInstancedParams>(currentCommand);
                    vkCmdDraw(cmdBuffer, params->vertexCount, params->instanceCount,
                              params->firstVertex, 0);
                    break;
                }
                case CommandID::DrawInstancedBaseInstance:
                {
                    const DrawInstancedBaseInstanceParams *params =
                        getParamPtr<DrawInstancedBaseInstanceParams>(currentCommand);
                    vkCmdDraw(cmdBuffer, params->vertexCount, params->instanceCount,
                              params->firstVertex, params->firstInstance);
                    break;
                }
                case CommandID::EndQuery:
                {
                    const EndQueryParams *params = getParamPtr<EndQueryParams>(currentCommand);
                    vkCmdEndQuery(cmdBuffer, params->queryPool, params->query);
                    break;
                }
                case CommandID::ExecutionBarrier:
                {
                    const ExecutionBarrierParams *params =
                        getParamPtr<ExecutionBarrierParams>(currentCommand);
                    vkCmdPipelineBarrier(cmdBuffer, params->stageMask, params->stageMask, 0, 0,
                                         nullptr, 0, nullptr, 0, nullptr);
                    break;
                }
                case CommandID::FillBuffer:
                {
                    const FillBufferParams *params = getParamPtr<FillBufferParams>(currentCommand);
                    vkCmdFillBuffer(cmdBuffer, params->dstBuffer, params->dstOffset, params->size,
                                    params->data);
                    break;
                }
                case CommandID::ImageBarrier:
                {
                    const ImageBarrierParams *params =
                        getParamPtr<ImageBarrierParams>(currentCommand);
                    vkCmdPipelineBarrier(cmdBuffer, params->srcStageMask, params->dstStageMask, 0,
                                         0, nullptr, 0, nullptr, 1, &params->imageMemoryBarrier);
                    break;
                }
                case CommandID::MemoryBarrier:
                {
                    const MemoryBarrierParams *params =
                        getParamPtr<MemoryBarrierParams>(currentCommand);
                    vkCmdPipelineBarrier(cmdBuffer, params->srcStageMask, params->dstStageMask, 0,
                                         1, &params->memoryBarrier, 0, nullptr, 0, nullptr);
                    break;
                }
                case CommandID::PipelineBarrier:
                {
                    const PipelineBarrierParams *params =
                        getParamPtr<PipelineBarrierParams>(currentCommand);
                    const VkMemoryBarrier *memoryBarriers =
                        Offset<VkMemoryBarrier>(params, sizeof(PipelineBarrierParams));
                    const VkBufferMemoryBarrier *bufferMemoryBarriers =
                        Offset<VkBufferMemoryBarrier>(
                            memoryBarriers, params->memoryBarrierCount * sizeof(VkMemoryBarrier));
                    const VkImageMemoryBarrier *imageMemoryBarriers = Offset<VkImageMemoryBarrier>(
                        bufferMemoryBarriers,
                        params->bufferMemoryBarrierCount * sizeof(VkBufferMemoryBarrier));
                    vkCmdPipelineBarrier(cmdBuffer, params->srcStageMask, params->dstStageMask,
                                         params->dependencyFlags, params->memoryBarrierCount,
                                         memoryBarriers, params->bufferMemoryBarrierCount,
                                         bufferMemoryBarriers, params->imageMemoryBarrierCount,
                                         imageMemoryBarriers);
                    break;
                }
                case CommandID::PushConstants:
                {
                    const PushConstantsParams *params =
                        getParamPtr<PushConstantsParams>(currentCommand);
                    const void *data = Offset<void>(params, sizeof(PushConstantsParams));
                    vkCmdPushConstants(cmdBuffer, params->layout, params->flag, params->offset,
                                       params->size, data);
                    break;
                }
                case CommandID::ResetEvent:
                {
                    const ResetEventParams *params = getParamPtr<ResetEventParams>(currentCommand);
                    vkCmdResetEvent(cmdBuffer, params->event, params->stageMask);
                    break;
                }
                case CommandID::ResetQueryPool:
                {
                    const ResetQueryPoolParams *params =
                        getParamPtr<ResetQueryPoolParams>(currentCommand);
                    vkCmdResetQueryPool(cmdBuffer, params->queryPool, params->firstQuery,
                                        params->queryCount);
                    break;
                }
                case CommandID::ResolveImage:
                {
                    const ResolveImageParams *params =
                        getParamPtr<ResolveImageParams>(currentCommand);
                    vkCmdResolveImage(cmdBuffer, params->srcImage,
                                      VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, params->dstImage,
                                      VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL, 1, &params->region);
                    break;
                }
                case CommandID::SetEvent:
                {
                    const SetEventParams *params = getParamPtr<SetEventParams>(currentCommand);
                    vkCmdSetEvent(cmdBuffer, params->event, params->stageMask);
                    break;
                }
                case CommandID::WaitEvents:
                {
                    const WaitEventsParams *params = getParamPtr<WaitEventsParams>(currentCommand);
                    const VkEvent *events = Offset<VkEvent>(params, sizeof(WaitEventsParams));
                    const VkMemoryBarrier *memoryBarriers =
                        Offset<VkMemoryBarrier>(events, params->eventCount * sizeof(VkEvent));
                    const VkBufferMemoryBarrier *bufferMemoryBarriers =
                        Offset<VkBufferMemoryBarrier>(
                            memoryBarriers, params->memoryBarrierCount * sizeof(VkMemoryBarrier));
                    const VkImageMemoryBarrier *imageMemoryBarriers = Offset<VkImageMemoryBarrier>(
                        bufferMemoryBarriers,
                        params->bufferMemoryBarrierCount * sizeof(VkBufferMemoryBarrier));
                    vkCmdWaitEvents(cmdBuffer, params->eventCount, events, params->srcStageMask,
                                    params->dstStageMask, params->memoryBarrierCount,
                                    memoryBarriers, params->bufferMemoryBarrierCount,
                                    bufferMemoryBarriers, params->imageMemoryBarrierCount,
                                    imageMemoryBarriers);
                    break;
                }
                case CommandID::WriteTimestamp:
                {
                    const WriteTimestampParams *params =
                        getParamPtr<WriteTimestampParams>(currentCommand);
                    vkCmdWriteTimestamp(cmdBuffer, params->pipelineStage, params->queryPool,
                                        params->query);
                    break;
                }
                default:
                {
                    UNREACHABLE();
                    break;
                }
            }
        }
    }
}

std::string SecondaryCommandBuffer::dumpCommands(const char *separator) const
{
    std::string result;
    for (const CommandHeader *command : mCommands)
    {
        for (const CommandHeader *currentCommand                      = command;
             currentCommand->id != CommandID::Invalid; currentCommand = NextCommand(currentCommand))
        {
            result += separator;
            switch (currentCommand->id)
            {
                case CommandID::BeginQuery:
                    result += "BeginQuery";
                    break;
                case CommandID::BindComputePipeline:
                    result += "BindComputePipeline";
                    break;
                case CommandID::BindDescriptorSets:
                    result += "BindDescriptorSets";
                    break;
                case CommandID::BindGraphicsPipeline:
                    result += "BindGraphicsPipeline";
                    break;
                case CommandID::BindIndexBuffer:
                    result += "BindIndexBuffer";
                    break;
                case CommandID::BindVertexBuffers:
                    result += "BindVertexBuffers";
                    break;
                case CommandID::BlitImage:
                    result += "BlitImage";
                    break;
                case CommandID::ClearAttachments:
                    result += "ClearAttachments";
                    break;
                case CommandID::ClearColorImage:
                    result += "ClearColorImage";
                    break;
                case CommandID::ClearDepthStencilImage:
                    result += "ClearDepthStencilImage";
                    break;
                case CommandID::CopyBuffer:
                    result += "CopyBuffer";
                    break;
                case CommandID::CopyBufferToImage:
                    result += "CopyBufferToImage";
                    break;
                case CommandID::CopyImage:
                    result += "CopyImage";
                    break;
                case CommandID::CopyImageToBuffer:
                    result += "CopyImageToBuffer";
                    break;
                case CommandID::Dispatch:
                    result += "Dispatch";
                    break;
                case CommandID::DispatchIndirect:
                    result += "DispatchIndirect";
                    break;
                case CommandID::Draw:
                    result += "Draw";
                    break;
                case CommandID::DrawIndexed:
                    result += "DrawIndexed";
                    break;
                case CommandID::DrawIndexedInstanced:
                    result += "DrawIndexedInstanced";
                    break;
                case CommandID::DrawInstanced:
                    result += "DrawInstanced";
                    break;
                case CommandID::EndQuery:
                    result += "EndQuery";
                    break;
                case CommandID::ExecutionBarrier:
                    result += "ExecutionBarrier";
                    break;
                case CommandID::FillBuffer:
                    result += "FillBuffer";
                    break;
                case CommandID::ImageBarrier:
                    result += "ImageBarrier";
                    break;
                case CommandID::MemoryBarrier:
                    result += "MemoryBarrier";
                    break;
                case CommandID::PipelineBarrier:
                    result += "PipelineBarrier";
                    break;
                case CommandID::PushConstants:
                    result += "PushConstants";
                    break;
                case CommandID::ResetEvent:
                    result += "ResetEvent";
                    break;
                case CommandID::ResetQueryPool:
                    result += "ResetQueryPool";
                    break;
                case CommandID::SetEvent:
                    result += "SetEvent";
                    break;
                case CommandID::WaitEvents:
                    result += "WaitEvents";
                    break;
                case CommandID::WriteTimestamp:
                    result += "WriteTimestamp";
                    break;
                default:
                {
                    UNREACHABLE();
                    result += "--invalid--";
                    break;
                }
            }
        }
    }
    return result;
}

}  // namespace priv
}  // namespace vk
}  // namespace rx
<|endoftext|>