<commit_before>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file        csvparams_invalid_file_tests.cpp
 * @brief       CSV param invalid files test
 *
 * @author      t.shirayanagi
 * @par         copyright
 * Copyright (C) 2018, Takazumi Shirayanagi\n
 * This software is released under the new BSD License,
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================

//======================================================================
// include
#include "iutest.hpp"

#if IUTEST_HAS_PARAM_TEST && IUTEST_HAS_CSVPARAMS
#  define CAN_CSVPARAMS_INVALID_FILE_TEST   1
#else
#  define CAN_CSVPARAMS_INVALID_FILE_TEST   0
#endif

#if CAN_CSVPARAMS_INVALID_FILE_TEST

class CsvParamsIntTest : public ::iutest::TestWithParam< int >
{
};

IUTEST_P(CsvParamsIntTest, DoNothing)
{
}

IUTEST_INSTANTIATE_TEST_CASE_P(NotExist, CsvParamsIntTest, ::iutest::CSV<int>("testdata/not-exist?.csv") );
IUTEST_INSTANTIATE_TEST_CASE_P(EmptyCsv, CsvParamsIntTest, ::iutest::CSV<int>("testdata/empty.csv") );

#endif

#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
#if CAN_CSVPARAMS_INVALID_FILE_TEST

#if IUTEST_HAS_STREAM_BUFFER
    ::iutest::detail::IUStreamBuffer<> stderr_capture(stderr);
#endif

    IUTEST_INIT(&argc, argv);
#if defined(OUTPUTXML)
    // 失敗テストを含むので xml 出力しない
    ::iutest::IUTEST_FLAG(output) = NULL;
#endif

    const int ret = IUTEST_RUN_ALL_TESTS();
    if( ret != 0 ) return 1;
#if IUTEST_HAS_STREAM_BUFFER && IUTEST_HAS_ASSERTION_RETURN
    IUTEST_ASSERT_STRIN("Unable to open file \"testdata/not-exist?.csv\".", stderr_capture.GetStreamString())
        << ::iutest::AssertionReturn<int>(1);
    IUTEST_ASSERT_STRIN("Empty params file \"testdata/empty.csv\".", stderr_capture.GetStreamString())
        << ::iutest::AssertionReturn<int>(1);
#endif
    printf("*** Successful ***\n");
#else
    (void)argc;
    (void)argv;
    printf("*** CAN_CSVPARAMS_INVALID_FILE_TEST=0 ***\n");
#endif
    return 0;
}

<commit_msg>fix disable has fopen #133<commit_after>//======================================================================
//-----------------------------------------------------------------------
/**
 * @file        csvparams_invalid_file_tests.cpp
 * @brief       CSV param invalid files test
 *
 * @author      t.shirayanagi
 * @par         copyright
 * Copyright (C) 2018, Takazumi Shirayanagi\n
 * This software is released under the new BSD License,
 * see LICENSE
*/
//-----------------------------------------------------------------------
//======================================================================

//======================================================================
// include
#include "iutest.hpp"

#if IUTEST_HAS_PARAM_TEST && IUTEST_HAS_CSVPARAMS
#  define CAN_CSVPARAMS_INVALID_FILE_TEST   1
#else
#  define CAN_CSVPARAMS_INVALID_FILE_TEST   0
#endif

#if CAN_CSVPARAMS_INVALID_FILE_TEST

class CsvParamsIntTest : public ::iutest::TestWithParam< int >
{
};

IUTEST_P(CsvParamsIntTest, DoNothing)
{
}

IUTEST_INSTANTIATE_TEST_CASE_P(NotExist, CsvParamsIntTest, ::iutest::CSV<int>("testdata/not-exist?.csv") );
IUTEST_INSTANTIATE_TEST_CASE_P(EmptyCsv, CsvParamsIntTest, ::iutest::CSV<int>("testdata/empty.csv") );

#endif

#ifdef UNICODE
int wmain(int argc, wchar_t* argv[])
#else
int main(int argc, char* argv[])
#endif
{
#if CAN_CSVPARAMS_INVALID_FILE_TEST

#if IUTEST_HAS_STREAM_BUFFER
    ::iutest::detail::IUStreamBuffer<> stderr_capture(stderr);
#endif

    IUTEST_INIT(&argc, argv);
#if defined(OUTPUTXML)
    // 失敗テストを含むので xml 出力しない
    ::iutest::IUTEST_FLAG(output) = NULL;
#endif

    const int ret = IUTEST_RUN_ALL_TESTS();
    if( ret != 0 ) return 1;
#if IUTEST_HAS_STREAM_BUFFER && IUTEST_HAS_ASSERTION_RETURN
    IUTEST_ASSERT_STRIN("Unable to open file \"testdata/not-exist?.csv\".", stderr_capture.GetStreamString())
        << ::iutest::AssertionReturn<int>(1);
    IUTEST_ASSERT_STRIN(
#if IUTEST_HAS_FOPEN
        "Empty params file "
#else
        "Unable to open file "
#endif
        "\"testdata/empty.csv\".", stderr_capture.GetStreamString()
    ) << ::iutest::AssertionReturn<int>(1);
#endif
    printf("*** Successful ***\n");
#else
    (void)argc;
    (void)argv;
    printf("*** CAN_CSVPARAMS_INVALID_FILE_TEST=0 ***\n");
#endif
    return 0;
}

<|endoftext|>


<commit_before>/// \file simple.cxx
/// \ingroup Tutorials
/// \author Axel Naumann <axel@cern.ch>
/// \date 2015-03-22
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome!

/*************************************************************************
 * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "ROOT/THist.h"
#include "ROOT/TFit.h"
#include "ROOT/TFile.h"

R__LOAD_LIBRARY(libRIO)

void simple() {
  using namespace ROOT;

  // Create a 2D histogram with an X axis with equidistant bins, and a y axis
  // with irregular binning.
  Experimental::TAxisConfig xAxis(100, 0., 1.);
  Experimental::TAxisConfig yAxis({0., 1., 2., 3.,10.});
  Experimental::TH2D histFromVars(xAxis, yAxis);

  // Or the short in-place version:
  // Create a 2D histogram with an X axis with equidistant bins, and a y axis
  // with irregular binning.
  Experimental::TH2D hist({100, 0., 1.}, {{0., 1., 2., 3.,10.}});

  // Fill weight 1. at the coordinate 0.01, 1.02.
  hist.Fill({0.01, 1.02});

  // Fit the histogram.
  Experimental::TFunction<2> func([](const std::array<double,2>& x,
                             const std::array_view<double>& par)
                          { return par[0]*x[0]*x[0] + (par[1]-x[1])*x[1]; });

  Experimental::TFitResult fitResult = Experimental::FitTo(hist, func, {{0., 1.}});

  Experimental::TFilePtr file = Experimental::TFilePtr::Recreate("hist.root");
  file->Write("TheHist", hist);
}
<commit_msg>Adapt to interface change.<commit_after>/// \file simple.cxx
/// \ingroup Tutorials
/// \author Axel Naumann <axel@cern.ch>
/// \date 2015-03-22
/// \warning This is part of the ROOT 7 prototype! It will change without notice. It might trigger earthquakes. Feedback is welcome!

/*************************************************************************
 * Copyright (C) 1995-2015, Rene Brun and Fons Rademakers.               *
 * All rights reserved.                                                  *
 *                                                                       *
 * For the licensing terms see $ROOTSYS/LICENSE.                         *
 * For the list of contributors see $ROOTSYS/README/CREDITS.             *
 *************************************************************************/

#include "ROOT/THist.h"
#include "ROOT/TFit.h"
#include "ROOT/TFile.h"

R__LOAD_LIBRARY(libRIO)

void simple() {
  using namespace ROOT;

  // Create a 2D histogram with an X axis with equidistant bins, and a y axis
  // with irregular binning.
  Experimental::TAxisConfig xAxis(100, 0., 1.);
  Experimental::TAxisConfig yAxis({0., 1., 2., 3.,10.});
  Experimental::TH2D histFromVars(xAxis, yAxis);

  // Or the short in-place version:
  // Create a 2D histogram with an X axis with equidistant bins, and a y axis
  // with irregular binning.
  Experimental::TH2D hist({100, 0., 1.}, {{0., 1., 2., 3.,10.}});

  // Fill weight 1. at the coordinate 0.01, 1.02.
  hist.Fill({0.01, 1.02});

  // Fit the histogram.
  Experimental::TFunction<2> func([](const std::array<double,2>& x,
                             const std::array_view<double>& par)
                          { return par[0]*x[0]*x[0] + (par[1]-x[1])*x[1]; });

  Experimental::TFitResult fitResult = Experimental::FitTo(hist, func, {{0., 1.}});

  Experimental::TFilePtr file = Experimental::TFile::Recreate("hist.root");
  file->Write("TheHist", hist);
}
<|endoftext|>


<commit_before>#ifdef STAN_OPENCL
#include <stan/math/opencl/opencl.hpp>
#include <test/unit/util.hpp>
#include <gtest/gtest.h>
#include <vector>
#include <fstream>
#include <string>

TEST(MathGpu, getInfo) {
  cl::Context cl = stan::math::opencl_context.context();
  EXPECT_NE("", stan::math::opencl_context.description());
  EXPECT_NE("", stan::math::opencl_context.capabilities());
  EXPECT_GT(stan::math::opencl_context.max_thread_block_size(), 0);
}

TEST(MathGpu, context_construction) {
  cl::Context cv = stan::math::opencl_context.context();
  cl::CommandQueue cq = stan::math::opencl_context.queue();
  std::vector<cl::Device> dv = stan::math::opencl_context.device();
  std::vector<cl::Platform> pl = stan::math::opencl_context.platform();
}

TEST(opencl_context, platform) {
  std::vector<cl::Platform> all_platforms;
  cl::Platform::get(&all_platforms);
  std::stringstream msg;

  msg << "all_platforms: " << all_platforms.size() << std::endl;
  for (auto platform : all_platforms) {
    msg << "platform name: " << platform.getInfo<CL_PLATFORM_NAME>()
        << std::endl;
  }

  EXPECT_GE(all_platforms.size(), 1)
      << "expecting to find at least one platform" << std::endl
      << msg.str();
}

TEST(opencl_context, devices) {
  try {
    std::vector<cl::Platform> all_platforms;
    cl::Platform::get(&all_platforms);
    std::vector<cl::Device> all_devices;
    all_platforms[OPENCL_PLATFORM_ID].getDevices(DEVICE_FILTER, &all_devices);

    std::stringstream msg;
    msg << "all_devices: " << all_devices.size() << std::endl;
    for (auto device : all_devices) {
      msg << "- device name: " << device.getInfo<CL_DEVICE_NAME>() << std::endl;
    }

    EXPECT_GE(all_devices.size(), 1)
        << "expecting to find at least one device" << std::endl
        << msg.str();

    msg.str("");
    msg << "max_thead_block_sizes: " << std::endl;
    for (auto device : all_devices) {
      size_t thread_block_size;
      device.getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &thread_block_size);
      msg << "- thread_block_size: " << thread_block_size << std::endl;
    }
  } catch (const cl::Error& e) {
    stan::math::check_opencl_error("listing_devices_test", e);
  }
}

TEST(opencl_context, compile_kernel_rawcode) {
  // build dummy kernel
  cl::Context cl = stan::math::opencl_context.context();
  std::vector<cl::Device> dv = stan::math::opencl_context.device();
  const std::string dummy_kernel_src
      = "__kernel void dummy(__global const int* foo) { };";
  cl::Program program_(cl, {dummy_kernel_src});
  program_.build({stan::math::opencl_context.device()});
  cl::Kernel dummy_kernel = cl::Kernel(program_, "dummy");
}

TEST(opencl_context, switch_devices_errors) {
  EXPECT_NO_THROW(stan::math::opencl_context.select_device(0, 0));
  EXPECT_THROW(stan::math::opencl_context.select_device(-1, 0),
               std::system_error);
  EXPECT_THROW(stan::math::opencl_context.select_device(0, -1),
               std::system_error);
  EXPECT_THROW(stan::math::opencl_context.select_device(99999, 0),
               std::system_error);
  EXPECT_THROW(stan::math::opencl_context.select_device(0, 99999),
               std::system_error);
}

// this test only checks anything if there are multiple devices installed
TEST(opencl_context, switch_devices) {
  std::vector<cl::Platform> platforms;
  cl::Platform::get(&platforms);
  for (int i = 0; i < platforms.size(); i++) {
    std::vector<cl::Device> devices;
    platforms[i].getDevices(DEVICE_FILTER, &devices);
    for (int j = 0; j < devices.size(); j++) {
      stan::math::opencl_context.select_device(i, j);
      Eigen::MatrixXd m(2, 2);
      m << 1, 2, 3, 4;
      stan::math::matrix_cl<double> m_cl(m);
      m_cl = 2 * m_cl;
      m_cl = m_cl * m_cl;
      Eigen::MatrixXd res = stan::math::from_matrix_cl(m_cl);
      Eigen::MatrixXd correct = (2 * m) * (2 * m);
      EXPECT_MATRIX_EQ(res, correct);
    }
  }
}

#endif
<commit_msg>Update comment on the new test<commit_after>#ifdef STAN_OPENCL
#include <stan/math/opencl/opencl.hpp>
#include <test/unit/util.hpp>
#include <gtest/gtest.h>
#include <vector>
#include <fstream>
#include <string>

TEST(MathGpu, getInfo) {
  cl::Context cl = stan::math::opencl_context.context();
  EXPECT_NE("", stan::math::opencl_context.description());
  EXPECT_NE("", stan::math::opencl_context.capabilities());
  EXPECT_GT(stan::math::opencl_context.max_thread_block_size(), 0);
}

TEST(MathGpu, context_construction) {
  cl::Context cv = stan::math::opencl_context.context();
  cl::CommandQueue cq = stan::math::opencl_context.queue();
  std::vector<cl::Device> dv = stan::math::opencl_context.device();
  std::vector<cl::Platform> pl = stan::math::opencl_context.platform();
}

TEST(opencl_context, platform) {
  std::vector<cl::Platform> all_platforms;
  cl::Platform::get(&all_platforms);
  std::stringstream msg;

  msg << "all_platforms: " << all_platforms.size() << std::endl;
  for (auto platform : all_platforms) {
    msg << "platform name: " << platform.getInfo<CL_PLATFORM_NAME>()
        << std::endl;
  }

  EXPECT_GE(all_platforms.size(), 1)
      << "expecting to find at least one platform" << std::endl
      << msg.str();
}

TEST(opencl_context, devices) {
  try {
    std::vector<cl::Platform> all_platforms;
    cl::Platform::get(&all_platforms);
    std::vector<cl::Device> all_devices;
    all_platforms[OPENCL_PLATFORM_ID].getDevices(DEVICE_FILTER, &all_devices);

    std::stringstream msg;
    msg << "all_devices: " << all_devices.size() << std::endl;
    for (auto device : all_devices) {
      msg << "- device name: " << device.getInfo<CL_DEVICE_NAME>() << std::endl;
    }

    EXPECT_GE(all_devices.size(), 1)
        << "expecting to find at least one device" << std::endl
        << msg.str();

    msg.str("");
    msg << "max_thead_block_sizes: " << std::endl;
    for (auto device : all_devices) {
      size_t thread_block_size;
      device.getInfo<size_t>(CL_DEVICE_MAX_WORK_GROUP_SIZE, &thread_block_size);
      msg << "- thread_block_size: " << thread_block_size << std::endl;
    }
  } catch (const cl::Error& e) {
    stan::math::check_opencl_error("listing_devices_test", e);
  }
}

TEST(opencl_context, compile_kernel_rawcode) {
  // build dummy kernel
  cl::Context cl = stan::math::opencl_context.context();
  std::vector<cl::Device> dv = stan::math::opencl_context.device();
  const std::string dummy_kernel_src
      = "__kernel void dummy(__global const int* foo) { };";
  cl::Program program_(cl, {dummy_kernel_src});
  program_.build({stan::math::opencl_context.device()});
  cl::Kernel dummy_kernel = cl::Kernel(program_, "dummy");
}

TEST(opencl_context, switch_devices_errors) {
  EXPECT_NO_THROW(stan::math::opencl_context.select_device(0, 0));
  EXPECT_THROW(stan::math::opencl_context.select_device(-1, 0),
               std::system_error);
  EXPECT_THROW(stan::math::opencl_context.select_device(0, -1),
               std::system_error);
  EXPECT_THROW(stan::math::opencl_context.select_device(99999, 0),
               std::system_error);
  EXPECT_THROW(stan::math::opencl_context.select_device(0, 99999),
               std::system_error);
}

// Checks that select_device() works for all devices found on the system. If there are multiple devices, this also tests that select_device() calls work after another device was already in use.
TEST(opencl_context, switch_devices) {
  std::vector<cl::Platform> platforms;
  cl::Platform::get(&platforms);
  for (int i = 0; i < platforms.size(); i++) {
    std::vector<cl::Device> devices;
    platforms[i].getDevices(DEVICE_FILTER, &devices);
    for (int j = 0; j < devices.size(); j++) {
      stan::math::opencl_context.select_device(i, j);
      Eigen::MatrixXd m(2, 2);
      m << 1, 2, 3, 4;
      stan::math::matrix_cl<double> m_cl(m);
      m_cl = 2 * m_cl;
      m_cl = m_cl * m_cl;
      Eigen::MatrixXd res = stan::math::from_matrix_cl(m_cl);
      Eigen::MatrixXd correct = (2 * m) * (2 * m);
      EXPECT_MATRIX_EQ(res, correct);
    }
  }
}

#endif
<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2009 Torus Knot Software Ltd

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 "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"

#include "OgreGLES2Prerequisites.h"
#include "OgreGLES2RenderSystem.h"

#include "OgreX11EGLSupport.h"
#include "OgreX11EGLWindow.h"
#include "OgreX11EGLRenderTexture.h"
#include "OgreX11EGLContext.h"

#if (OGRE_PLATFORM != OGRE_PLATFORM_LINUX) && (OGRE_PLATFORM != OGRE_PLATFORM_TEGRA2)
	void XStringListToTextProperty(char ** prop, int num, XTextProperty * textProp){};
	Window DefaultRootWindow(Display* nativeDisplayType){return Window();};
	bool XQueryExtension(Display* nativeDisplayType, char * name, int * dummy0, int * dummy2, int * dummy3){return 0;}
	XRRScreenConfiguration * XRRGetScreenInfo(Display* nativeDisplayType, Window window ){return 0;};
	int XRRConfigCurrentConfiguration(XRRScreenConfiguration * config, Rotation * rotation){return 0;};
	XRRScreenSize * XRRConfigSizes(XRRScreenConfiguration * config, int * nSizes){return 0;};
	int XRRConfigCurrentRate(XRRScreenConfiguration * config){return 0;};
	short * XRRConfigRates(XRRScreenConfiguration * config, int sizeID, int * nRates){return 0;};
	void XRRFreeScreenConfigInfo(XRRScreenConfiguration * config){}
	int DefaultScreen(NativeDisplayType nativeDisplayType){return 0;};
	int DisplayWidth(Display* nativeDisplayType, int screen){return 0;};
	int DisplayHeight(Display* nativeDisplayType, int screen){return 0;};
	Display* XOpenDisplay(int num){return NULL;};
	void XCloseDisplay(Display* nativeDisplayType){};
	Atom XInternAtom(Display* nativeDisplayType, char * name, X11Bool isTrue) {return Atom();};
	char * DisplayString(NativeDisplayType nativeDisplayType){return 0;};
	const char * XDisplayName(char * name){return 0;};
	Visual * DefaultVisual(Display* nativeDisplayType,  int screen){return 0;};
	int XVisualIDFromVisual(Visual *v){return 0;};
	void XRRSetScreenConfigAndRate(Display* nativeDisplayType, XRRScreenConfiguration * config, Window window, int size, Rotation rotation, int mode, int currentTime ){};
	XVisualInfo * XGetVisualInfo(Display* nativeDisplayType,  int mask, XVisualInfo * info, int * n){return 0;};
	typedef int (*XErrorHandler)(Display *, XErrorEvent*);
	XErrorHandler XSetErrorHandler(XErrorHandler xErrorHandler){return 0;};
	void XDestroyWindow(Display* nativeDisplayType, Window nativeWindowType){};
	bool XGetWindowAttributes(Display* nativeDisplayType, Window nativeWindowType, XWindowAttributes * xWindowAttributes){return 0;};
	int XCreateColormap(Display* nativeDisplayType, Window nativeWindowType, int visual, int allocNone){return 0;};
	Window XCreateWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top, int width, int height, int dummy1, int depth, int inputOutput, int visual, int mask, XSetWindowAttributes * xSetWindowAttributes){return Window();};
	void XFree(void *data){};
	XWMHints * XAllocWMHints(){return 0;};
	XSizeHints * XAllocSizeHints(){return 0;};
	void XSetWMProperties(Display* nativeDisplayType, Window nativeWindowType,XTextProperty * titleprop, char * dummy1, char * dummy2, int num, XSizeHints *sizeHints, XWMHints *wmHints, char * dummy3){};
	void XSetWMProtocols(Display* nativeDisplayType, Window nativeWindowType, Atom * atom, int num){};
	void XMapWindow(Display* nativeDisplayType, Window nativeWindowType){};
	void XFlush(Display* nativeDisplayType){};
	void XMoveWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top){};
	void XResizeWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top){};
	void XQueryTree(Display* nativeDisplayType, Window nativeWindowType, Window * root, Window *parent, Window **children, unsigned int * nChildren){};
	void XSendEvent(Display* nativeDisplayType, Window nativeWindowType, int dummy1, int mask, XEvent* xevent){};
#endif

namespace Ogre {

    X11EGLSupport::X11EGLSupport()
    {
		// A connection that might be shared with the application for GL rendering:
        mGLDisplay = getGLDisplay();

 		// A connection that is NOT shared to enable independent event processing:
        mNativeDisplay = getNativeDisplay();

        int dummy = 0;

	// TODO: Probe video modes
        mCurrentMode.first.first = 1280;
        mCurrentMode.first.second = 1024;
//            mCurrentMode.first.first = DisplayWidth((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
//            mCurrentMode.first.second = DisplayHeight((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
        mCurrentMode.second = 0;
        mOriginalMode = mCurrentMode;
        mVideoModes.push_back(mCurrentMode);

        EGLConfig *glConfigs;
        int config, nConfigs = 0;

        glConfigs = chooseGLConfig(NULL, &nConfigs);

        for (config = 0; config < nConfigs; config++)
        {
            int caveat, samples;

            getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat);

            if (caveat != EGL_SLOW_CONFIG)
            {
                getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples);
                mSampleLevels.push_back(StringConverter::toString(samples));
            }
        }

        free(glConfigs);

        removeDuplicates(mSampleLevels);
    }

    X11EGLSupport::~X11EGLSupport()
    {
        if (mNativeDisplay)
        {
            XCloseDisplay((Display*)mNativeDisplay);
        }

        if (mGLDisplay)
        {
            eglTerminate(mGLDisplay);
        }
    }

    NativeDisplayType X11EGLSupport::getNativeDisplay()
    {
        if (!mNativeDisplay)
        {
	    mNativeDisplay = (NativeDisplayType)XOpenDisplay(NULL);

            if (!mNativeDisplay)
            {
                OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                            "Couldn`t open X display",
                            "X11EGLSupport::getXDisplay");
            }

            mAtomDeleteWindow = XInternAtom((Display*)mNativeDisplay, "WM_DELETE_WINDOW", True);
            mAtomFullScreen = XInternAtom((Display*)mNativeDisplay, "_NET_WM_STATE_FULLSCREEN", True);
            mAtomState = XInternAtom((Display*)mNativeDisplay, "_NET_WM_STATE", True);
        }

        return mNativeDisplay;
    }

    String X11EGLSupport::getDisplayName(void)
    {
		return String((const char*)XDisplayName(DisplayString(mNativeDisplay)));
    }

    void X11EGLSupport::switchMode(uint& width, uint& height, short& frequency)
    {
//        if (!mRandr)
//            return;

        int size = 0;
        int newSize = -1;

        VideoModes::iterator mode;
        VideoModes::iterator end = mVideoModes.end();
        VideoMode *newMode = 0;

        for(mode = mVideoModes.begin(); mode != end; size++)
        {
            if (mode->first.first >= static_cast<int>(width) &&
                mode->first.second >= static_cast<int>(height))
            {
                if (!newMode ||
                    mode->first.first < newMode->first.first ||
                    mode->first.second < newMode->first.second)
                {
                    newSize = size;
                    newMode = &(*mode);
                }
            }

            VideoMode* lastMode = &(*mode);

            while (++mode != end && mode->first == lastMode->first)
            {
                if (lastMode == newMode && mode->second == frequency)
                {
                    newMode = &(*mode);
                }
            }
        }

        if (newMode && *newMode != mCurrentMode)
        {
            XWindowAttributes winAtt;
            newMode->first.first = DisplayWidth(mNativeDisplay, 0);
            newMode->first.second = DisplayHeight(mNativeDisplay, 0);
            newMode->second = 0; // TODO: Hardcoding refresh rate for LCD's
            mCurrentMode = *newMode;
        }
    }

    XVisualInfo *X11EGLSupport::getVisualFromFBConfig(::EGLConfig glConfig)
    {
        XVisualInfo *vi, tmp;
        int vid, n;
        ::EGLDisplay glDisplay;

        glDisplay = getGLDisplay();
        mNativeDisplay = getNativeDisplay();

        if (eglGetConfigAttrib(glDisplay, glConfig, EGL_NATIVE_VISUAL_ID, &vid) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to get VISUAL_ID from glConfig",
                        __FUNCTION__);
            return 0;
        }
        EGL_CHECK_ERROR

        if (vid == 0)
        {
            const int screen_number = DefaultScreen(mNativeDisplay);
            Visual *v = DefaultVisual((Display*)mNativeDisplay, screen_number);
            vid = XVisualIDFromVisual(v);
        }

        tmp.visualid = vid;
        vi = 0;
        vi = XGetVisualInfo((Display*)mNativeDisplay,
                            VisualIDMask,
                            &tmp, &n);
        if (vi == 0)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to get X11 VISUAL",
                        __FUNCTION__);
            return 0;
        }

        return vi;
    }

    RenderWindow* X11EGLSupport::newWindow(const String &name,
                                        unsigned int width, unsigned int height,
                                        bool fullScreen,
                                        const NameValuePairList *miscParams)
    {
        EGLWindow* window = new X11EGLWindow(this);
        window->create(name, width, height, fullScreen, miscParams);

        return window;
    }

	//X11EGLSupport::getGLDisplay sets up the native variable
	//then calls EGLSupport::getGLDisplay
    EGLDisplay X11EGLSupport::getGLDisplay()
    {
        if (!mGLDisplay)
        {
            if(!mNativeDisplay)
                mNativeDisplay = getNativeDisplay();
            return EGLSupport::getGLDisplay();
        }
        return mGLDisplay;
    }

}

<commit_msg>GLES2: Use the resolution of the display as the video mode instead of hardcoding a value.<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2009 Torus Knot Software Ltd

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 "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"

#include "OgreGLES2Prerequisites.h"
#include "OgreGLES2RenderSystem.h"

#include "OgreX11EGLSupport.h"
#include "OgreX11EGLWindow.h"
#include "OgreX11EGLRenderTexture.h"
#include "OgreX11EGLContext.h"

#if (OGRE_PLATFORM != OGRE_PLATFORM_LINUX) && (OGRE_PLATFORM != OGRE_PLATFORM_TEGRA2)
	void XStringListToTextProperty(char ** prop, int num, XTextProperty * textProp){};
	Window DefaultRootWindow(Display* nativeDisplayType){return Window();};
	bool XQueryExtension(Display* nativeDisplayType, char * name, int * dummy0, int * dummy2, int * dummy3){return 0;}
	XRRScreenConfiguration * XRRGetScreenInfo(Display* nativeDisplayType, Window window ){return 0;};
	int XRRConfigCurrentConfiguration(XRRScreenConfiguration * config, Rotation * rotation){return 0;};
	XRRScreenSize * XRRConfigSizes(XRRScreenConfiguration * config, int * nSizes){return 0;};
	int XRRConfigCurrentRate(XRRScreenConfiguration * config){return 0;};
	short * XRRConfigRates(XRRScreenConfiguration * config, int sizeID, int * nRates){return 0;};
	void XRRFreeScreenConfigInfo(XRRScreenConfiguration * config){}
	int DefaultScreen(NativeDisplayType nativeDisplayType){return 0;};
	int DisplayWidth(Display* nativeDisplayType, int screen){return 0;};
	int DisplayHeight(Display* nativeDisplayType, int screen){return 0;};
	Display* XOpenDisplay(int num){return NULL;};
	void XCloseDisplay(Display* nativeDisplayType){};
	Atom XInternAtom(Display* nativeDisplayType, char * name, X11Bool isTrue) {return Atom();};
	char * DisplayString(NativeDisplayType nativeDisplayType){return 0;};
	const char * XDisplayName(char * name){return 0;};
	Visual * DefaultVisual(Display* nativeDisplayType,  int screen){return 0;};
	int XVisualIDFromVisual(Visual *v){return 0;};
	void XRRSetScreenConfigAndRate(Display* nativeDisplayType, XRRScreenConfiguration * config, Window window, int size, Rotation rotation, int mode, int currentTime ){};
	XVisualInfo * XGetVisualInfo(Display* nativeDisplayType,  int mask, XVisualInfo * info, int * n){return 0;};
	typedef int (*XErrorHandler)(Display *, XErrorEvent*);
	XErrorHandler XSetErrorHandler(XErrorHandler xErrorHandler){return 0;};
	void XDestroyWindow(Display* nativeDisplayType, Window nativeWindowType){};
	bool XGetWindowAttributes(Display* nativeDisplayType, Window nativeWindowType, XWindowAttributes * xWindowAttributes){return 0;};
	int XCreateColormap(Display* nativeDisplayType, Window nativeWindowType, int visual, int allocNone){return 0;};
	Window XCreateWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top, int width, int height, int dummy1, int depth, int inputOutput, int visual, int mask, XSetWindowAttributes * xSetWindowAttributes){return Window();};
	void XFree(void *data){};
	XWMHints * XAllocWMHints(){return 0;};
	XSizeHints * XAllocSizeHints(){return 0;};
	void XSetWMProperties(Display* nativeDisplayType, Window nativeWindowType,XTextProperty * titleprop, char * dummy1, char * dummy2, int num, XSizeHints *sizeHints, XWMHints *wmHints, char * dummy3){};
	void XSetWMProtocols(Display* nativeDisplayType, Window nativeWindowType, Atom * atom, int num){};
	void XMapWindow(Display* nativeDisplayType, Window nativeWindowType){};
	void XFlush(Display* nativeDisplayType){};
	void XMoveWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top){};
	void XResizeWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top){};
	void XQueryTree(Display* nativeDisplayType, Window nativeWindowType, Window * root, Window *parent, Window **children, unsigned int * nChildren){};
	void XSendEvent(Display* nativeDisplayType, Window nativeWindowType, int dummy1, int mask, XEvent* xevent){};
#endif

namespace Ogre {

    X11EGLSupport::X11EGLSupport()
    {
        // A connection that might be shared with the application for GL rendering:
        mGLDisplay = getGLDisplay();

        // A connection that is NOT shared to enable independent event processing:
        mNativeDisplay = getNativeDisplay();

        int dummy = 0;

	// TODO: Probe video modes
        mCurrentMode.first.first = DisplayWidth(mNativeDisplay, DefaultScreen(mNativeDisplay));
        mCurrentMode.first.second = DisplayHeight(mNativeDisplay, DefaultScreen(mNativeDisplay));
        mCurrentMode.second = 0;

        mOriginalMode = mCurrentMode;

        mVideoModes.push_back(mCurrentMode);

        EGLConfig *glConfigs;
        int config, nConfigs = 0;

        glConfigs = chooseGLConfig(NULL, &nConfigs);

        for (config = 0; config < nConfigs; config++)
        {
            int caveat, samples;

            getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat);

            if (caveat != EGL_SLOW_CONFIG)
            {
                getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples);
                mSampleLevels.push_back(StringConverter::toString(samples));
            }
        }

        free(glConfigs);

        removeDuplicates(mSampleLevels);
    }

    X11EGLSupport::~X11EGLSupport()
    {
        if (mNativeDisplay)
        {
            XCloseDisplay((Display*)mNativeDisplay);
        }

        if (mGLDisplay)
        {
            eglTerminate(mGLDisplay);
        }
    }

    NativeDisplayType X11EGLSupport::getNativeDisplay()
    {
        if (!mNativeDisplay)
        {
	    mNativeDisplay = (NativeDisplayType)XOpenDisplay(NULL);

            if (!mNativeDisplay)
            {
                OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                            "Couldn`t open X display",
                            "X11EGLSupport::getXDisplay");
            }

            mAtomDeleteWindow = XInternAtom((Display*)mNativeDisplay, "WM_DELETE_WINDOW", True);
            mAtomFullScreen = XInternAtom((Display*)mNativeDisplay, "_NET_WM_STATE_FULLSCREEN", True);
            mAtomState = XInternAtom((Display*)mNativeDisplay, "_NET_WM_STATE", True);
        }

        return mNativeDisplay;
    }

    String X11EGLSupport::getDisplayName(void)
    {
		return String((const char*)XDisplayName(DisplayString(mNativeDisplay)));
    }

    void X11EGLSupport::switchMode(uint& width, uint& height, short& frequency)
    {
//        if (!mRandr)
//            return;

        int size = 0;
        int newSize = -1;

        VideoModes::iterator mode;
        VideoModes::iterator end = mVideoModes.end();
        VideoMode *newMode = 0;

        for(mode = mVideoModes.begin(); mode != end; size++)
        {
            if (mode->first.first >= static_cast<int>(width) &&
                mode->first.second >= static_cast<int>(height))
            {
                if (!newMode ||
                    mode->first.first < newMode->first.first ||
                    mode->first.second < newMode->first.second)
                {
                    newSize = size;
                    newMode = &(*mode);
                }
            }

            VideoMode* lastMode = &(*mode);

            while (++mode != end && mode->first == lastMode->first)
            {
                if (lastMode == newMode && mode->second == frequency)
                {
                    newMode = &(*mode);
                }
            }
        }

        if (newMode && *newMode != mCurrentMode)
        {
            XWindowAttributes winAtt;
            newMode->first.first = DisplayWidth(mNativeDisplay, 0);
            newMode->first.second = DisplayHeight(mNativeDisplay, 0);
            newMode->second = 0; // TODO: Hardcoding refresh rate for LCD's
            mCurrentMode = *newMode;
        }
    }

    XVisualInfo *X11EGLSupport::getVisualFromFBConfig(::EGLConfig glConfig)
    {
        XVisualInfo *vi, tmp;
        int vid, n;
        ::EGLDisplay glDisplay;

        glDisplay = getGLDisplay();
        mNativeDisplay = getNativeDisplay();

        if (eglGetConfigAttrib(glDisplay, glConfig, EGL_NATIVE_VISUAL_ID, &vid) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to get VISUAL_ID from glConfig",
                        __FUNCTION__);
            return 0;
        }
        EGL_CHECK_ERROR

        if (vid == 0)
        {
            const int screen_number = DefaultScreen(mNativeDisplay);
            Visual *v = DefaultVisual((Display*)mNativeDisplay, screen_number);
            vid = XVisualIDFromVisual(v);
        }

        tmp.visualid = vid;
        vi = 0;
        vi = XGetVisualInfo((Display*)mNativeDisplay,
                            VisualIDMask,
                            &tmp, &n);
        if (vi == 0)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to get X11 VISUAL",
                        __FUNCTION__);
            return 0;
        }

        return vi;
    }

    RenderWindow* X11EGLSupport::newWindow(const String &name,
                                        unsigned int width, unsigned int height,
                                        bool fullScreen,
                                        const NameValuePairList *miscParams)
    {
        EGLWindow* window = new X11EGLWindow(this);
        window->create(name, width, height, fullScreen, miscParams);

        return window;
    }

	//X11EGLSupport::getGLDisplay sets up the native variable
	//then calls EGLSupport::getGLDisplay
    EGLDisplay X11EGLSupport::getGLDisplay()
    {
        if (!mGLDisplay)
        {
            if(!mNativeDisplay)
                mNativeDisplay = getNativeDisplay();
            return EGLSupport::getGLDisplay();
        }
        return mGLDisplay;
    }

}

<|endoftext|>


<commit_before>#include	"Action/MoveTo.hh"

/**
   Move to a location

   @param x,y           Coordinates of the destination
   @param allowApprox   If the bot should stop 1 tile before the destination
 */
Action::MoveTo::MoveTo(uint16_t x, uint16_t y, bool allowApprox)
  : _owInit(false), _approx(allowApprox), _tx(x), _ty(y), _tid(-1), _path(NULL)
{
  addListener("onFrame", &Action::MoveTo::_checkNPCMovement);
}

/**
   Move to a person

   @param tid           Index of the person in the person array
 */
Action::MoveTo::MoveTo(uint8_t tid)
  : _owInit(false), _approx(true), _tx(0), _ty(0), _tid(tid), _path(NULL)
{
  addListener("onFrame", &Action::MoveTo::_checkNPCMovement);
}

Action::MoveTo::~MoveTo()
{
}

void		Action::MoveTo::addListener(const std::string &signal, void (Action::MoveTo::*listener)())
{
  std::function<void (AAction *)> l = [listener](AAction *that){(static_cast<Action::MoveTo *>(that)->*listener)();};

  _listeners[signal].push_back(l);
}

void		Action::MoveTo::_checkNPCMovement()
{
  const OverWorld	*ows = _data.overWorlds();

  for (int i = 1; _owInit && i < 16 && (ows[i].getMap() || ows[i].getBank()); i++)
    {
      if (ows[i].getBank() == _data.player().getBank() &&	// If the overworld is in our map
	  ows[i].getMap() == _data.player().getMap() &&
	  (ows[i].getDestX() != _oldow[i].getDestX() ||		// If the overworld is moving
	   ows[i].getDestY() != _oldow[i].getDestY() ||
	   ows[i].getBank() != _oldow[i].getBank() ||		// Or if it's a new overworld
	   ows[i].getMap() != _oldow[i].getMap()))
	emit("onInit");
    }
  memcpy((void *) (_oldow + 1), (void *) (ows + 1), 15 * sizeof(OverWorld));
  _owInit = true;
}

void		Action::MoveTo::_releaseKeys()
{
  for (uint8_t i = KEY_LEFT; i <= KEY_DOWN; i++)
    sdlSetButton((EKey) i, false);
}

void            Action::MoveTo::_updateTargetPos()
{
  if (_tid == -1)
    return;

  const OverWorld	*ows = _data.overWorlds();
  Player	&p = _data.player();
  World::Map    &m = _data.world()[p.getBank()][p.getMap()];

  _tx = m.persons[_tid].x;
  _ty = m.persons[_tid].y;
  for (int i = 1; i < 16 && (ows[i].getMap() || ows[i].getBank()); i++)
    {
      if (ows[i].getEventNb() == m.persons[_tid].evtNb)
        {
          _tx = ows[i].getDestX();
          _ty = ows[i].getDestY();
          return;
        }
    }
}

void            Action::MoveTo::_searchBehindBar()
{
  Player	&p = _data.player();
  World::Map    &m = _data.world()[p.getBank()][p.getMap()];

  for (int i = 0; i < 4; i++)
    {
      int       x = _tx + !(i & 1) * (i - 1);
      int       y = _ty + (i & 1) * (i - 2);
      // Person is behind a bar
      if (m.data[y][x].attr->behavior == 0x80)
        {
          _tx = x;
          _ty = y;
          _tid = -1;
          _init();
          return;
        }
    }
}

void		Action::MoveTo::_init()
{
  Player	&p = _data.player();
  PathFinder	finder(_data.world()[p.getBank()][p.getMap()]);

  if (_tid != -1 && _tid >= _data.world()[p.getBank()][p.getMap()].nbPersons)
    {
      fprintf(stderr, "%d is not a valid person ID\n", _tid);
      _state = Action::ERROR;
      return;
    }
  _updateTargetPos();
  _pathi = 1;
  if (_path)
    {
      delete _path;
      _path = NULL;
    }
  _oldx = p.getX();
  _oldy = p.getY();
  if (p.getX() == _tx && p.getY() == _ty)
    {
      _state = Action::FINISHED;
      return;
    }
  _path = finder.search(p.getX(), p.getY(), _tx, _ty, _approx);
  if (!_path && _tid != -1)
    _searchBehindBar();
  _state = _path ? Action::RUNNING : Action::ERROR;
}

void		Action::MoveTo::_update()
{
  const OverWorld       &ow = _data.overWorld(0);
  World::Map::Node      *end = (*_path)[_path->size() - 1];
  Player	&p = _data.player();
  bool		moved = _oldx != p.getX() || _oldy != p.getY();

  if (_path && _pathi == _path->size() &&
      ow.getCurrX() == end->x && ow.getCurrY() == end->y)
    {
      _state = Action::FINISHED;
      delete _path;
      _path = NULL;
    }
  else if (_path && _pathi < _path->size() && (_pathi == 1 || moved) &&
           (ow.getDestX() != end->x || ow.getDestY() != end->y))
    {
      int	dx = (*_path)[_pathi]->x - p.getX();
      int	dy = (*_path)[_pathi]->y - p.getY();
      EKey	k;

      _releaseKeys();
      if (!dx)
	k = dy < 0 ? KEY_UP : KEY_DOWN;
      else
	k = dx < 0 ? KEY_LEFT : KEY_RIGHT;
      sdlSetButton(k, true);
      _pathi++;
    }
  if (ow.getDestX() == end->x && ow.getDestY() == end->y)
    _releaseKeys();
  _oldx = p.getX();
  _oldy = p.getY();
}
<commit_msg>fix: moveTo failing after battles<commit_after>#include	"Action/MoveTo.hh"

/**
   Move to a location

   @param x,y           Coordinates of the destination
   @param allowApprox   If the bot should stop 1 tile before the destination
 */
Action::MoveTo::MoveTo(uint16_t x, uint16_t y, bool allowApprox)
  : _owInit(false), _approx(allowApprox), _tx(x), _ty(y), _tid(-1), _path(NULL)
{
  addListener("onFrame", &Action::MoveTo::_checkNPCMovement);
}

/**
   Move to a person

   @param tid           Index of the person in the person array
 */
Action::MoveTo::MoveTo(uint8_t tid)
  : _owInit(false), _approx(true), _tx(0), _ty(0), _tid(tid), _path(NULL)
{
  addListener("onFrame", &Action::MoveTo::_checkNPCMovement);
}

Action::MoveTo::~MoveTo()
{
}

void		Action::MoveTo::addListener(const std::string &signal, void (Action::MoveTo::*listener)())
{
  std::function<void (AAction *)> l = [listener](AAction *that){(static_cast<Action::MoveTo *>(that)->*listener)();};

  _listeners[signal].push_back(l);
}

void		Action::MoveTo::_checkNPCMovement()
{
  const OverWorld	*ows = _data.overWorlds();

  for (int i = 1; _owInit && i < 16 && (ows[i].getMap() || ows[i].getBank()); i++)
    {
      if (ows[i].getBank() == _data.player().getBank() &&	// If the overworld is in our map
	  ows[i].getMap() == _data.player().getMap() &&
	  (ows[i].getDestX() != _oldow[i].getDestX() ||		// If the overworld is moving
	   ows[i].getDestY() != _oldow[i].getDestY() ||
	   ows[i].getBank() != _oldow[i].getBank() ||		// Or if it's a new overworld
	   ows[i].getMap() != _oldow[i].getMap()))
	emit("onInit");
    }
  memcpy((void *) (_oldow + 1), (void *) (ows + 1), 15 * sizeof(OverWorld));
  _owInit = true;
}

void		Action::MoveTo::_releaseKeys()
{
  for (uint8_t i = KEY_LEFT; i <= KEY_DOWN; i++)
    sdlSetButton((EKey) i, false);
}

void            Action::MoveTo::_updateTargetPos()
{
  if (_tid == -1)
    return;

  const OverWorld	*ows = _data.overWorlds();
  Player	&p = _data.player();
  World::Map    &m = _data.world()[p.getBank()][p.getMap()];

  _tx = m.persons[_tid].x;
  _ty = m.persons[_tid].y;
  for (int i = 1; i < 16 && (ows[i].getMap() || ows[i].getBank()); i++)
    {
      if (ows[i].getEventNb() == m.persons[_tid].evtNb)
        {
          _tx = ows[i].getDestX();
          _ty = ows[i].getDestY();
          return;
        }
    }
}

void            Action::MoveTo::_searchBehindBar()
{
  Player	&p = _data.player();
  World::Map    &m = _data.world()[p.getBank()][p.getMap()];

  for (int i = 0; i < 4; i++)
    {
      int       x = _tx + !(i & 1) * (i - 1);
      int       y = _ty + (i & 1) * (i - 2);
      // Person is behind a bar
      if (m.data[y][x].attr->behavior == 0x80)
        {
          _tx = x;
          _ty = y;
          _tid = -1;
          _init();
          return;
        }
    }
}

void		Action::MoveTo::_init()
{
  Player	&p = _data.player();
  PathFinder	finder(_data.world()[p.getBank()][p.getMap()]);

  if (_tid != -1 && _tid >= _data.world()[p.getBank()][p.getMap()].nbPersons)
    {
      fprintf(stderr, "%d is not a valid person ID\n", _tid);
      _state = Action::ERROR;
      return;
    }
  _updateTargetPos();
  _pathi = 1;
  if (_path)
    {
      delete _path;
      _path = NULL;
    }
  _oldx = p.getX();
  _oldy = p.getY();
  if (p.getX() == _tx && p.getY() == _ty)
    {
      _state = Action::FINISHED;
      return;
    }
  _path = finder.search(p.getX(), p.getY(), _tx, _ty, _approx);
  if (!_path && _tid != -1)
    _searchBehindBar();
  _state = _path ? Action::RUNNING : Action::ERROR;
}

void		Action::MoveTo::_update()
{
  const OverWorld       &ow = _data.overWorld(0);
  World::Map::Node      *end = (*_path)[_path->size() - 1];
  Player	&p = _data.player();
  bool		moved = _oldx != ow.getDestX() || _oldy != ow.getDestY();

  if (_path && _pathi == _path->size() &&
      ow.getCurrX() == end->x && ow.getCurrY() == end->y)
    {
      _state = Action::FINISHED;
      delete _path;
      _path = NULL;
    }
  else if (_path && _pathi < _path->size() && (_pathi == 1 || moved) &&
           (ow.getDestX() != end->x || ow.getDestY() != end->y))
    {
      int	dx = (*_path)[_pathi]->x - ow.getDestX();
      int	dy = (*_path)[_pathi]->y - ow.getDestY();
      EKey	k;

      _releaseKeys();
      if (!dx)
	k = dy < 0 ? KEY_UP : KEY_DOWN;
      else
	k = dx < 0 ? KEY_LEFT : KEY_RIGHT;
      sdlSetButton(k, true);
      _pathi++;
    }
  if (ow.getDestX() == end->x && ow.getDestY() == end->y)
    _releaseKeys();
  _oldx = ow.getDestX();
  _oldy = ow.getDestY();
}
<|endoftext|>


<commit_before>#ifndef COMPARATOR_HPP
	#define COMPARATOR_HPP
	#include <cstring>
	#include <opencv2/core/core.hpp>
	#include "math.h"
	#include <algorithm>
	#include <list>
	#include <vector>
	#include <utility>

	#ifdef WITH_TESTS
		#ifdef TEST_PRIVATE_PART
			#define private public
		#endif
	#endif

	typedef unsigned int uint;
	int const channels = 3;//not a parameter, only for convinience
	typedef unsigned char TYPE;
	typedef int DTYPE;

		enum Transition
		{
			no = 1 << 0,
			fwd = 1 << 1,
			back = 1 << 2,
			biFwdBack= fwd | back,
			upToDw = 1 << 3,
			dwToUp = 1 << 4,
			biUpDw = upToDw | dwToUp,
			lToR = 1 << 5,
			rToL = 1 << 6,
			biLR = lToR | rToL,
			biLUp = lToR | upToDw,
			biLDw = lToR | dwToUp,
			biRUp = rToL | upToDw,
			biRDw = rToL | dwToUp,
			all = biLR | biUpDw,
		};

		inline Transition& operator|=(Transition& a, const Transition& b)
		{return a = static_cast<Transition>((a) | (b));}

		struct IndexTransition
		{
			unsigned int row;
			unsigned int col;
			Transition transition;

			bool same_position( IndexTransition& b )
			{
				return ( ( row == b.row ) && ( col == b.col ) ) ? true : false;
			}

			unsigned int index(cv::Mat& img)
			{
				return row * img.step + col;
			}
		};

		class DataProcess;

		template <class TYPE>
		class Classifier;

		template <class TYPE>
		class IterateProcess
		{
		public:
			IterateProcess( cv::Mat&, TYPE, double, double, double[] );
			std::vector<IndexTransition> iterate_HV();
		private:
			cv::Mat_<TYPE> img;//reference by default
			Classifier<TYPE> classifier;

			std::vector<IndexTransition> iterate_H();
			std::vector<IndexTransition> iterate_V();

		};

		template <class TYPE>
		class Classifier
		{
		public:
			Classifier( TYPE, double, double, double[] );
			void copy_pix(TYPE[], TYPE[]);
			Transition f_classifier();
			#ifdef WITH_TESTS
				void set_parameters( TYPE, double, double, double[] );
			#endif
		private:
			TYPE pix0[channels];
			TYPE pix1[channels];
			TYPE acceptanceLevel;
			double lightThreshold;
			double colorThreshold;
			double colorBalance[channels];
			double lightDistance;

			void correct_pix0();
			double color_distance();
			double light_distance();

			bool brighter();
			void swap();
		};

		extern "C"
		{

		}

#endif<commit_msg>rearabge trabsition 	modified:   ../lib/include/libcomparator.hpp<commit_after>#ifndef COMPARATOR_HPP
	#define COMPARATOR_HPP
	#include <cstring>
	#include <opencv2/core/core.hpp>
	#include "math.h"
	#include <algorithm>
	#include <list>
	#include <vector>
	#include <utility>

	#ifdef WITH_TESTS
		#ifdef TEST_PRIVATE_PART
			#define private public
		#endif
	#endif

	typedef unsigned int uint;
	int const channels = 3;//not a parameter, only for convinience
	typedef unsigned char TYPE;
	typedef int DTYPE;

		enum Transition
		{
			no = 1 << 0,
			fwd = 1 << 1,
			back = 1 << 2,
			biFwdBack= fwd | back,

			lToR = 1 << 3,
			dwToUp = lToR << 1,
			rToL = lToR << 2,
			upToDw = lToR << 3,

			biLDw = lToR | dwToUp,
			biRDw = biLDw << 1,
			biRUp = biLDw << 2,
			biLUp = biLDw << 3,

			biLR = lToR | rToL,
			biUpDw = biLR << 1,

			all = biLR | biUpDw,
		};

		inline Transition& operator|=(Transition& a, const Transition& b)
		{return a = static_cast<Transition>((a) | (b));}

		struct IndexTransition
		{
			unsigned int row;
			unsigned int col;
			Transition transition;

			bool same_position( IndexTransition& b )
			{
				return ( ( row == b.row ) && ( col == b.col ) ) ? true : false;
			}

			unsigned int index(cv::Mat& img)
			{
				return row * img.step + col;
			}
		};

		class DataProcess;

		template <class TYPE>
		class Classifier;

		template <class TYPE>
		class IterateProcess
		{
		public:
			IterateProcess( cv::Mat&, TYPE, double, double, double[] );
			std::vector<IndexTransition> iterate_HV();
		private:
			cv::Mat_<TYPE> img;//reference by default
			Classifier<TYPE> classifier;

			std::vector<IndexTransition> iterate_H();
			std::vector<IndexTransition> iterate_V();

		};

		template <class TYPE>
		class Classifier
		{
		public:
			Classifier( TYPE, double, double, double[] );
			void copy_pix(TYPE[], TYPE[]);
			Transition f_classifier();
			#ifdef WITH_TESTS
				void set_parameters( TYPE, double, double, double[] );
			#endif
		private:
			TYPE pix0[channels];
			TYPE pix1[channels];
			TYPE acceptanceLevel;
			double lightThreshold;
			double colorThreshold;
			double colorBalance[channels];
			double lightDistance;

			void correct_pix0();
			double color_distance();
			double light_distance();

			bool brighter();
			void swap();
		};

		extern "C"
		{

		}

#endif<|endoftext|>


<commit_before>#include "CppUTest/TestHarness.h"
#include "CppUTest/TestMemoryAllocator.h"
#include "CppUTest/MemoryLeakDetector.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/PlatformSpecificFunctions.h"
#include "CppUTest/TestTestingFixture.h"
#include "AllocationInCppFile.h"

#include "CppUTest/TestHarness_c.h"
#include "AllocationInCFile.h"

TEST_GROUP(BasicBehavior)
{
};

TEST(BasicBehavior, CanDeleteNullPointers)
{
    delete (char*) NULLPTR;
    delete [] (char*) NULLPTR;
}

#ifndef CPPUTEST_MEM_LEAK_DETECTION_DISABLED

CPPUTEST_DO_NOT_SANITIZE_ADDRESS
static void deleteArrayInvalidatesMemory()
{
    unsigned char* memory = new unsigned char[10];
    PlatformSpecificMemset(memory, 0xAB, 10);
    delete [] memory;
    CHECK(memory[5] != 0xCB);
}

TEST(BasicBehavior, deleteArrayInvalidatesMemory)
{
    deleteArrayInvalidatesMemory();
}

CPPUTEST_DO_NOT_SANITIZE_ADDRESS
static void deleteInvalidatesMemory()
{
    unsigned char* memory = new unsigned char;
    *memory = 0xAD;
    delete memory;
    CHECK(*memory != 0xAD);
}

TEST(BasicBehavior, deleteInvalidatesMemory)
{
    deleteInvalidatesMemory();
}

#if __cplusplus >= 201402L
TEST(BasicBehavior, DeleteWithSizeParameterWorks)
{
    char* charMemory = new char;
    char* charArrayMemory = new char[10];
    ::operator delete(charMemory, sizeof(char));
    ::operator delete[](charArrayMemory, sizeof(char)* 10);
}
#endif

static void deleteUnallocatedMemory()
{
    delete (char*) 0x1234678;
    FAIL("Should never come here"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(BasicBehavior, deleteWillNotThrowAnExceptionWhenDeletingUnallocatedMemoryButCanStillCauseTestFailures)
{
    /*
     * Test failure might cause an exception. But according to C++ standard, you aren't allowed
     * to throw exceptions in the delete function. If you do that, it will call std::terminate.
     * Therefore, the delete will need to fail without exceptions.
     */
    MemoryLeakFailure* defaultReporter = MemoryLeakWarningPlugin::getGlobalFailureReporter();
    TestTestingFixture fixture;
    fixture.setTestFunction(deleteUnallocatedMemory);
    fixture.runAllTests();
    LONGS_EQUAL(1, fixture.getFailureCount());
    POINTERS_EQUAL(defaultReporter, MemoryLeakWarningPlugin::getGlobalFailureReporter());
}

#endif

#ifdef CPPUTEST_USE_MALLOC_MACROS

/* This include is added because *sometimes* the cstdlib does an #undef. This should have been prevented */
#if CPPUTEST_USE_STD_CPP_LIB
#include <cstdlib>
#endif

TEST(BasicBehavior, bothMallocAndFreeAreOverloaded)
{
    void* memory = cpputest_malloc_location(sizeof(char), "file", 10);
    free(memory);

    memory = malloc(sizeof(unsigned char));
    cpputest_free_location(memory, "file", 10);
}

#endif

#if CPPUTEST_USE_MEM_LEAK_DETECTION

CPPUTEST_DO_NOT_SANITIZE_ADDRESS
static void freeInvalidatesMemory()
{
    unsigned char* memory = (unsigned char*) cpputest_malloc(sizeof(unsigned char));
    *memory = 0xAD;
    cpputest_free(memory);
    CHECK(*memory != 0xAD);
}

TEST(BasicBehavior, freeInvalidatesMemory)
{
    freeInvalidatesMemory();
}
#endif

TEST_GROUP(MemoryLeakOverridesToBeUsedInProductionCode)
{
    MemoryLeakDetector* memLeakDetector;
    void setup()
    {
        memLeakDetector = MemoryLeakWarningPlugin::getGlobalDetector();
    }

};

#ifdef CPPUTEST_USE_MALLOC_MACROS

TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocOverrideIsUsed)
{
    int memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking);
    void* memory = malloc(10);
    LONGS_EQUAL(memLeaks+1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking));
    free (memory);
}

#ifdef CPPUTEST_USE_STRDUP_MACROS

TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrdupOverrideIsUsed)
{
    int memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking);
    char* memory = strdup("0123456789");
    LONGS_EQUAL(memLeaks+1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking));
    free (memory);
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrndupOverrideIsUsed)
{
    int memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking);
    char* memory = strndup("0123456789", 10);
    LONGS_EQUAL(memLeaks+1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking));
    free (memory);
}
#endif

#endif

TEST(MemoryLeakOverridesToBeUsedInProductionCode, UseNativeMallocByTemporarlySwitchingOffMalloc)
{
    int memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking);
#ifdef CPPUTEST_USE_MALLOC_MACROS
    #undef malloc
    #undef free
#endif
    void* memory = malloc(10);
    LONGS_EQUAL(memLeaks, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking));
    free (memory);

#ifdef CPPUTEST_USE_MALLOC_MACROS
#include "CppUTest/MemoryLeakDetectorMallocMacros.h"
#endif
}

/* TEST... allowing for a new overload in a class */
class NewDummyClass
{
public:
    static bool overloaded_new_called;

#ifdef CPPUTEST_USE_NEW_MACROS
    #undef new
#endif
    void* operator new (size_t size)
#ifdef CPPUTEST_USE_NEW_MACROS
    #include "CppUTest/MemoryLeakDetectorNewMacros.h"
#endif
    {
        overloaded_new_called = true;
        return malloc(size);
    }
    void dummyFunction()
    {
        char* memory = new char;
        delete memory;
    }
};
bool NewDummyClass::overloaded_new_called = false;

TEST(MemoryLeakOverridesToBeUsedInProductionCode, NoSideEffectsFromTurningOffNewMacros)
{
    /*
     * Interesting effect of wrapping the operator new around the macro is
     * that the actual new that is called is a different one than expected.
     *
     * The overloaded operator new doesn't actually ever get called.
     *
     * This might come as a surprise, so it is important to realize!
     */
    NewDummyClass dummy;
    dummy.dummyFunction();
    // CHECK(dummy.overloaded_new_called);
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, UseNativeNewByTemporarlySwitchingOffNew)
{
#ifdef CPPUTEST_USE_NEW_MACROS
    #undef new
    #undef delete
#endif
    char* memory = new char[10];
    delete [] memory;
#ifdef CPPUTEST_USE_NEW_MACROS
    #include "CppUTest/MemoryLeakDetectorNewMacros.h"
#endif
}

#if CPPUTEST_USE_MEM_LEAK_DETECTION

TEST(MemoryLeakOverridesToBeUsedInProductionCode, OperatorNewMacroOverloadViaIncludeFileWorks)
{
    char* leak = newAllocation();
    STRCMP_NOCASE_CONTAINS("AllocationInCppFile.cpp", memLeakDetector->report(mem_leak_period_checking));
    delete leak;
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, OperatorNewArrayMacroOverloadViaIncludeFileWorks)
{
    char* leak = newArrayAllocation();
    STRCMP_NOCASE_CONTAINS("AllocationInCppFile.cpp", memLeakDetector->report(mem_leak_period_checking));
    delete[] leak;
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocOverrideWorks)
{
    char* leak = mallocAllocation();
    STRCMP_NOCASE_CONTAINS("AllocationInCFile.c", memLeakDetector->report(mem_leak_period_checking));
    freeAllocation(leak);
}

#ifdef CPPUTEST_USE_STRDUP_MACROS
TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrdupOverrideWorks)
{
    char* leak = strdupAllocation();
    STRCMP_NOCASE_CONTAINS("AllocationInCFile.c", memLeakDetector->report(mem_leak_period_checking));
    freeAllocation(leak);
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrndupOverrideWorks)
{
    char* leak = strndupAllocation();
    STRCMP_NOCASE_CONTAINS("AllocationInCFile.c", memLeakDetector->report(mem_leak_period_checking));
    freeAllocation(leak);
}
#endif

TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocWithButFreeWithoutLeakDetectionDoesntCrash)
{
    char* leak = mallocAllocation();
    freeAllocationWithoutMacro(leak);
    LONGS_EQUAL(2, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking));
    memLeakDetector->removeMemoryLeakInformationWithoutCheckingOrDeallocatingTheMemoryButDeallocatingTheAccountInformation(getCurrentMallocAllocator(), leak, true);
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, OperatorNewOverloadingWithoutMacroWorks)
{
    char* leak = newAllocationWithoutMacro();
    STRCMP_CONTAINS("unknown", memLeakDetector->report(mem_leak_period_checking));
    delete leak;
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, OperatorNewArrayOverloadingWithoutMacroWorks)
{
    char* leak = newArrayAllocationWithoutMacro();
    STRCMP_CONTAINS("unknown", memLeakDetector->report(mem_leak_period_checking));
    delete[] leak;
}

#else

TEST(MemoryLeakOverridesToBeUsedInProductionCode, MemoryOverridesAreDisabled)
{
    char* leak = newAllocation();
    STRCMP_EQUAL("No memory leaks were detected.", memLeakDetector->report(mem_leak_period_checking));
    delete leak;
}

#endif

TEST_GROUP(OutOfMemoryTestsForOperatorNew)
{
    TestMemoryAllocator* no_memory_allocator;
    GlobalMemoryAllocatorStash memoryAllocatorStash;
    void setup()
    {
        memoryAllocatorStash.save();
        no_memory_allocator = new NullUnknownAllocator;
        setCurrentNewAllocator(no_memory_allocator);
        setCurrentNewArrayAllocator(no_memory_allocator);
    }

    void teardown()
    {
        delete no_memory_allocator;
        memoryAllocatorStash.restore();
    }
};

#if CPPUTEST_USE_MEM_LEAK_DETECTION

#if CPPUTEST_USE_STD_CPP_LIB

TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorThrowsAnExceptionWhenUsingStdCppNew)
{
    CHECK_THROWS(std::bad_alloc, new char);
}

TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorThrowsAnExceptionWhenUsingStdCppNew)
{
    CHECK_THROWS(std::bad_alloc, new char[10]);
}

TEST_GROUP(TestForExceptionsInConstructor)
{
};

TEST(TestForExceptionsInConstructor,ConstructorThrowsAnException)
{
    CHECK_THROWS(int, new ClassThatThrowsAnExceptionInTheConstructor);
}

TEST(TestForExceptionsInConstructor,ConstructorThrowsAnExceptionAllocatedAsArray)
{
    CHECK_THROWS(int, new ClassThatThrowsAnExceptionInTheConstructor[10]);
}

#else

TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNull)
{
    POINTERS_EQUAL(NULLPTR, new char);
}

TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNull)
{
    POINTERS_EQUAL(NULLPTR, new char[10]);
}

#endif

#undef new

#if CPPUTEST_USE_STD_CPP_LIB

/*
 * CLang 4.2 and memory allocation.
 *
 * Clang 4.2 has done some optimizations to their memory management that actually causes slightly different behavior than what the C++ Standard defines.
 * Usually this is not a problem... but in this case, it is a problem.
 *
 * More information about the optimization can be found at: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3433.html
 * We've done a bug-report to clang to fix some of this non-standard behavior, which is open at: http://llvm.org/bugs/show_bug.cgi?id=15541
 *
 * I very much hope that nobody would actually ever hit this bug/optimization as it is hard to figure out what is going on.
 *
 * The original test simply did "new char". Because the memory wasn't assigned to anything and is local in context, the optimization *doesn't* call
 * the operator new overload. Because it doesn't call the operator new (optimizing away a call to operator new), therefore the method wouldn't throw an exception
 * and therefore this test failed.
 *
 * The first attempt to fix this is to create a local variable and assigned the memory to that. Also this doesn't work as it still detects the allocation is
 * local and optimizes away the memory call.
 *
 * Now, we assign the memory on some static global which fools the optimizer to believe that it isn't local and it stops optimizing the operator new call.
 *
 * We (Bas Vodde and Terry Yin) suspect that in a real product, you wouldn't be able to detect the optimization and it's breaking of Standard C++. Therefore,
 * for now, we keep this hack in the test to fool the optimizer and hope nobody will ever notice this 'optimizer behavior' in a real product.
 *
 * Update 2020: The gcc compiler implemented the same optimization, but it seems to be slightly smarter and discovered that we assign to a static variable.
 * Thus it still optimized away the call to operator new. Did another bug report, but it is unlikely to get fixed. You can find it at:
 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94671
 *
 * Changed the variable to be external so it would definitively be a mistake to optimize the call.
 *
 */

extern char* some_memory;
char* some_memory;

TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorThrowsAnExceptionWhenUsingStdCppNewWithoutOverride)
{
    CHECK_THROWS(std::bad_alloc, some_memory = new char);
}

TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorThrowsAnExceptionWhenUsingStdCppNewWithoutOverride)
{
    CHECK_THROWS(std::bad_alloc, some_memory = new char[10]);
}

TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNullWithoutOverride)
{
    POINTERS_EQUAL(NULLPTR, new (std::nothrow) char);
}

TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNullWithoutOverride)
{
    POINTERS_EQUAL(NULLPTR, new (std::nothrow) char[10]);
}

#else

TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNullWithoutOverride)
{
    POINTERS_EQUAL(NULLPTR, new char);
}

TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNullWithoutOverride)
{
    POINTERS_EQUAL(NULLPTR, new char[10]);
}

#endif

#endif
<commit_msg>Same as last commit<commit_after>#include "CppUTest/TestHarness.h"
#include "CppUTest/TestMemoryAllocator.h"
#include "CppUTest/MemoryLeakDetector.h"
#include "CppUTest/TestOutput.h"
#include "CppUTest/TestRegistry.h"
#include "CppUTest/PlatformSpecificFunctions.h"
#include "CppUTest/TestTestingFixture.h"
#include "AllocationInCppFile.h"

#include "CppUTest/TestHarness_c.h"
#include "AllocationInCFile.h"

TEST_GROUP(BasicBehavior)
{
};

TEST(BasicBehavior, CanDeleteNullPointers)
{
    delete (char*) NULLPTR;
    delete [] (char*) NULLPTR;
}

#ifndef CPPUTEST_MEM_LEAK_DETECTION_DISABLED

CPPUTEST_DO_NOT_SANITIZE_ADDRESS
static void deleteArrayInvalidatesMemory()
{
    unsigned char* memory = new unsigned char[10];
    PlatformSpecificMemset(memory, 0xAB, 10);
    delete [] memory;
    CHECK(memory[5] != 0xCB);
}

TEST(BasicBehavior, deleteArrayInvalidatesMemory)
{
    deleteArrayInvalidatesMemory();
}

CPPUTEST_DO_NOT_SANITIZE_ADDRESS
static void deleteInvalidatesMemory()
{
    unsigned char* memory = new unsigned char;
    *memory = 0xAD;
    delete memory;
    CHECK(*memory != 0xAD);
}

TEST(BasicBehavior, deleteInvalidatesMemory)
{
    deleteInvalidatesMemory();
}

#if __cplusplus >= 201402L
TEST(BasicBehavior, DeleteWithSizeParameterWorks)
{
    char* charMemory = new char;
    char* charArrayMemory = new char[10];
    ::operator delete(charMemory, sizeof(char));
    ::operator delete[](charArrayMemory, sizeof(char)* 10);
}
#endif

static void deleteUnallocatedMemory()
{
    delete (char*) 0x1234678;
    FAIL("Should never come here"); // LCOV_EXCL_LINE
} // LCOV_EXCL_LINE

TEST(BasicBehavior, deleteWillNotThrowAnExceptionWhenDeletingUnallocatedMemoryButCanStillCauseTestFailures)
{
    /*
     * Test failure might cause an exception. But according to C++ standard, you aren't allowed
     * to throw exceptions in the delete function. If you do that, it will call std::terminate.
     * Therefore, the delete will need to fail without exceptions.
     */
    MemoryLeakFailure* defaultReporter = MemoryLeakWarningPlugin::getGlobalFailureReporter();
    TestTestingFixture fixture;
    fixture.setTestFunction(deleteUnallocatedMemory);
    fixture.runAllTests();
    LONGS_EQUAL(1, fixture.getFailureCount());
    POINTERS_EQUAL(defaultReporter, MemoryLeakWarningPlugin::getGlobalFailureReporter());
}

#endif

#ifdef CPPUTEST_USE_MALLOC_MACROS

/* This include is added because *sometimes* the cstdlib does an #undef. This should have been prevented */
#if CPPUTEST_USE_STD_CPP_LIB
#include <cstdlib>
#endif

TEST(BasicBehavior, bothMallocAndFreeAreOverloaded)
{
    void* memory = cpputest_malloc_location(sizeof(char), "file", 10);
    free(memory);

    memory = malloc(sizeof(unsigned char));
    cpputest_free_location(memory, "file", 10);
}

#endif

#if CPPUTEST_USE_MEM_LEAK_DETECTION

CPPUTEST_DO_NOT_SANITIZE_ADDRESS
static void freeInvalidatesMemory()
{
    unsigned char* memory = (unsigned char*) cpputest_malloc(sizeof(unsigned char));
    *memory = 0xAD;
    cpputest_free(memory);
    CHECK(*memory != 0xAD);
}

TEST(BasicBehavior, freeInvalidatesMemory)
{
    freeInvalidatesMemory();
}
#endif

TEST_GROUP(MemoryLeakOverridesToBeUsedInProductionCode)
{
    MemoryLeakDetector* memLeakDetector;
    void setup()
    {
        memLeakDetector = MemoryLeakWarningPlugin::getGlobalDetector();
    }

};

#ifdef CPPUTEST_USE_MALLOC_MACROS

TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocOverrideIsUsed)
{
    int memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking);
    void* memory = malloc(10);
    LONGS_EQUAL(memLeaks+1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking));
    free (memory);
}

#ifdef CPPUTEST_USE_STRDUP_MACROS

TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrdupOverrideIsUsed)
{
    int memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking);
    char* memory = strdup("0123456789");
    LONGS_EQUAL(memLeaks+1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking));
    free (memory);
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrndupOverrideIsUsed)
{
    int memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking);
    char* memory = strndup("0123456789", 10);
    LONGS_EQUAL(memLeaks+1, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking));
    free (memory);
}
#endif

#endif

TEST(MemoryLeakOverridesToBeUsedInProductionCode, UseNativeMallocByTemporarlySwitchingOffMalloc)
{
    int memLeaks = memLeakDetector->totalMemoryLeaks(mem_leak_period_checking);
#ifdef CPPUTEST_USE_MALLOC_MACROS
    #undef malloc
    #undef free
#endif
    void* memory = malloc(10);
    LONGS_EQUAL(memLeaks, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking));
    free (memory);

#ifdef CPPUTEST_USE_MALLOC_MACROS
#include "CppUTest/MemoryLeakDetectorMallocMacros.h"
#endif
}

/* TEST... allowing for a new overload in a class */
class NewDummyClass
{
public:
    static bool overloaded_new_called;

#ifdef CPPUTEST_USE_NEW_MACROS
    #undef new
#endif
    void* operator new (size_t size)
#ifdef CPPUTEST_USE_NEW_MACROS
    #include "CppUTest/MemoryLeakDetectorNewMacros.h"
#endif
    {
        overloaded_new_called = true;
        return malloc(size);
    }
    void dummyFunction()
    {
        char* memory = new char;
        delete memory;
    }
};
bool NewDummyClass::overloaded_new_called = false;

TEST(MemoryLeakOverridesToBeUsedInProductionCode, NoSideEffectsFromTurningOffNewMacros)
{
    /*
     * Interesting effect of wrapping the operator new around the macro is
     * that the actual new that is called is a different one than expected.
     *
     * The overloaded operator new doesn't actually ever get called.
     *
     * This might come as a surprise, so it is important to realize!
     */
    NewDummyClass dummy;
    dummy.dummyFunction();
    // CHECK(dummy.overloaded_new_called);
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, UseNativeNewByTemporarlySwitchingOffNew)
{
#ifdef CPPUTEST_USE_NEW_MACROS
    #undef new
    #undef delete
#endif
    char* memory = new char[10];
    delete [] memory;
#ifdef CPPUTEST_USE_NEW_MACROS
    #include "CppUTest/MemoryLeakDetectorNewMacros.h"
#endif
}

#if CPPUTEST_USE_MEM_LEAK_DETECTION

TEST(MemoryLeakOverridesToBeUsedInProductionCode, OperatorNewMacroOverloadViaIncludeFileWorks)
{
    char* leak = newAllocation();
    STRCMP_NOCASE_CONTAINS("AllocationInCppFile.cpp", memLeakDetector->report(mem_leak_period_checking));
    delete leak;
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, OperatorNewArrayMacroOverloadViaIncludeFileWorks)
{
    char* leak = newArrayAllocation();
    STRCMP_NOCASE_CONTAINS("AllocationInCppFile.cpp", memLeakDetector->report(mem_leak_period_checking));
    delete[] leak;
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocOverrideWorks)
{
    char* leak = mallocAllocation();
    STRCMP_NOCASE_CONTAINS("AllocationInCFile.c", memLeakDetector->report(mem_leak_period_checking));
    freeAllocation(leak);
}

#ifdef CPPUTEST_USE_STRDUP_MACROS
TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrdupOverrideWorks)
{
    char* leak = strdupAllocation();
    STRCMP_NOCASE_CONTAINS("AllocationInCFile.c", memLeakDetector->report(mem_leak_period_checking));
    freeAllocation(leak);
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, StrndupOverrideWorks)
{
    char* leak = strndupAllocation();
    STRCMP_NOCASE_CONTAINS("AllocationInCFile.c", memLeakDetector->report(mem_leak_period_checking));
    freeAllocation(leak);
}
#endif

TEST(MemoryLeakOverridesToBeUsedInProductionCode, MallocWithButFreeWithoutLeakDetectionDoesntCrash)
{
    char* leak = mallocAllocation();
    freeAllocationWithoutMacro(leak);
    LONGS_EQUAL(2, memLeakDetector->totalMemoryLeaks(mem_leak_period_checking));
    memLeakDetector->removeMemoryLeakInformationWithoutCheckingOrDeallocatingTheMemoryButDeallocatingTheAccountInformation(getCurrentMallocAllocator(), leak, true);
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, OperatorNewOverloadingWithoutMacroWorks)
{
    char* leak = newAllocationWithoutMacro();
    STRCMP_CONTAINS("unknown", memLeakDetector->report(mem_leak_period_checking));
    delete leak;
}

TEST(MemoryLeakOverridesToBeUsedInProductionCode, OperatorNewArrayOverloadingWithoutMacroWorks)
{
    char* leak = newArrayAllocationWithoutMacro();
    STRCMP_CONTAINS("unknown", memLeakDetector->report(mem_leak_period_checking));
    delete[] leak;
}

#else

TEST(MemoryLeakOverridesToBeUsedInProductionCode, MemoryOverridesAreDisabled)
{
    char* leak = newAllocation();
    STRCMP_EQUAL("No memory leaks were detected.", memLeakDetector->report(mem_leak_period_checking));
    delete leak;
}

#endif

TEST_GROUP(OutOfMemoryTestsForOperatorNew)
{
    TestMemoryAllocator* no_memory_allocator;
    GlobalMemoryAllocatorStash memoryAllocatorStash;
    void setup()
    {
        memoryAllocatorStash.save();
        no_memory_allocator = new NullUnknownAllocator;
        setCurrentNewAllocator(no_memory_allocator);
        setCurrentNewArrayAllocator(no_memory_allocator);
    }

    void teardown()
    {
        memoryAllocatorStash.restore();
        delete no_memory_allocator;
    }
};

#if CPPUTEST_USE_MEM_LEAK_DETECTION

#if CPPUTEST_USE_STD_CPP_LIB

TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorThrowsAnExceptionWhenUsingStdCppNew)
{
    CHECK_THROWS(std::bad_alloc, new char);
}

TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorThrowsAnExceptionWhenUsingStdCppNew)
{
    CHECK_THROWS(std::bad_alloc, new char[10]);
}

TEST_GROUP(TestForExceptionsInConstructor)
{
};

TEST(TestForExceptionsInConstructor,ConstructorThrowsAnException)
{
    CHECK_THROWS(int, new ClassThatThrowsAnExceptionInTheConstructor);
}

TEST(TestForExceptionsInConstructor,ConstructorThrowsAnExceptionAllocatedAsArray)
{
    CHECK_THROWS(int, new ClassThatThrowsAnExceptionInTheConstructor[10]);
}

#else

TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNull)
{
    POINTERS_EQUAL(NULLPTR, new char);
}

TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNull)
{
    POINTERS_EQUAL(NULLPTR, new char[10]);
}

#endif

#undef new

#if CPPUTEST_USE_STD_CPP_LIB

/*
 * CLang 4.2 and memory allocation.
 *
 * Clang 4.2 has done some optimizations to their memory management that actually causes slightly different behavior than what the C++ Standard defines.
 * Usually this is not a problem... but in this case, it is a problem.
 *
 * More information about the optimization can be found at: http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3433.html
 * We've done a bug-report to clang to fix some of this non-standard behavior, which is open at: http://llvm.org/bugs/show_bug.cgi?id=15541
 *
 * I very much hope that nobody would actually ever hit this bug/optimization as it is hard to figure out what is going on.
 *
 * The original test simply did "new char". Because the memory wasn't assigned to anything and is local in context, the optimization *doesn't* call
 * the operator new overload. Because it doesn't call the operator new (optimizing away a call to operator new), therefore the method wouldn't throw an exception
 * and therefore this test failed.
 *
 * The first attempt to fix this is to create a local variable and assigned the memory to that. Also this doesn't work as it still detects the allocation is
 * local and optimizes away the memory call.
 *
 * Now, we assign the memory on some static global which fools the optimizer to believe that it isn't local and it stops optimizing the operator new call.
 *
 * We (Bas Vodde and Terry Yin) suspect that in a real product, you wouldn't be able to detect the optimization and it's breaking of Standard C++. Therefore,
 * for now, we keep this hack in the test to fool the optimizer and hope nobody will ever notice this 'optimizer behavior' in a real product.
 *
 * Update 2020: The gcc compiler implemented the same optimization, but it seems to be slightly smarter and discovered that we assign to a static variable.
 * Thus it still optimized away the call to operator new. Did another bug report, but it is unlikely to get fixed. You can find it at:
 * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=94671
 *
 * Changed the variable to be external so it would definitively be a mistake to optimize the call.
 *
 */

extern char* some_memory;
char* some_memory;

TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorThrowsAnExceptionWhenUsingStdCppNewWithoutOverride)
{
    CHECK_THROWS(std::bad_alloc, some_memory = new char);
}

TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorThrowsAnExceptionWhenUsingStdCppNewWithoutOverride)
{
    CHECK_THROWS(std::bad_alloc, some_memory = new char[10]);
}

TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNullWithoutOverride)
{
    POINTERS_EQUAL(NULLPTR, new (std::nothrow) char);
}

TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNullWithoutOverride)
{
    POINTERS_EQUAL(NULLPTR, new (std::nothrow) char[10]);
}

#else

TEST(OutOfMemoryTestsForOperatorNew, FailingNewOperatorReturnsNullWithoutOverride)
{
    POINTERS_EQUAL(NULLPTR, new char);
}

TEST(OutOfMemoryTestsForOperatorNew, FailingNewArrayOperatorReturnsNullWithoutOverride)
{
    POINTERS_EQUAL(NULLPTR, new char[10]);
}

#endif

#endif
<|endoftext|>


<commit_before><commit_msg>Base::FileInfo: fix left overs in transient directory<commit_after><|endoftext|>


<commit_before>/*
Copyright (c) 2021 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.
*/
// Test hipEventRecord serialization behavior.
// Through manual inspection of the reported timestamps, can determine if recording a NULL event
// forces synchronization : set
#include <hip_test_checkers.hh>
#include <kernels.hh>
#include <hip_test_context.hh>
#include <hip_test_common.hh>

TEST_CASE("Unit_hipEventRecord") {
    size_t N = 4 * 1024 * 1024;
    unsigned threadsPerBlock = 256;
    int iterations = 1;

    unsigned blocks = (N + threadsPerBlock - 1) / threadsPerBlock;
    if (blocks > 1024) blocks = 1024;
    if (blocks == 0) blocks = 1;

    printf("N=%zu (A+B+C= %6.1f MB total) blocks=%u threadsPerBlock=%u iterations=%d\n", N,
           ((double)3 * N * sizeof(float)) / 1024 / 1024, blocks, threadsPerBlock, iterations);
    printf("iterations=%d\n", iterations);

    size_t Nbytes = N * sizeof(float);

    float *A_h, *B_h, *C_h;
    float *A_d, *B_d, *C_d;
    HipTest::initArrays(&A_d, &B_d, &C_d, &A_h, &B_h, &C_h, N);

    hipEvent_t start, stop;

    // NULL stream check:
    HIP_CHECK(hipEventCreate(&start));
    HIP_CHECK(hipEventCreate(&stop));

    HIP_CHECK(hipMemcpy(A_d, A_h, Nbytes, hipMemcpyHostToDevice));
    HIP_CHECK(hipMemcpy(B_d, B_h, Nbytes, hipMemcpyHostToDevice));

    for (int i = 0; i < iterations; i++) {
        //--- START TIMED REGION
        long long hostStart = HipTest::get_time();
        // Record the start event
        HIP_CHECK(hipEventRecord(start, NULL));

        HipTest::launchKernel<float>(HipTest::vectorADD<float>, blocks, threadsPerBlock, 0, 0,
static_cast<const float*>(A_d), static_cast<const float*>(B_d), C_d, N);

        HIP_CHECK(hipEventRecord(stop, NULL));
        HIP_CHECK(hipEventSynchronize(stop));
        long long hostStop = HipTest::get_time();
        //--- STOP TIMED REGION

        float eventMs = 1.0f;
        HIP_CHECK(hipEventElapsedTime(&eventMs, start, stop));
        float hostMs = HipTest::elapsed_time(hostStart, hostStop);

        printf("host_time (chrono)                =%6.3fms\n", hostMs);
        printf("kernel_time (hipEventElapsedTime) =%6.3fms\n", eventMs);
        printf("\n");

        // Make sure timer is timing something...
        REQUIRE(eventMs > 0.0f);
    }

    HIP_CHECK(hipMemcpy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost));

    HIP_CHECK(hipEventDestroy(start));
    HIP_CHECK(hipEventDestroy(stop));

    HipTest::checkVectorADD(A_h, B_h, C_h, N, true);
}
<commit_msg>EXSWCPHIPT-102 - Adding hipEventRecord Tests (#2722)<commit_after>/*
Copyright (c) 2021 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.
*/

// Test hipEventRecord serialization behavior.

#include <hip_test_common.hh>

#include <kernels.hh>
#include <hip_test_checkers.hh>
#include <hip_test_context.hh>

TEST_CASE("Unit_hipEventRecord") {
  constexpr size_t N = 1024;
  constexpr int iterations = 1;

  constexpr int blocks = 1024;

  constexpr size_t Nbytes = N * sizeof(float);

  float *A_h, *B_h, *C_h;
  float *A_d, *B_d, *C_d;
  HipTest::initArrays(&A_d, &B_d, &C_d, &A_h, &B_h, &C_h, N);

  enum TestType {
    WithFlags_Default = hipEventDefault,
    WithFlags_Blocking = hipEventBlockingSync,
    WithFlags_DisableTiming = hipEventDisableTiming,
#if HT_AMD
    WithFlags_ReleaseToDevice = hipEventReleaseToDevice,
    WithFlags_ReleaseToSystem = hipEventReleaseToSystem,
#endif
    WithoutFlags
  };

#if HT_AMD
  auto flags = GENERATE(WithFlags_Default, WithFlags_Blocking, WithFlags_DisableTiming,
                        WithFlags_ReleaseToDevice, WithFlags_ReleaseToSystem, WithoutFlags);
#endif

#if HT_NVIDIA
  auto flags =
      GENERATE(WithFlags_Default, WithFlags_Blocking, WithFlags_DisableTiming, WithoutFlags);
#endif

  hipEvent_t start{}, stop{};

  if (flags == WithoutFlags) {
    HIP_CHECK(hipEventCreate(&start));
    HIP_CHECK(hipEventCreate(&stop));
  } else {
    HIP_CHECK(hipEventCreateWithFlags(&start, flags));
    HIP_CHECK(hipEventCreateWithFlags(&stop, flags));
  }

  HIP_CHECK(hipMemcpy(A_d, A_h, Nbytes, hipMemcpyHostToDevice));
  HIP_CHECK(hipMemcpy(B_d, B_h, Nbytes, hipMemcpyHostToDevice));

  for (int i = 0; i < iterations; i++) {
    //--- START TIMED REGION
    long long hostStart = HipTest::get_time();
    // Record the start event
    HIP_CHECK(hipEventRecord(start, NULL));

    HipTest::launchKernel<float>(HipTest::vectorADD<float>, blocks, 1, 0, 0,
                                 static_cast<const float*>(A_d), static_cast<const float*>(B_d),
                                 C_d, N);

    HIP_CHECK(hipEventRecord(stop, NULL));
    HIP_CHECK(hipEventSynchronize(stop));
    long long hostStop = HipTest::get_time();
    //--- STOP TIMED REGION

    float hostMs = HipTest::elapsed_time(hostStart, hostStop);

    INFO("host_time (chrono)                = " << hostMs);

    // Make sure timer is timing something...
    if (flags != WithFlags_DisableTiming) {
      float eventMs = 1.0f;
      HIP_CHECK(hipEventElapsedTime(&eventMs, start, stop));
      INFO("kernel_time (hipEventElapsedTime) = " << eventMs);
      REQUIRE(eventMs > 0.0f);
    }
  }

  HIP_CHECK(hipMemcpy(C_h, C_d, Nbytes, hipMemcpyDeviceToHost));

  HIP_CHECK(hipEventDestroy(start));
  HIP_CHECK(hipEventDestroy(stop));

  HipTest::checkVectorADD(A_h, B_h, C_h, N, true);
  HipTest::freeArrays(A_d, B_d, C_d, A_h, B_h, C_h, false);
  TestContext::get().cleanContext();
}

TEST_CASE("Unit_hipEventRecord_Negative") {
  SECTION("Nullptr event") {
    HIP_CHECK_ERROR(hipEventRecord(nullptr, nullptr), hipErrorInvalidResourceHandle);
  }
}<|endoftext|>