<commit_before>/*=========================================================================

  Program:   Visualization Toolkit

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"

#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkMolecule.h"
#include "vtkLight.h"
#include "vtkOpenGLMoleculeMapper.h"
#include "vtkOpenGLSphereMapper.h"
#include "vtkNew.h"
#include "vtkProperty.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkPDBReader.h"
#include "vtkPlaneSource.h"
#include "vtkPolyDataMapper.h"

#include "vtkDepthOfFieldPass.h"
#include "vtkRenderStepsPass.h"
#include "vtkSequencePass.h"
#include "vtkShadowMapBakerPass.h"
#include "vtkShadowMapPass.h"
#include "vtkOpenGLRenderer.h"
#include "vtkCameraPass.h"
#include "vtkRenderPassCollection.h"
#include "vtkSSAAPass.h"

#include "vtkLookupTable.h"
#include "vtkPeriodicTable.h"

#include "vtkTimerLog.h"
#include "vtkCamera.h"

int TestPDBBallAndStickShadows(int argc, char *argv[])
{
  char* fileName =
    vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/2LYZ.pdb");

  // read protein from pdb
  vtkNew<vtkPDBReader> reader;
  reader->SetFileName(fileName);
  reader->Update();

  delete [] fileName;

  vtkNew<vtkOpenGLMoleculeMapper> molmapper;
  molmapper->SetInputConnection(reader->GetOutputPort(1));
  molmapper->SetRenderBonds(false);
  molmapper->SetAtomicRadiusType( vtkMoleculeMapper::VDWRadius );
  molmapper->SetAtomicRadiusScaleFactor( 0.9 );
  molmapper->SetScalarMaterialModeToAmbientAndDiffuse();

  // get the default lookup table and desaturate it to be
  // more pleasing
  vtkNew<vtkPeriodicTable> pt;
  vtkNew<vtkLookupTable> lut;
  pt->GetDefaultLUT(lut.Get());
  const unsigned short numColors = lut->GetNumberOfColors();
  double rgb[4];
  for (vtkIdType i = 0; static_cast<unsigned int>(i) < numColors; ++i)
    {
    lut->GetTableValue(i, rgb);
    lut->SetTableValue(i, 0.45 + rgb[0]*0.55,
      0.45 + rgb[1]*0.55, 0.45 + rgb[2]*0.55);
    }
  molmapper->GetFastAtomMapper()->SetLookupTable(lut.Get());

  vtkNew<vtkActor> actor;
  actor->SetMapper(molmapper.GetPointer());
  actor->GetProperty()->SetDiffuse(0.7);

  // we override the default shader very slightly so that
  // the ambient color component is scaled off the diffuse
  molmapper->GetFastAtomMapper()->AddShaderReplacement(
    vtkShader::Fragment,  // in the fragment shader
    "//VTK::Color::Impl",
    true, // before the standard replacements
    "//VTK::Color::Impl\n" // we still want the default
    "  ambientColor = diffuseColor*0.2;\n", //but we add this
    false // only do it once
    );

  vtkNew<vtkRenderer> ren;
  vtkNew<vtkRenderWindow> win;
  win->AddRenderer(ren.GetPointer());
  vtkNew<vtkRenderWindowInteractor> iren;
  iren->SetRenderWindow(win.GetPointer());

  ren->AddActor(actor.GetPointer());
  ren->ResetCamera();
  ren->GetActiveCamera()->Zoom(1.7);
  ren->GetActiveCamera()->SetFocalDisk(ren->GetActiveCamera()->GetDistance()*0.05);
  ren->SetBackground2(0.2, 0.2, 0.3);
  ren->SetBackground(0.1, 0.1, 0.15);
  ren->GradientBackgroundOn();
  win->SetSize(600, 600);

  // add a plane
  vtkNew<vtkPlaneSource> plane;
  double *bounds = molmapper->GetBounds();
  plane->SetOrigin(bounds[0], bounds[2], bounds[4]);
  plane->SetPoint1(bounds[1], bounds[2], bounds[4]);
  plane->SetPoint2(bounds[0], bounds[2], bounds[5]);
  vtkNew<vtkPolyDataMapper> planeMapper;
  planeMapper->SetInputConnection(plane->GetOutputPort());
  vtkNew<vtkActor> planeActor;
  planeActor->SetMapper(planeMapper.Get());
  ren->AddActor(planeActor.Get());

  vtkNew<vtkLight> light1;
  light1->SetFocalPoint(0,0,0);
  light1->SetPosition(0, 0.9, 0.3);
  light1->SetIntensity(0.5);
  light1->SetShadowAttenuation(0.6);
  ren->AddLight(light1.Get());

  vtkNew<vtkLight> light2;
  light2->SetFocalPoint(0,0,0);
  light2->SetPosition(0.0,0.9,-0.3);
  light2->SetIntensity(0.5);
  light2->SetShadowAttenuation(0.6);
  ren->AddLight(light2.Get());

  vtkNew<vtkShadowMapPass> shadows;

  vtkNew<vtkSequencePass> seq;
  vtkNew<vtkRenderPassCollection> passes;
  passes->AddItem(shadows->GetShadowMapBakerPass());
  passes->AddItem(shadows.Get());
  seq->SetPasses(passes.Get());

  vtkNew<vtkCameraPass> cameraP;
  cameraP->SetDelegatePass(seq.Get());

  // create the basic VTK render steps
  vtkNew<vtkRenderStepsPass> basicPasses;

  vtkOpenGLRenderer *glrenderer =
      vtkOpenGLRenderer::SafeDownCast(ren.GetPointer());

  // finally add the DOF passs
  vtkNew<vtkDepthOfFieldPass> dofp;
  dofp->AutomaticFocalDistanceOff();
  dofp->SetDelegatePass(cameraP.Get());

  // finally blur the resulting image
  // The blur delegates rendering the unblured image
  // to the basicPasses
  vtkNew<vtkSSAAPass> ssaa;
  ssaa->SetDelegatePass(dofp.Get());
  //ssaa->SetDelegatePass(cameraP.Get());

  // tell the renderer to use our render pass pipeline
//  glrenderer->SetPass(ssaa.Get());
  glrenderer->SetPass(dofp.Get());
//  glrenderer->SetPass(cameraP.Get());

  // tell the renderer to use our render pass pipeline
  vtkNew<vtkTimerLog> timer;
  timer->StartTimer();
  win->Render();
  timer->StopTimer();
  double firstRender = timer->GetElapsedTime();
  cerr << "first render time: " << firstRender << endl;

  int numRenders = 5;
  timer->StartTimer();
  for (int i = 0; i < numRenders; ++i)
    {
    ren->GetActiveCamera()->Azimuth(85.0/numRenders);
    ren->GetActiveCamera()->Elevation(85.0/numRenders);
    win->Render();
    }
  timer->StopTimer();
  double elapsed = timer->GetElapsedTime();
  cerr << "interactive render time: " << elapsed / numRenders << endl;

  ren->GetActiveCamera()->SetPosition(0,0,1);
  ren->GetActiveCamera()->SetFocalPoint(0,0,0);
  ren->GetActiveCamera()->SetViewUp(0,1,0);
  ren->ResetCamera();
  ren->GetActiveCamera()->Zoom(1.7);

  win->Render();

  // Finally render the scene and compare the image to a reference image
  win->SetMultiSamples(0);
  win->GetInteractor()->Initialize();
  win->GetInteractor()->Start();

  return EXIT_SUCCESS;
}
<commit_msg>Fix accidental commit of one test<commit_after>/*=========================================================================

  Program:   Visualization Toolkit

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkTestUtilities.h"
#include "vtkRegressionTestImage.h"

#include "vtkActor.h"
#include "vtkCamera.h"
#include "vtkMolecule.h"
#include "vtkLight.h"
#include "vtkMoleculeMapper.h"
#include "vtkNew.h"
#include "vtkProperty.h"
#include "vtkRenderWindowInteractor.h"
#include "vtkRenderWindow.h"
#include "vtkRenderer.h"
#include "vtkPDBReader.h"
#include "vtkPlaneSource.h"
#include "vtkPolyDataMapper.h"

#include "vtkTimerLog.h"
#include "vtkCamera.h"

int TestPDBBallAndStickShadows(int argc, char *argv[])
{
  char* fileName =
    vtkTestUtilities::ExpandDataFileName(argc, argv, "Data/2LYZ.pdb");

  // read protein from pdb
  vtkNew<vtkPDBReader> reader;
  reader->SetFileName(fileName);
  reader->Update();

  delete [] fileName;

  vtkNew<vtkMoleculeMapper> molmapper;
  molmapper->SetInputConnection(reader->GetOutputPort(1));

  cerr << "Class: " << molmapper->GetClassName() << endl;
  cerr << "Atoms: " << molmapper->GetInput()->GetNumberOfAtoms() << endl;
  cerr << "Bonds: " << molmapper->GetInput()->GetNumberOfBonds() << endl;

  molmapper->UseBallAndStickSettings();

  vtkNew<vtkActor> actor;
  actor->SetMapper(molmapper.GetPointer());
  actor->GetProperty()->SetAmbient(0.2);
  actor->GetProperty()->SetDiffuse(0.7);
  actor->GetProperty()->SetSpecular(0.3);
  actor->GetProperty()->SetSpecularPower(40);

  vtkNew<vtkRenderer> ren;
  vtkNew<vtkRenderWindow> win;
  win->AddRenderer(ren.GetPointer());
  vtkNew<vtkRenderWindowInteractor> iren;
  iren->SetRenderWindow(win.GetPointer());

  ren->AddActor(actor.GetPointer());
  ren->ResetCamera();
  ren->GetActiveCamera()->Zoom(1.7);
  ren->SetBackground(0.4, 0.5, 0.6);
  win->SetSize(450, 450);

  // add a plane
  vtkNew<vtkPlaneSource> plane;
  double *bounds = molmapper->GetBounds();
  plane->SetOrigin(bounds[0], bounds[2], bounds[4]);
  plane->SetPoint1(bounds[1], bounds[2], bounds[4]);
  plane->SetPoint2(bounds[0], bounds[2], bounds[5]);
  vtkNew<vtkPolyDataMapper> planeMapper;
  planeMapper->SetInputConnection(plane->GetOutputPort());
  vtkNew<vtkActor> planeActor;
  planeActor->SetMapper(planeMapper.Get());
  ren->AddActor(planeActor.Get());

  vtkNew<vtkLight> light1;
  light1->SetFocalPoint(0,0,0);
  light1->SetPosition(0,1,0.2);
  light1->SetColor(0.95,0.97,1.0);
  light1->SetIntensity(0.8);
  ren->AddLight(light1.Get());

  vtkNew<vtkLight> light2;
  light2->SetFocalPoint(0,0,0);
  light2->SetPosition(1.0,1.0,1.0);
  light2->SetColor(1.0,0.8,0.7);
  light2->SetIntensity(0.3);
  ren->AddLight(light2.Get());

  ren->UseShadowsOn();

  vtkNew<vtkTimerLog> timer;
  timer->StartTimer();
  win->Render();
  timer->StopTimer();
  double firstRender = timer->GetElapsedTime();
  cerr << "first render time: " << firstRender << endl;

/*
  int numRenders = 500;
  timer->StartTimer();
  for (int i = 0; i < numRenders; ++i)
    {
    ren->GetActiveCamera()->Azimuth(85.0/numRenders);
    ren->GetActiveCamera()->Elevation(85.0/numRenders);
    win->Render();
    }
  timer->StopTimer();
  double elapsed = timer->GetElapsedTime();
  cerr << "interactive render time: " << elapsed / numRenders << endl;
*/

  ren->GetActiveCamera()->SetPosition(0,0,1);
  ren->GetActiveCamera()->SetFocalPoint(0,0,0);
  ren->GetActiveCamera()->SetViewUp(0,1,0);
  ren->ResetCamera();
  ren->GetActiveCamera()->Zoom(1.7);

  win->Render();

  // Finally render the scene and compare the image to a reference image
  win->SetMultiSamples(0);
  win->GetInteractor()->Initialize();
  win->GetInteractor()->Start();

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
 * File:  gmm.cpp
 * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include <string>

#include "common/sedna.h"

#include "common/gmm.h"
#include "common/base.h"
#include "common/xptr.h"
#include "common/u/uutils.h"

static void *global_memory;
UMMap global_memory_mapping;

void create_global_memory_mapping(int os_primitives_id_min_bound)
{
    char buf[1024];
    vmm_region_values v;

    global_memory_mapping = uCreateFileMapping(U_INVALID_FD, PAGE_SIZE, SEDNA_GLOBAL_MEMORY_MAPPING, NULL, __sys_call_error);
    if (U_INVALID_FILEMAPPING(global_memory_mapping))
        throw USER_EXCEPTION2(SE4074, "See file FAQ shipped with the distribution");

    global_memory = uMapViewOfFile(global_memory_mapping, NULL, PAGE_SIZE, 0, __sys_call_error);
    if (global_memory == NULL)
        throw USER_EXCEPTION(SE4078);

    memset(global_memory, '\0', PAGE_SIZE);
    *(t_layer*)global_memory = INVALID_LAYER;

    //!!! overflow may happen
    strcpy(buf, SEDNA_DATA);
#ifdef _WIN32
    strcat(buf, "\\data");
#else
    strcat(buf, "/data");
#endif
    if (!uIsFileExist(buf, __sys_call_error))
    {
        if (uMkDir(buf, NULL, __sys_call_error) == 0)
            throw USER_EXCEPTION2(SE4300, buf);
    }

    //!!! overflow may happen
#ifdef _WIN32
    strcat(buf, "\\vmm.dat");
#else
    strcat(buf, "/vmm.dat");
#endif

    if (uIsFileExist(buf, __sys_call_error))
    {
        UFile fd = uOpenFile(buf, U_SHARE_READ, U_READ, 0, __sys_call_error);
        if (fd == U_INVALID_FD)
            throw USER_EXCEPTION2(SE4042, "vmm.dat");

        int bytes_read = 0;
        int res = uReadFile(fd, &v, sizeof(vmm_region_values), &bytes_read, __sys_call_error);
        if (res == 0 || bytes_read != sizeof(vmm_region_values))
            throw USER_EXCEPTION2(SE4044, "vmm.dat");

        if (uCloseFile(fd, __sys_call_error) == 0)
            throw USER_EXCEPTION2(SE4043, "vmm.dat");

        LAYER_ADDRESS_SPACE_START_ADDR_INT = v.LAYER_ADDRESS_SPACE_START_ADDR_INT;
        LAYER_ADDRESS_SPACE_BOUNDARY_INT = v.LAYER_ADDRESS_SPACE_BOUNDARY_INT;
        PH_ADDRESS_SPACE_START_ADDR_INT = v.PH_ADDRESS_SPACE_START_ADDR_INT;
        LAYER_ADDRESS_SPACE_SIZE = v.LAYER_ADDRESS_SPACE_SIZE;

//d_printf2("load LAYER_ADDRESS_SPACE_SIZE = %d\n", LAYER_ADDRESS_SPACE_SIZE);

        LAYER_ADDRESS_SPACE_START_ADDR = (void*)LAYER_ADDRESS_SPACE_START_ADDR_INT;
        LAYER_ADDRESS_SPACE_BOUNDARY = (void*)LAYER_ADDRESS_SPACE_BOUNDARY_INT;
        PH_ADDRESS_SPACE_START_ADDR = (void*)PH_ADDRESS_SPACE_START_ADDR_INT;

        *(vmm_region_values*)((char*)global_memory + PAGE_SIZE - sizeof(vmm_region_values)) = v;
    }
    else
    {
        char buf2[128];
        uSetEnvironmentVariable(SEDNA_DETERMINE_VMM_REGION, "1", __sys_call_error);
        uSetEnvironmentVariable(SEDNA_OS_PRIMITIVES_ID_MIN_BOUND, u_itoa(os_primitives_id_min_bound, buf2, 10), __sys_call_error);

        char path_buf[U_MAX_PATH + 10];
        std::string path_str = uGetImageProcPath(path_buf, __sys_call_error) + std::string("/") + SESSION_EXE;
        strcpy(path_buf, path_str.c_str());

        UPID pid;
        UPHANDLE process_handle;
        if (uCreateProcess(path_buf,
                           false, // inherit handles
                           NULL,
                           U_DETACHED_PROCESS,
                           &process_handle,
                           NULL,
                           &pid,
                           NULL,
                           NULL,
                           __sys_call_error) != 0)
            throw SYSTEM_ENV_EXCEPTION("Can't create process");

        int status;
        uWaitForChildProcess(pid, process_handle, &status, __sys_call_error);
        if (status) SYSTEM_ENV_EXCEPTION("Can't determine VMM region");
        uCloseProcess(process_handle, __sys_call_error);

        uSetEnvironmentVariable(SEDNA_DETERMINE_VMM_REGION, "0", __sys_call_error);

        v = *(vmm_region_values*)((char*)global_memory + PAGE_SIZE - sizeof(vmm_region_values));

        LAYER_ADDRESS_SPACE_START_ADDR_INT = v.LAYER_ADDRESS_SPACE_START_ADDR_INT;
        LAYER_ADDRESS_SPACE_BOUNDARY_INT = v.LAYER_ADDRESS_SPACE_BOUNDARY_INT;
        PH_ADDRESS_SPACE_START_ADDR_INT = v.PH_ADDRESS_SPACE_START_ADDR_INT;
        LAYER_ADDRESS_SPACE_SIZE = v.LAYER_ADDRESS_SPACE_SIZE;

//fprintf(res_os, "create LAYER_ADDRESS_SPACE_START_ADDR_INT = 0x%x\n", v.LAYER_ADDRESS_SPACE_START_ADDR_INT);
//fprintf(res_os, "create LAYER_ADDRESS_SPACE_BOUNDARY_INT = 0x%x\n", v.LAYER_ADDRESS_SPACE_BOUNDARY_INT);
//fprintf(res_os"create PH_ADDRESS_SPACE_START_ADDR_INT = 0x%x\n", v.PH_ADDRESS_SPACE_START_ADDR_INT);
//fprintf(res_os, "create LAYER_ADDRESS_SPACE_SIZE = 0x%x\n", v.LAYER_ADDRESS_SPACE_SIZE);

        if (LAYER_ADDRESS_SPACE_SIZE < VMM_REGION_MIN_SIZE) throw USER_EXCEPTION(SE1031);

        LAYER_ADDRESS_SPACE_START_ADDR = (void*)LAYER_ADDRESS_SPACE_START_ADDR_INT;
        LAYER_ADDRESS_SPACE_BOUNDARY = (void*)LAYER_ADDRESS_SPACE_BOUNDARY_INT;
        PH_ADDRESS_SPACE_START_ADDR = (void*)PH_ADDRESS_SPACE_START_ADDR_INT;

        UFile fd = uCreateFile(buf, 0, U_WRITE, 0, NULL, __sys_call_error);
        if (fd == U_INVALID_FD)
            throw USER_EXCEPTION2(SE4040, "vmm.dat");

        int bytes_written = 0;
        int res = uWriteFile(fd, &v, sizeof(vmm_region_values), &bytes_written, __sys_call_error);
        if (res == 0 || bytes_written != sizeof(vmm_region_values))
            throw USER_EXCEPTION2(SE4045, "vmm.dat");

        if (uCloseFile(fd, __sys_call_error) == 0)
            throw USER_EXCEPTION2(SE4043, "vmm.dat");
    }

    elog(EL_INFO,  ("Layer address space start addr = 0x%x", LAYER_ADDRESS_SPACE_START_ADDR));
    elog(EL_INFO,  ("Layer address space boundary   = 0x%x", LAYER_ADDRESS_SPACE_BOUNDARY));
    elog(EL_INFO,  ("Persistent heap start addr     = 0x%x", PH_ADDRESS_SPACE_START_ADDR));
}

void release_global_memory_mapping()
{
    if (uUnmapViewOfFile(global_memory_mapping, global_memory, PAGE_SIZE, __sys_call_error) == -1)
        throw USER_EXCEPTION(SE4079);

    if (uReleaseFileMapping(global_memory_mapping, SEDNA_GLOBAL_MEMORY_MAPPING, __sys_call_error) == -1)
        throw USER_EXCEPTION(SE4076);
}

void open_global_memory_mapping(int err_code)
{
    global_memory_mapping = uOpenFileMapping(U_INVALID_FD, PAGE_SIZE, SEDNA_GLOBAL_MEMORY_MAPPING, __sys_call_error);
    if (U_INVALID_FILEMAPPING(global_memory_mapping))
        throw USER_EXCEPTION(err_code);
}

void close_global_memory_mapping()
{
    if (uCloseFileMapping(global_memory_mapping, __sys_call_error) == -1)
        throw USER_EXCEPTION(SE4077);
}

UMMap get_global_memory_mapping()
{
    return global_memory_mapping;
}

void get_vmm_region_values()
{
    global_memory = uMapViewOfFile(global_memory_mapping, NULL, PAGE_SIZE, 0, __sys_call_error);
    if (global_memory == NULL)
        throw USER_EXCEPTION(SE4078);

    vmm_region_values *v;
    v = (vmm_region_values*)((char*)global_memory + PAGE_SIZE - sizeof(vmm_region_values));

    LAYER_ADDRESS_SPACE_START_ADDR_INT = v->LAYER_ADDRESS_SPACE_START_ADDR_INT;
    LAYER_ADDRESS_SPACE_BOUNDARY_INT = v->LAYER_ADDRESS_SPACE_BOUNDARY_INT;
    PH_ADDRESS_SPACE_START_ADDR_INT = v->PH_ADDRESS_SPACE_START_ADDR_INT;
    LAYER_ADDRESS_SPACE_SIZE = v->LAYER_ADDRESS_SPACE_SIZE;

    LAYER_ADDRESS_SPACE_START_ADDR = (void*)LAYER_ADDRESS_SPACE_START_ADDR_INT;
    LAYER_ADDRESS_SPACE_BOUNDARY = (void*)LAYER_ADDRESS_SPACE_BOUNDARY_INT;
    PH_ADDRESS_SPACE_START_ADDR = (void*)PH_ADDRESS_SPACE_START_ADDR_INT;

    if (uUnmapViewOfFile(global_memory_mapping, global_memory, PAGE_SIZE, __sys_call_error) == -1)
        throw USER_EXCEPTION(SE4079);
}

void set_vmm_region_values()
{
    global_memory = uMapViewOfFile(global_memory_mapping, NULL, PAGE_SIZE, 0, __sys_call_error);
    if (global_memory == NULL)
        throw USER_EXCEPTION(SE4078);

    vmm_region_values *v;
    v = (vmm_region_values*)((char*)global_memory + PAGE_SIZE - sizeof(vmm_region_values));

    v->LAYER_ADDRESS_SPACE_START_ADDR_INT = LAYER_ADDRESS_SPACE_START_ADDR_INT;
    v->LAYER_ADDRESS_SPACE_BOUNDARY_INT = LAYER_ADDRESS_SPACE_BOUNDARY_INT;
    v->PH_ADDRESS_SPACE_START_ADDR_INT = PH_ADDRESS_SPACE_START_ADDR_INT;
    v->LAYER_ADDRESS_SPACE_SIZE = LAYER_ADDRESS_SPACE_SIZE;

    if (uUnmapViewOfFile(global_memory_mapping, global_memory, PAGE_SIZE, __sys_call_error) == -1)
        throw USER_EXCEPTION(SE4079);
}

<commit_msg>verbosity added into some gov exceptions<commit_after>/*
 * File:  gmm.cpp
 * Copyright (C) 2004 The Institute for System Programming of the Russian Academy of Sciences (ISP RAS)
 */

#include <string>

#include "common/sedna.h"

#include "common/gmm.h"
#include "common/base.h"
#include "common/xptr.h"
#include "common/u/uutils.h"

static void *global_memory;
UMMap global_memory_mapping;

void create_global_memory_mapping(int os_primitives_id_min_bound)
{
    char buf[1024];
    vmm_region_values v;

    global_memory_mapping = uCreateFileMapping(U_INVALID_FD, PAGE_SIZE, SEDNA_GLOBAL_MEMORY_MAPPING, NULL, __sys_call_error);
    if (U_INVALID_FILEMAPPING(global_memory_mapping))
        throw USER_EXCEPTION2(SE4074, "See file FAQ shipped with the distribution");

    global_memory = uMapViewOfFile(global_memory_mapping, NULL, PAGE_SIZE, 0, __sys_call_error);
    if (global_memory == NULL)
        throw USER_EXCEPTION(SE4078);

    memset(global_memory, '\0', PAGE_SIZE);
    *(t_layer*)global_memory = INVALID_LAYER;

    //!!! overflow may happen
    strcpy(buf, SEDNA_DATA);
#ifdef _WIN32
    strcat(buf, "\\data");
#else
    strcat(buf, "/data");
#endif
    if (!uIsFileExist(buf, __sys_call_error))
    {
        if (uMkDir(buf, NULL, __sys_call_error) == 0)
            throw USER_EXCEPTION2(SE4300, buf);
    }

    //!!! overflow may happen
#ifdef _WIN32
    strcat(buf, "\\vmm.dat");
#else
    strcat(buf, "/vmm.dat");
#endif

    if (uIsFileExist(buf, __sys_call_error))
    {
        UFile fd = uOpenFile(buf, U_SHARE_READ, U_READ, 0, __sys_call_error);
        if (fd == U_INVALID_FD)
            throw USER_EXCEPTION2(SE4042, "vmm.dat");

        int bytes_read = 0;
        int res = uReadFile(fd, &v, sizeof(vmm_region_values), &bytes_read, __sys_call_error);
        if (res == 0 || bytes_read != sizeof(vmm_region_values))
            throw USER_EXCEPTION2(SE4044, "vmm.dat");

        if (uCloseFile(fd, __sys_call_error) == 0)
            throw USER_EXCEPTION2(SE4043, "vmm.dat");

        LAYER_ADDRESS_SPACE_START_ADDR_INT = v.LAYER_ADDRESS_SPACE_START_ADDR_INT;
        LAYER_ADDRESS_SPACE_BOUNDARY_INT = v.LAYER_ADDRESS_SPACE_BOUNDARY_INT;
        PH_ADDRESS_SPACE_START_ADDR_INT = v.PH_ADDRESS_SPACE_START_ADDR_INT;
        LAYER_ADDRESS_SPACE_SIZE = v.LAYER_ADDRESS_SPACE_SIZE;

        LAYER_ADDRESS_SPACE_START_ADDR = (void*)LAYER_ADDRESS_SPACE_START_ADDR_INT;
        LAYER_ADDRESS_SPACE_BOUNDARY = (void*)LAYER_ADDRESS_SPACE_BOUNDARY_INT;
        PH_ADDRESS_SPACE_START_ADDR = (void*)PH_ADDRESS_SPACE_START_ADDR_INT;

        *(vmm_region_values*)((char*)global_memory + PAGE_SIZE - sizeof(vmm_region_values)) = v;
    }
    else
    {
        char buf2[128];
        uSetEnvironmentVariable(SEDNA_DETERMINE_VMM_REGION, "1", __sys_call_error);
        uSetEnvironmentVariable(SEDNA_OS_PRIMITIVES_ID_MIN_BOUND, u_itoa(os_primitives_id_min_bound, buf2, 10), __sys_call_error);

        char path_buf[U_MAX_PATH + 10];
        std::string path_str = uGetImageProcPath(path_buf, __sys_call_error) + std::string("/") + SESSION_EXE;
        strcpy(path_buf, path_str.c_str());

        UPID pid;
        UPHANDLE process_handle;
        if (uCreateProcess(path_buf,
                           false, // inherit handles
                           NULL,
                           U_DETACHED_PROCESS,
                           &process_handle,
                           NULL,
                           &pid,
                           NULL,
                           NULL,
                           __sys_call_error) != 0)
            throw SYSTEM_ENV_EXCEPTION("Cannot create process to determine VMM region");

        int status = 0;
        int res = 0;

        res = uWaitForChildProcess(pid, process_handle, &status, __sys_call_error);
        if (0 != res || status)
            throw SYSTEM_ENV_EXCEPTION((std::string("Cannot determine VMM region, status: ") + int2string(status) + ", result: " + int2string(res)).c_str());

        uCloseProcess(process_handle, __sys_call_error);
        uSetEnvironmentVariable(SEDNA_DETERMINE_VMM_REGION, "0", __sys_call_error);

        v = *(vmm_region_values*)((char*)global_memory + PAGE_SIZE - sizeof(vmm_region_values));

        LAYER_ADDRESS_SPACE_START_ADDR_INT = v.LAYER_ADDRESS_SPACE_START_ADDR_INT;
        LAYER_ADDRESS_SPACE_BOUNDARY_INT = v.LAYER_ADDRESS_SPACE_BOUNDARY_INT;
        PH_ADDRESS_SPACE_START_ADDR_INT = v.PH_ADDRESS_SPACE_START_ADDR_INT;
        LAYER_ADDRESS_SPACE_SIZE = v.LAYER_ADDRESS_SPACE_SIZE;

        if (LAYER_ADDRESS_SPACE_SIZE < VMM_REGION_MIN_SIZE)
            throw USER_EXCEPTION2(SE1031, (std::string("Determined layer size: ") + int2string(LAYER_ADDRESS_SPACE_SIZE)).c_str());

        LAYER_ADDRESS_SPACE_START_ADDR = (void*)LAYER_ADDRESS_SPACE_START_ADDR_INT;
        LAYER_ADDRESS_SPACE_BOUNDARY = (void*)LAYER_ADDRESS_SPACE_BOUNDARY_INT;
        PH_ADDRESS_SPACE_START_ADDR = (void*)PH_ADDRESS_SPACE_START_ADDR_INT;

        UFile fd = uCreateFile(buf, 0, U_WRITE, 0, NULL, __sys_call_error);
        if (fd == U_INVALID_FD)
            throw USER_EXCEPTION2(SE4040, "vmm.dat");

        int bytes_written = 0;
        res = uWriteFile(fd, &v, sizeof(vmm_region_values), &bytes_written, __sys_call_error);
        if (res == 0 || bytes_written != sizeof(vmm_region_values))
            throw USER_EXCEPTION2(SE4045, "vmm.dat");

        if (uCloseFile(fd, __sys_call_error) == 0)
            throw USER_EXCEPTION2(SE4043, "vmm.dat");
    }

    elog(EL_INFO,  ("Layer address space start addr = 0x%x", LAYER_ADDRESS_SPACE_START_ADDR));
    elog(EL_INFO,  ("Layer address space boundary   = 0x%x", LAYER_ADDRESS_SPACE_BOUNDARY));
    elog(EL_INFO,  ("Persistent heap start addr     = 0x%x", PH_ADDRESS_SPACE_START_ADDR));
}

void release_global_memory_mapping()
{
    if (uUnmapViewOfFile(global_memory_mapping, global_memory, PAGE_SIZE, __sys_call_error) == -1)
        throw USER_EXCEPTION(SE4079);

    if (uReleaseFileMapping(global_memory_mapping, SEDNA_GLOBAL_MEMORY_MAPPING, __sys_call_error) == -1)
        throw USER_EXCEPTION(SE4076);
}

void open_global_memory_mapping(int err_code)
{
    global_memory_mapping = uOpenFileMapping(U_INVALID_FD, PAGE_SIZE, SEDNA_GLOBAL_MEMORY_MAPPING, __sys_call_error);
    if (U_INVALID_FILEMAPPING(global_memory_mapping))
        throw USER_EXCEPTION(err_code);
}

void close_global_memory_mapping()
{
    if (uCloseFileMapping(global_memory_mapping, __sys_call_error) == -1)
        throw USER_EXCEPTION(SE4077);
}

UMMap get_global_memory_mapping()
{
    return global_memory_mapping;
}

void get_vmm_region_values()
{
    global_memory = uMapViewOfFile(global_memory_mapping, NULL, PAGE_SIZE, 0, __sys_call_error);
    if (global_memory == NULL)
        throw USER_EXCEPTION(SE4078);

    vmm_region_values *v;
    v = (vmm_region_values*)((char*)global_memory + PAGE_SIZE - sizeof(vmm_region_values));

    LAYER_ADDRESS_SPACE_START_ADDR_INT = v->LAYER_ADDRESS_SPACE_START_ADDR_INT;
    LAYER_ADDRESS_SPACE_BOUNDARY_INT = v->LAYER_ADDRESS_SPACE_BOUNDARY_INT;
    PH_ADDRESS_SPACE_START_ADDR_INT = v->PH_ADDRESS_SPACE_START_ADDR_INT;
    LAYER_ADDRESS_SPACE_SIZE = v->LAYER_ADDRESS_SPACE_SIZE;

    LAYER_ADDRESS_SPACE_START_ADDR = (void*)LAYER_ADDRESS_SPACE_START_ADDR_INT;
    LAYER_ADDRESS_SPACE_BOUNDARY = (void*)LAYER_ADDRESS_SPACE_BOUNDARY_INT;
    PH_ADDRESS_SPACE_START_ADDR = (void*)PH_ADDRESS_SPACE_START_ADDR_INT;

    if (uUnmapViewOfFile(global_memory_mapping, global_memory, PAGE_SIZE, __sys_call_error) == -1)
        throw USER_EXCEPTION(SE4079);
}

void set_vmm_region_values()
{
    global_memory = uMapViewOfFile(global_memory_mapping, NULL, PAGE_SIZE, 0, __sys_call_error);
    if (global_memory == NULL)
        throw USER_EXCEPTION(SE4078);

    vmm_region_values *v;
    v = (vmm_region_values*)((char*)global_memory + PAGE_SIZE - sizeof(vmm_region_values));

    v->LAYER_ADDRESS_SPACE_START_ADDR_INT = LAYER_ADDRESS_SPACE_START_ADDR_INT;
    v->LAYER_ADDRESS_SPACE_BOUNDARY_INT = LAYER_ADDRESS_SPACE_BOUNDARY_INT;
    v->PH_ADDRESS_SPACE_START_ADDR_INT = PH_ADDRESS_SPACE_START_ADDR_INT;
    v->LAYER_ADDRESS_SPACE_SIZE = LAYER_ADDRESS_SPACE_SIZE;

    if (uUnmapViewOfFile(global_memory_mapping, global_memory, PAGE_SIZE, __sys_call_error) == -1)
        throw USER_EXCEPTION(SE4079);
}

<|endoftext|>


<commit_before>/****************************************************************************
 Copyright (c) Yassy
 https://github.com/yassy0413/cocos2dx-3.x-util
 ****************************************************************************/
#include "CCLazySprite.h"
#include "network/HttpClient.h"

NS_CC_EXT_BEGIN

typedef std::unordered_map<std::string, std::list<LazySprite*>> DownloadingTaskList;
static DownloadingTaskList* _downloadingTasks = nullptr;

void LazySprite::requestDownload(const std::string& url, const std::string& cacheFilePath, const std::string& cacheFileDir, LazySprite* target){

    bool needHttpRequest = true;

    if( _downloadingTasks ){
        auto it = _downloadingTasks->find(url);
        if( it != _downloadingTasks->end() ){
            it->second.push_back(target);
            needHttpRequest = false;
        }
    }else{
        _downloadingTasks = new (std::nothrow) DownloadingTaskList();
    }

    target->retain();

    if( needHttpRequest ){
        _downloadingTasks->emplace(url, std::list<LazySprite*>{target});

        network::HttpRequest* req = new network::HttpRequest();
        req->setRequestType( network::HttpRequest::Type::GET );
        req->setUrl( url.c_str() );
        req->setResponseCallback([cacheFilePath, cacheFileDir](network::HttpClient* client, network::HttpResponse* response){

            std::list<LazySprite*> targets;
            if( _downloadingTasks ){
                auto it = _downloadingTasks->find( response->getHttpRequest()->getUrl() );
                if( it != _downloadingTasks->end() ){
                    targets = std::move(it->second);
                }
                _downloadingTasks->erase(it);

                if( _downloadingTasks->empty() ){
                    CC_SAFE_DELETE(_downloadingTasks);
                }
            }
            CC_ASSERT( !targets.empty() );

            if( response->isSucceed() ){
                // ダウンロードしたファイルをローカルへ保存する
                if( FileUtils::getInstance()->createDirectory( cacheFileDir ) ){
                    FILE* file = fopen( cacheFilePath.c_str(), "wb" );
                    fwrite( &response->getResponseData()->at(0), response->getResponseData()->size(), 1, file );
                    fclose( file );
                }
                for( auto it : targets ){
                    // 自分以外からの参照があれば処理
                    if( it->getReferenceCount() > 1 ){
                        // TODO: make thread. バイナリを直接渡せるようにする
                        it->addImageAsync(cacheFilePath);
                    }
                }
            }else{
                CCASSERT(0, cacheFilePath.c_str());
            }

            for( auto it : targets ){
                it->release();
            }
        });
        network::HttpClient::getInstance()->sendImmediate( req );
    }
}

#pragma mark -- LazySprite

LazySprite::LazySprite()
: _finishedCallback(nullptr)
{}

LazySprite::~LazySprite(){
}

Sprite* LazySprite::createAsync(const std::string& filename, const ccLazySpriteCallback& callback){
    LazySprite *sprite = new (std::nothrow) LazySprite();
    if (sprite && sprite->initAsync(filename, callback))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

Sprite* LazySprite::createWithURL(const std::string& url, const ccLazySpriteCallback& callback, const std::string& cachePath){
    LazySprite *sprite = new (std::nothrow) LazySprite();
    if (sprite && sprite->initWithURL(url, callback, cachePath))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

bool LazySprite::initAsync(const std::string& filename, const ccLazySpriteCallback& callback){
    if( Sprite::init() ){
        addImageAsync(filename);
        return true;
    }
    return false;
}

bool LazySprite::initWithURL(const std::string& url, const ccLazySpriteCallback& callback, const std::string& cachePath){
    if( Sprite::init() ){
        _finishedCallback = callback;

        std::string cacheFileDir = FileUtils::getInstance()->getWritablePath() + cachePath;
        if( *cacheFileDir.rbegin() != '/' ){
            cacheFileDir.push_back('/');
        }

        std::string filename;
        const auto separator = url.rfind('/');
        if( separator != std::string::npos ){
            const std::string domain = url.substr(0, separator);
            if( !domain.empty() ){
                char* buf;
                cocos2d::base64Encode((const unsigned char*)domain.c_str(), (unsigned int)domain.length(), &buf);
                cacheFileDir += buf;
                cacheFileDir.push_back('/');
                free(buf);
            }
            filename = url.substr(separator+1, std::string::npos);
            if( !filename.empty() ){
                char* buf;
                cocos2d::base64Encode((const unsigned char*)filename.c_str(), (unsigned int)filename.length(), &buf);
                filename = buf;
                free(buf);
            }
        }
        if( filename.empty() ){
            filename = cocos2d::StringUtils::toString( std::hash<std::string>()(url) );
        }
        const std::string cacheFilePath = cacheFileDir + filename;

        if( FileUtils::getInstance()->isFileExist( cacheFilePath ) ){
            addImageAsync(cacheFilePath);
            CCLOG("cache hit [%s]", url.c_str());
        }else{
            requestDownload(url, cacheFilePath, cacheFileDir, this);
        }
        return true;
    }
    return false;
}

void LazySprite::addImageAsync(const std::string& filename){
    retain();
    Director::getInstance()->getTextureCache()->addImageAsync( filename, [this](Texture2D* texture){

        // 自分以外からの参照があれば処理
        if( getReferenceCount() > 1 ){
            setTexture( texture );
            setTextureRect( Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height ) );
            if( _finishedCallback != nullptr ){
                _finishedCallback( this );
            }
        }

        release();
    });
}

NS_CC_EXT_END
<commit_msg>HttpRequest のメモリリーク修正<commit_after>/****************************************************************************
 Copyright (c) Yassy
 https://github.com/yassy0413/cocos2dx-3.x-util
 ****************************************************************************/
#include "CCLazySprite.h"
#include "network/HttpClient.h"

NS_CC_EXT_BEGIN

typedef std::unordered_map<std::string, std::list<LazySprite*>> DownloadingTaskList;
static DownloadingTaskList* _downloadingTasks = nullptr;

void LazySprite::requestDownload(const std::string& url, const std::string& cacheFilePath, const std::string& cacheFileDir, LazySprite* target){

    bool needHttpRequest = true;

    if( _downloadingTasks ){
        auto it = _downloadingTasks->find(url);
        if( it != _downloadingTasks->end() ){
            it->second.push_back(target);
            needHttpRequest = false;
        }
    }else{
        _downloadingTasks = new (std::nothrow) DownloadingTaskList();
    }

    target->retain();

    if( needHttpRequest ){
        _downloadingTasks->emplace(url, std::list<LazySprite*>{target});

        network::HttpRequest* req = new network::HttpRequest();
        req->setRequestType( network::HttpRequest::Type::GET );
        req->setUrl( url.c_str() );
        req->setResponseCallback([cacheFilePath, cacheFileDir](network::HttpClient* client, network::HttpResponse* response){

            std::list<LazySprite*> targets;
            if( _downloadingTasks ){
                auto it = _downloadingTasks->find( response->getHttpRequest()->getUrl() );
                if( it != _downloadingTasks->end() ){
                    targets = std::move(it->second);
                }
                _downloadingTasks->erase(it);

                if( _downloadingTasks->empty() ){
                    CC_SAFE_DELETE(_downloadingTasks);
                }
            }
            CC_ASSERT( !targets.empty() );

            if( response->isSucceed() ){
                // ダウンロードしたファイルをローカルへ保存する
                if( FileUtils::getInstance()->createDirectory( cacheFileDir ) ){
                    FILE* file = fopen( cacheFilePath.c_str(), "wb" );
                    fwrite( response->getResponseData()->data(), response->getResponseData()->size(), 1, file );
                    fclose( file );
                }
                for( auto it : targets ){
                    // 自分以外からの参照があれば処理
                    if( it->getReferenceCount() > 1 ){
                        // TODO: make thread. バイナリを直接渡せるようにする
                        it->addImageAsync(cacheFilePath);
                    }
                }
            }else{
                CCASSERT(0, cacheFilePath.c_str());
            }

            for( auto it : targets ){
                it->release();
            }
        });
        network::HttpClient::getInstance()->sendImmediate( req );
        req->release();
    }
}

#pragma mark -- LazySprite

LazySprite::LazySprite()
: _finishedCallback(nullptr)
{}

LazySprite::~LazySprite(){
}

Sprite* LazySprite::createAsync(const std::string& filename, const ccLazySpriteCallback& callback){
    LazySprite *sprite = new (std::nothrow) LazySprite();
    if (sprite && sprite->initAsync(filename, callback))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

Sprite* LazySprite::createWithURL(const std::string& url, const ccLazySpriteCallback& callback, const std::string& cachePath){
    LazySprite *sprite = new (std::nothrow) LazySprite();
    if (sprite && sprite->initWithURL(url, callback, cachePath))
    {
        sprite->autorelease();
        return sprite;
    }
    CC_SAFE_DELETE(sprite);
    return nullptr;
}

bool LazySprite::initAsync(const std::string& filename, const ccLazySpriteCallback& callback){
    if( Sprite::init() ){
        addImageAsync(filename);
        return true;
    }
    return false;
}

bool LazySprite::initWithURL(const std::string& url, const ccLazySpriteCallback& callback, const std::string& cachePath){
    if( Sprite::init() ){
        _finishedCallback = callback;

        std::string cacheFileDir = FileUtils::getInstance()->getWritablePath() + cachePath;
        if( *cacheFileDir.rbegin() != '/' ){
            cacheFileDir.push_back('/');
        }

        std::string filename;
        const auto separator = url.rfind('/');
        if( separator != std::string::npos ){
            const std::string domain = url.substr(0, separator);
            if( !domain.empty() ){
                char* buf;
                cocos2d::base64Encode((const unsigned char*)domain.c_str(), (unsigned int)domain.length(), &buf);
                cacheFileDir += buf;
                cacheFileDir.push_back('/');
                free(buf);
            }
            filename = url.substr(separator+1, std::string::npos);
            if( !filename.empty() ){
                char* buf;
                cocos2d::base64Encode((const unsigned char*)filename.c_str(), (unsigned int)filename.length(), &buf);
                filename = buf;
                free(buf);
            }
        }
        if( filename.empty() ){
            filename = cocos2d::StringUtils::toString( std::hash<std::string>()(url) );
        }
        const std::string cacheFilePath = cacheFileDir + filename;

        if( FileUtils::getInstance()->isFileExist( cacheFilePath ) ){
            addImageAsync(cacheFilePath);
            CCLOG("cache hit [%s]", url.c_str());
        }else{
            requestDownload(url, cacheFilePath, cacheFileDir, this);
        }
        return true;
    }
    return false;
}

void LazySprite::addImageAsync(const std::string& filename){
    retain();
    Director::getInstance()->getTextureCache()->addImageAsync( filename, [this](Texture2D* texture){

        // 自分以外からの参照があれば処理
        if( getReferenceCount() > 1 ){
            setTexture( texture );
            setTextureRect( Rect(0, 0, texture->getContentSize().width, texture->getContentSize().height ) );
            if( _finishedCallback != nullptr ){
                _finishedCallback( this );
            }
        }

        release();
    });
}

NS_CC_EXT_END
<|endoftext|>


<commit_before>#include "PrintMPIBackendASTVisitor.hpp"

namespace
{
    const char* impl_cppStartString()
    {
        return
"\n"
"// This program was created by the Equelle compiler from SINTEF.\n"
"\n"
"#include <opm/core/utility/parameters/ParameterGroup.hpp>\n"
"#include <opm/core/linalg/LinearSolverFactory.hpp>\n"
"#include <opm/core/utility/ErrorMacros.hpp>\n"
"#include <opm/autodiff/AutoDiffBlock.hpp>\n"
"#include <opm/autodiff/AutoDiffHelpers.hpp>\n"
"#include <opm/core/grid.h>\n"
"#include <opm/core/grid/GridManager.hpp>\n"
"#include <algorithm>\n"
"#include <iterator>\n"
"#include <iostream>\n"
"#include <cmath>\n"
"#include <array>\n"
"\n"
"#include \"equelle/RuntimeMPI.hpp\"\n"
"\n"
"void ensureRequirements(const equelle::RuntimeMPI& er);\n"
"void equelleGeneratedCode(equelle::RuntimeMPI& er);\n"
"\n"
 "#ifndef EQUELLE_NO_MAIN\n"
"int main(int argc, char** argv)\n"
"{\n"
"    // Get user parameters.\n"
"    Opm::parameter::ParameterGroup param(argc, argv, false);\n"
"\n"
"    // Create the Equelle runtime.\n"
"    equelle::RuntimeMPI er(param);\n"
"    equelleGeneratedCode(er);\n"
"    return 0;\n"
"}\n"
"#endif // EQUELLE_NO_MAIN\n"
"\n"
"void equelleGeneratedCode(equelle::RuntimeMPI& er) {\n"
"    using namespace equelle;\n"
"    ensureRequirements(er);\n"
"\n"
"    // ============= Generated code starts here ================\n";
    }

    const char* impl_cppEndString()
    {
        return "\n"
"    // ============= Generated code ends here ================\n"
"\n"
"}\n";
    }
}

PrintMPIBackendASTVisitor::PrintMPIBackendASTVisitor()
{
}

PrintMPIBackendASTVisitor::~PrintMPIBackendASTVisitor()
{

}

const char *PrintMPIBackendASTVisitor::cppStartString() const
{
    return ::impl_cppStartString();
}

const char *PrintMPIBackendASTVisitor::cppEndString() const
{
    return ::impl_cppEndString();
}

<commit_msg>PrintMPIBackendASTVisitor::cppStartString so that it initializes MPI and decomposes the grid.<commit_after>#include "PrintMPIBackendASTVisitor.hpp"

namespace
{
    const char* impl_cppStartString()
    {
        return
"\n"
"// This program was created by the Equelle compiler from SINTEF.\n"
"\n"
"#include <opm/core/utility/parameters/ParameterGroup.hpp>\n"
"#include <opm/core/linalg/LinearSolverFactory.hpp>\n"
"#include <opm/core/utility/ErrorMacros.hpp>\n"
"#include <opm/autodiff/AutoDiffBlock.hpp>\n"
"#include <opm/autodiff/AutoDiffHelpers.hpp>\n"
"#include <opm/core/grid.h>\n"
"#include <opm/core/grid/GridManager.hpp>\n"
"#include <algorithm>\n"
"#include <iterator>\n"
"#include <iostream>\n"
"#include <cmath>\n"
"#include <array>\n"
"\n"
"#include \"equelle/RuntimeMPI.hpp\"\n"
"\n"
"//void ensureRequirements(const equelle::RuntimeMPI& er);\n"
"void equelleGeneratedCode(equelle::RuntimeMPI& er);\n"
"\n"
 "#ifndef EQUELLE_NO_MAIN\n"
"int main(int argc, char** argv)\n"
"{\n"
"    // Initialize MPI\n"
"    equelle::MPIInitializer mpiInitializer;"
"    // Get user parameters.\n"
"    Opm::parameter::ParameterGroup param(argc, argv, false);\n"
"\n"
"    // Create the Equelle runtime.\n"
"    equelle::RuntimeMPI er(param);\n"
"    er.decompose();"
"    equelleGeneratedCode(er);\n"
"    return 0;\n"
"}\n"
"#endif // EQUELLE_NO_MAIN\n"
"\n"
"void equelleGeneratedCode(equelle::RuntimeMPI& er) {\n"
"    using namespace equelle;\n"
"    //ensureRequirements(er);\n"
"\n"
"    // ============= Generated code starts here ================\n";
    }

    const char* impl_cppEndString()
    {
        return "\n"
"    // ============= Generated code ends here ================\n"
"\n"
"}\n";
    }
}

PrintMPIBackendASTVisitor::PrintMPIBackendASTVisitor()
{
}

PrintMPIBackendASTVisitor::~PrintMPIBackendASTVisitor()
{

}

const char *PrintMPIBackendASTVisitor::cppStartString() const
{
    return ::impl_cppStartString();
}

const char *PrintMPIBackendASTVisitor::cppEndString() const
{
    return ::impl_cppEndString();
}

<|endoftext|>


<commit_before>#ifndef ENTT_CORE_ANY_HPP
#define ENTT_CORE_ANY_HPP

#include <cstddef>
#include <functional>
#include <new>
#include <type_traits>
#include <utility>
#include "../config/config.h"
#include "fwd.hpp"
#include "type_info.hpp"
#include "type_traits.hpp"

namespace entt {

/**
 * @brief A SBO friendly, type-safe container for single values of any type.
 * @tparam Len Size of the storage reserved for the small buffer optimization.
 */
template<std::size_t Len>
class basic_any {
    enum class operation { COPY, MOVE, DTOR, COMP, ADDR, CADDR, REF, CREF, TYPE };

    using storage_type = std::aligned_storage_t<Len == 0u ? 1u : Len>;
    using vtable_type = const void *(const operation, const basic_any &, const void *);

    template<typename Type>
    static constexpr auto in_situ = (Len != 0u) && (sizeof(Type) <= sizeof(storage_type)) && std::is_nothrow_move_constructible_v<Type>;

    template<typename Type>
    [[nodiscard]] static bool compare(const void *lhs, const void *rhs) {
        if constexpr(!std::is_function_v<Type> && is_equality_comparable_v<Type>) {
            return *static_cast<const Type *>(lhs) == *static_cast<const Type *>(rhs);
        } else {
            return lhs == rhs;
        }
    }

    template<typename Type>
    static Type & as(const void *to) {
        return *const_cast<Type *>(static_cast<const Type *>(to));
    }

    template<typename Type>
    static const void * basic_vtable([[maybe_unused]] const operation op, [[maybe_unused]] const basic_any &from, [[maybe_unused]] const void *to) {
        if constexpr(!std::is_void_v<Type>) {
            if constexpr(std::is_lvalue_reference_v<Type>) {
                using base_type = std::remove_const_t<std::remove_reference_t<Type>>;

                switch(op) {
                case operation::COPY:
                    if constexpr(std::is_copy_constructible_v<base_type>) {
                        as<basic_any>(to).emplace<base_type>(*static_cast<const base_type *>(from.instance));
                    }
                    break;
                case operation::MOVE:
                    as<basic_any>(to).instance = from.instance;
                case operation::DTOR:
                    break;
                case operation::COMP:
                    return compare<base_type>(from.instance, to) ? to : nullptr;
                case operation::ADDR:
                    return std::is_const_v<std::remove_reference_t<Type>> ? nullptr : from.instance;
                case operation::CADDR:
                    return from.instance;
                case operation::REF:
                    as<basic_any>(to).instance = from.instance;
                    as<basic_any>(to).vtable = basic_vtable<Type>;
                    break;
                case operation::CREF:
                    as<basic_any>(to).instance = from.instance;
                    as<basic_any>(to).vtable = basic_vtable<const base_type &>;
                    break;
                case operation::TYPE:
                    as<type_info>(to) = type_id<base_type>();
                    break;
                }
            } else if constexpr(in_situ<Type>) {
                #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606L
                auto *instance = const_cast<Type *>(std::launder(reinterpret_cast<const Type *>(&from.storage)));
                #else
                auto *instance = const_cast<Type *>(reinterpret_cast<const Type *>(&from.storage));
                #endif

                switch(op) {
                case operation::COPY:
                    if constexpr(std::is_copy_constructible_v<Type>) {
                        new (&as<basic_any>(to).storage) Type{std::as_const(*instance)};
                        as<basic_any>(to).vtable = from.vtable;
                    }
                    break;
                case operation::MOVE:
                    new (&as<basic_any>(to).storage) Type{std::move(*instance)};
                    [[fallthrough]];
                case operation::DTOR:
                    instance->~Type();
                    break;
                case operation::COMP:
                    return compare<Type>(instance, to) ? to : nullptr;
                case operation::ADDR:
                case operation::CADDR:
                    return instance;
                case operation::REF:
                    as<basic_any>(to).instance = instance;
                    as<basic_any>(to).vtable = basic_vtable<Type &>;
                    break;
                case operation::CREF:
                    as<basic_any>(to).instance = instance;
                    as<basic_any>(to).vtable = basic_vtable<const Type &>;
                    break;
                case operation::TYPE:
                    as<type_info>(to) = type_id<Type>();
                    break;
                }
            } else {
                switch(op) {
                case operation::COPY:
                    if constexpr(std::is_copy_constructible_v<Type>) {
                        as<basic_any>(to).instance = new Type{*static_cast<const Type *>(from.instance)};
                        as<basic_any>(to).vtable = from.vtable;
                    }
                    break;
                case operation::MOVE:
                    as<basic_any>(to).instance = from.instance;
                    break;
                case operation::DTOR:
                    if constexpr(std::is_array_v<Type>) {
                        delete[] static_cast<const Type *>(from.instance);
                    } else {
                        delete static_cast<const Type *>(from.instance);
                    }
                    break;
                case operation::COMP:
                    return compare<Type>(from.instance, to) ? to : nullptr;
                case operation::ADDR:
                case operation::CADDR:
                    return from.instance;
                case operation::REF:
                    as<basic_any>(to).instance = from.instance;
                    as<basic_any>(to).vtable = basic_vtable<Type &>;
                    break;
                case operation::CREF:
                    as<basic_any>(to).instance = from.instance;
                    as<basic_any>(to).vtable = basic_vtable<const Type &>;
                    break;
                case operation::TYPE:
                    as<type_info>(to) = type_id<Type>();
                    break;
                }
            }
        }

        return nullptr;
    }

public:
    /*! @brief Default constructor. */
    basic_any() ENTT_NOEXCEPT
        : basic_any{std::in_place_type<void>}
    {}

    /**
     * @brief Constructs an any by directly initializing the new object.
     * @tparam Type Type of object to use to initialize the wrapper.
     * @tparam Args Types of arguments to use to construct the new instance.
     * @param args Parameters to use to construct the instance.
     */
    template<typename Type, typename... Args>
    explicit basic_any(std::in_place_type_t<Type>, [[maybe_unused]] Args &&... args)
        : vtable{&basic_vtable<Type>},
          instance{}
    {
        if constexpr(!std::is_void_v<Type>) {
            if constexpr(std::is_lvalue_reference_v<Type>) {
                static_assert(sizeof...(Args) == 1u && (std::is_lvalue_reference_v<Args> && ...));
                instance = (&args, ...);
            } else if constexpr(in_situ<Type>) {
                new (&storage) Type(std::forward<Args>(args)...);
            } else {
                instance = new Type(std::forward<Args>(args)...);
            }
        }
    }

    /**
     * @brief Constructs an any that holds an unmanaged object.
     * @tparam Type Type of object to use to initialize the wrapper.
     * @param value An instance of an object to use to initialize the wrapper.
     */
    template<typename Type>
    basic_any(std::reference_wrapper<Type> value) ENTT_NOEXCEPT
        : basic_any{std::in_place_type<Type &>, value.get()}
    {}

    /**
     * @brief Constructs an any from a given value.
     * @tparam Type Type of object to use to initialize the wrapper.
     * @param value An instance of an object to use to initialize the wrapper.
     */
    template<typename Type, typename = std::enable_if_t<!std::is_same_v<std::decay_t<Type>, basic_any>>>
    basic_any(Type &&value)
        : basic_any{std::in_place_type<std::decay_t<Type>>, std::forward<Type>(value)}
    {}

    /**
     * @brief Copy constructor.
     * @param other The instance to copy from.
     */
    basic_any(const basic_any &other)
        : basic_any{}
    {
        other.vtable(operation::COPY, other, this);
    }

    /**
     * @brief Move constructor.
     * @param other The instance to move from.
     */
    basic_any(basic_any &&other) ENTT_NOEXCEPT
        : basic_any{}
    {
        other.vtable(operation::MOVE, other, this);
        vtable = std::exchange(other.vtable, &basic_vtable<void>);
    }

    /*! @brief Frees the internal storage, whatever it means. */
    ~basic_any() {
        vtable(operation::DTOR, *this, nullptr);
    }

    /**
     * @brief Assignment operator.
     * @param other The instance to assign from.
     * @return This any object.
     */
    basic_any & operator=(basic_any other) {
        swap(*this, other);
        return *this;
    }

    /**
     * @brief Returns the type of the contained object.
     * @return The type of the contained object, if any.
     */
    [[nodiscard]] type_info type() const ENTT_NOEXCEPT {
        type_info info;
        vtable(operation::TYPE, *this, &info);
        return info;
    }

    /**
     * @brief Returns an opaque pointer to the contained instance.
     * @return An opaque pointer the contained instance, if any.
     */
    [[nodiscard]] const void * data() const ENTT_NOEXCEPT {
        return vtable(operation::CADDR, *this, nullptr);
    }

    /*! @copydoc data */
    [[nodiscard]] void * data() ENTT_NOEXCEPT {
        return const_cast<void *>(vtable(operation::ADDR, *this, nullptr));
    }

    /**
     * @brief Replaces the contained object by creating a new instance directly.
     * @tparam Type Type of object to use to initialize the wrapper.
     * @tparam Args Types of arguments to use to construct the new instance.
     * @param args Parameters to use to construct the instance.
     */
    template<typename Type, typename... Args>
    void emplace(Args &&... args) {
        *this = basic_any{std::in_place_type<Type>, std::forward<Args>(args)...};
    }

    /*! @brief Destroys contained object */
    void reset() {
        *this = basic_any{};
    }

    /**
     * @brief Returns false if a wrapper is empty, true otherwise.
     * @return False if the wrapper is empty, true otherwise.
     */
    [[nodiscard]] explicit operator bool() const ENTT_NOEXCEPT {
        return !(vtable(operation::CADDR, *this, nullptr) == nullptr);
    }

    /**
     * @brief Checks if two wrappers differ in their content.
     * @param other Wrapper with which to compare.
     * @return False if the two objects differ in their content, true otherwise.
     */
    bool operator==(const basic_any &other) const ENTT_NOEXCEPT {
        return type() == other.type() && (vtable(operation::COMP, *this, other.data()) == other.data());
    }

    /**
     * @brief Swaps two any objects.
     * @param lhs A valid any object.
     * @param rhs A valid any object.
     */
    friend void swap(basic_any &lhs, basic_any &rhs) {
        basic_any tmp{};
        lhs.vtable(operation::MOVE, lhs, &tmp);
        rhs.vtable(operation::MOVE, rhs, &lhs);
        lhs.vtable(operation::MOVE, tmp, &rhs);
        std::swap(lhs.vtable, rhs.vtable);
    }

    /**
     * @brief Aliasing constructor.
     * @return An any that shares a reference to an unmanaged object.
     */
    [[nodiscard]] basic_any as_ref() ENTT_NOEXCEPT {
        basic_any ref{};
        vtable(operation::REF, *this, &ref);
        return ref;
    }

    /*! @copydoc as_ref */
    [[nodiscard]] basic_any as_ref() const ENTT_NOEXCEPT {
        basic_any ref{};
        vtable(operation::CREF, *this, &ref);
        return ref;
    }

private:
    vtable_type *vtable;
    union { const void *instance = nullptr; storage_type storage; };
};

/**
 * @brief Checks if two wrappers differ in their content.
 * @tparam Len Size of the storage reserved for the small buffer optimization.
 * @param lhs A wrapper, either empty or not.
 * @param rhs A wrapper, either empty or not.
 * @return True if the two wrappers differ in their content, false otherwise.
 */
template<std::size_t Len>
[[nodiscard]] inline bool operator!=(const basic_any<Len> &lhs, const basic_any<Len> &rhs) ENTT_NOEXCEPT {
    return !(lhs == rhs);
}

/**
 * @brief Performs type-safe access to the contained object.
 * @tparam Len Size of the storage reserved for the small buffer optimization.
 * @tparam Type Type to which conversion is required.
 * @param data Target any object.
 * @return The element converted to the requested type.
 */
template<typename Type, std::size_t Len>
Type any_cast(const basic_any<Len> &data) ENTT_NOEXCEPT {
    const auto * const instance = any_cast<std::remove_reference_t<Type>>(&data);
    ENTT_ASSERT(instance);
    return static_cast<Type>(*instance);
}

/*! @copydoc any_cast */
template<typename Type, std::size_t Len>
Type any_cast(basic_any<Len> &data) ENTT_NOEXCEPT {
    // forces const on non-reference types to make them work also with wrappers for const references
    auto * const instance = any_cast<std::conditional_t<std::is_reference_v<Type>, std::remove_reference_t<Type>, const Type>>(&data);
    ENTT_ASSERT(instance);
    return static_cast<Type>(*instance);
}

/*! @copydoc any_cast */
template<typename Type, std::size_t Len>
Type any_cast(basic_any<Len> &&data) ENTT_NOEXCEPT {
    // forces const on non-reference types to make them work also with wrappers for const references
    auto * const instance = any_cast<std::conditional_t<std::is_reference_v<Type>, std::remove_reference_t<Type>, const Type>>(&data);
    ENTT_ASSERT(instance);
    return static_cast<Type>(std::move(*instance));
}

/*! @copydoc any_cast */
template<typename Type, std::size_t Len>
const Type * any_cast(const basic_any<Len> *data) ENTT_NOEXCEPT {
    return (data->type() == type_id<Type>() ? static_cast<const Type *>(data->data()) : nullptr);
}

/*! @copydoc any_cast */
template<typename Type, std::size_t Len>
Type * any_cast(basic_any<Len> *data) ENTT_NOEXCEPT {
    // last attempt to make wrappers for const references return their values
    return (data->type() == type_id<Type>() ? static_cast<Type *>(static_cast<constness_as_t<basic_any<Len>, Type> *>(data)->data()) : nullptr);
}

}

#endif
<commit_msg>any: make VS happy :)<commit_after>#ifndef ENTT_CORE_ANY_HPP
#define ENTT_CORE_ANY_HPP

#include <cstddef>
#include <functional>
#include <new>
#include <type_traits>
#include <utility>
#include "../config/config.h"
#include "fwd.hpp"
#include "type_info.hpp"
#include "type_traits.hpp"

namespace entt {

/**
 * @brief A SBO friendly, type-safe container for single values of any type.
 * @tparam Len Size of the storage reserved for the small buffer optimization.
 */
template<std::size_t Len>
class basic_any {
    enum class operation { COPY, MOVE, DTOR, COMP, ADDR, CADDR, REF, CREF, TYPE };

    using storage_type = std::aligned_storage_t<Len == 0u ? 1u : Len>;
    using vtable_type = const void *(const operation, const basic_any &, const void *);

    template<typename Type>
    static constexpr auto in_situ = (Len != 0u) && (sizeof(Type) <= sizeof(storage_type)) && std::is_nothrow_move_constructible_v<Type>;

    template<typename Type>
    [[nodiscard]] static bool compare(const void *lhs, const void *rhs) {
        if constexpr(!std::is_function_v<Type> && is_equality_comparable_v<Type>) {
            return *static_cast<const Type *>(lhs) == *static_cast<const Type *>(rhs);
        } else {
            return lhs == rhs;
        }
    }

    template<typename Type>
    static Type & as(const void *to) {
        return *const_cast<Type *>(static_cast<const Type *>(to));
    }

    template<typename Type>
    static const void * basic_vtable([[maybe_unused]] const operation op, [[maybe_unused]] const basic_any &from, [[maybe_unused]] const void *to) {
        if constexpr(!std::is_void_v<Type>) {
            if constexpr(std::is_lvalue_reference_v<Type>) {
                using base_type = std::remove_const_t<std::remove_reference_t<Type>>;

                switch(op) {
                case operation::COPY:
                    if constexpr(std::is_copy_constructible_v<base_type>) {
                        as<basic_any>(to).emplace<base_type>(*static_cast<const base_type *>(from.instance));
                    }
                    break;
                case operation::MOVE:
                    as<basic_any>(to).instance = from.instance;
                case operation::DTOR:
                    break;
                case operation::COMP:
                    return compare<base_type>(from.instance, to) ? to : nullptr;
                case operation::ADDR:
                    return std::is_const_v<std::remove_reference_t<Type>> ? nullptr : from.instance;
                case operation::CADDR:
                    return from.instance;
                case operation::REF:
                    as<basic_any>(to).instance = from.instance;
                    as<basic_any>(to).vtable = basic_vtable<Type>;
                    break;
                case operation::CREF:
                    as<basic_any>(to).instance = from.instance;
                    as<basic_any>(to).vtable = basic_vtable<const base_type &>;
                    break;
                case operation::TYPE:
                    as<type_info>(to) = type_id<base_type>();
                    break;
                }
            } else if constexpr(in_situ<Type>) {
                #if defined(__cpp_lib_launder) && __cpp_lib_launder >= 201606L
                auto *instance = const_cast<Type *>(std::launder(reinterpret_cast<const Type *>(&from.storage)));
                #else
                auto *instance = const_cast<Type *>(reinterpret_cast<const Type *>(&from.storage));
                #endif

                switch(op) {
                case operation::COPY:
                    if constexpr(std::is_copy_constructible_v<Type>) {
                        new (&as<basic_any>(to).storage) Type{std::as_const(*instance)};
                        as<basic_any>(to).vtable = from.vtable;
                    }
                    break;
                case operation::MOVE:
                    new (&as<basic_any>(to).storage) Type{std::move(*instance)};
                    [[fallthrough]];
                case operation::DTOR:
                    instance->~Type();
                    break;
                case operation::COMP:
                    return compare<Type>(instance, to) ? to : nullptr;
                case operation::ADDR:
                case operation::CADDR:
                    return instance;
                case operation::REF:
                    as<basic_any>(to).instance = instance;
                    as<basic_any>(to).vtable = basic_vtable<Type &>;
                    break;
                case operation::CREF:
                    as<basic_any>(to).instance = instance;
                    as<basic_any>(to).vtable = basic_vtable<const Type &>;
                    break;
                case operation::TYPE:
                    as<type_info>(to) = type_id<Type>();
                    break;
                }
            } else {
                switch(op) {
                case operation::COPY:
                    if constexpr(std::is_copy_constructible_v<Type>) {
                        as<basic_any>(to).instance = new Type{*static_cast<const Type *>(from.instance)};
                        as<basic_any>(to).vtable = from.vtable;
                    }
                    break;
                case operation::MOVE:
                    as<basic_any>(to).instance = from.instance;
                    break;
                case operation::DTOR:
                    if constexpr(std::is_array_v<Type>) {
                        delete[] static_cast<const Type *>(from.instance);
                    } else {
                        delete static_cast<const Type *>(from.instance);
                    }
                    break;
                case operation::COMP:
                    return compare<Type>(from.instance, to) ? to : nullptr;
                case operation::ADDR:
                case operation::CADDR:
                    return from.instance;
                case operation::REF:
                    as<basic_any>(to).instance = from.instance;
                    as<basic_any>(to).vtable = basic_vtable<Type &>;
                    break;
                case operation::CREF:
                    as<basic_any>(to).instance = from.instance;
                    as<basic_any>(to).vtable = basic_vtable<const Type &>;
                    break;
                case operation::TYPE:
                    as<type_info>(to) = type_id<Type>();
                    break;
                }
            }
        }

        return nullptr;
    }

public:
    /*! @brief Default constructor. */
    basic_any() ENTT_NOEXCEPT
        : basic_any{std::in_place_type<void>}
    {}

    /**
     * @brief Constructs an any by directly initializing the new object.
     * @tparam Type Type of object to use to initialize the wrapper.
     * @tparam Args Types of arguments to use to construct the new instance.
     * @param args Parameters to use to construct the instance.
     */
    template<typename Type, typename... Args>
    explicit basic_any(std::in_place_type_t<Type>, [[maybe_unused]] Args &&... args)
        : vtable{&basic_vtable<Type>},
          instance{}
    {
        if constexpr(!std::is_void_v<Type>) {
            if constexpr(std::is_lvalue_reference_v<Type>) {
                static_assert(sizeof...(Args) == 1u && (std::is_lvalue_reference_v<Args> && ...));
                instance = (&args, ...);
            } else if constexpr(in_situ<Type>) {
                new (&storage) Type(std::forward<Args>(args)...);
            } else {
                instance = new Type(std::forward<Args>(args)...);
            }
        }
    }

    /**
     * @brief Constructs an any that holds an unmanaged object.
     * @tparam Type Type of object to use to initialize the wrapper.
     * @param value An instance of an object to use to initialize the wrapper.
     */
    template<typename Type>
    basic_any(std::reference_wrapper<Type> value) ENTT_NOEXCEPT
        : basic_any{std::in_place_type<Type &>, value.get()}
    {}

    /**
     * @brief Constructs an any from a given value.
     * @tparam Type Type of object to use to initialize the wrapper.
     * @param value An instance of an object to use to initialize the wrapper.
     */
    template<typename Type, typename = std::enable_if_t<!std::is_same_v<std::decay_t<Type>, basic_any>>>
    basic_any(Type &&value)
        : basic_any{std::in_place_type<std::decay_t<Type>>, std::forward<Type>(value)}
    {}

    /**
     * @brief Copy constructor.
     * @param other The instance to copy from.
     */
    basic_any(const basic_any &other)
        : basic_any{}
    {
        other.vtable(operation::COPY, other, this);
    }

    /**
     * @brief Move constructor.
     * @param other The instance to move from.
     */
    basic_any(basic_any &&other) ENTT_NOEXCEPT
        : basic_any{}
    {
        other.vtable(operation::MOVE, other, this);
        vtable = std::exchange(other.vtable, &basic_vtable<void>);
    }

    /*! @brief Frees the internal storage, whatever it means. */
    ~basic_any() {
        vtable(operation::DTOR, *this, nullptr);
    }

    /**
     * @brief Assignment operator.
     * @param other The instance to assign from.
     * @return This any object.
     */
    basic_any & operator=(basic_any other) {
        swap(*this, other);
        return *this;
    }

    /**
     * @brief Returns the type of the contained object.
     * @return The type of the contained object, if any.
     */
    [[nodiscard]] type_info type() const ENTT_NOEXCEPT {
        type_info info;
        vtable(operation::TYPE, *this, &info);
        return info;
    }

    /**
     * @brief Returns an opaque pointer to the contained instance.
     * @return An opaque pointer the contained instance, if any.
     */
    [[nodiscard]] const void * data() const ENTT_NOEXCEPT {
        return vtable(operation::CADDR, *this, nullptr);
    }

    /*! @copydoc data */
    [[nodiscard]] void * data() ENTT_NOEXCEPT {
        return const_cast<void *>(vtable(operation::ADDR, *this, nullptr));
    }

    /**
     * @brief Replaces the contained object by creating a new instance directly.
     * @tparam Type Type of object to use to initialize the wrapper.
     * @tparam Args Types of arguments to use to construct the new instance.
     * @param args Parameters to use to construct the instance.
     */
    template<typename Type, typename... Args>
    void emplace(Args &&... args) {
        *this = basic_any{std::in_place_type<Type>, std::forward<Args>(args)...};
    }

    /*! @brief Destroys contained object */
    void reset() {
        *this = basic_any{};
    }

    /**
     * @brief Returns false if a wrapper is empty, true otherwise.
     * @return False if the wrapper is empty, true otherwise.
     */
    [[nodiscard]] explicit operator bool() const ENTT_NOEXCEPT {
        return !(vtable(operation::CADDR, *this, nullptr) == nullptr);
    }

    /**
     * @brief Checks if two wrappers differ in their content.
     * @param other Wrapper with which to compare.
     * @return False if the two objects differ in their content, true otherwise.
     */
    bool operator==(const basic_any &other) const ENTT_NOEXCEPT {
        return type() == other.type() && (vtable(operation::COMP, *this, other.data()) == other.data());
    }

    /**
     * @brief Swaps two any objects.
     * @param lhs A valid any object.
     * @param rhs A valid any object.
     */
    friend void swap(basic_any &lhs, basic_any &rhs) {
        basic_any tmp{};
        lhs.vtable(operation::MOVE, lhs, &tmp);
        rhs.vtable(operation::MOVE, rhs, &lhs);
        lhs.vtable(operation::MOVE, tmp, &rhs);
        std::swap(lhs.vtable, rhs.vtable);
    }

    /**
     * @brief Aliasing constructor.
     * @return An any that shares a reference to an unmanaged object.
     */
    [[nodiscard]] basic_any as_ref() ENTT_NOEXCEPT {
        basic_any ref{};
        vtable(operation::REF, *this, &ref);
        return ref;
    }

    /*! @copydoc as_ref */
    [[nodiscard]] basic_any as_ref() const ENTT_NOEXCEPT {
        basic_any ref{};
        vtable(operation::CREF, *this, &ref);
        return ref;
    }

private:
    vtable_type *vtable;
    union { const void *instance; storage_type storage{}; };
};

/**
 * @brief Checks if two wrappers differ in their content.
 * @tparam Len Size of the storage reserved for the small buffer optimization.
 * @param lhs A wrapper, either empty or not.
 * @param rhs A wrapper, either empty or not.
 * @return True if the two wrappers differ in their content, false otherwise.
 */
template<std::size_t Len>
[[nodiscard]] inline bool operator!=(const basic_any<Len> &lhs, const basic_any<Len> &rhs) ENTT_NOEXCEPT {
    return !(lhs == rhs);
}

/**
 * @brief Performs type-safe access to the contained object.
 * @tparam Len Size of the storage reserved for the small buffer optimization.
 * @tparam Type Type to which conversion is required.
 * @param data Target any object.
 * @return The element converted to the requested type.
 */
template<typename Type, std::size_t Len>
Type any_cast(const basic_any<Len> &data) ENTT_NOEXCEPT {
    const auto * const instance = any_cast<std::remove_reference_t<Type>>(&data);
    ENTT_ASSERT(instance);
    return static_cast<Type>(*instance);
}

/*! @copydoc any_cast */
template<typename Type, std::size_t Len>
Type any_cast(basic_any<Len> &data) ENTT_NOEXCEPT {
    // forces const on non-reference types to make them work also with wrappers for const references
    auto * const instance = any_cast<std::conditional_t<std::is_reference_v<Type>, std::remove_reference_t<Type>, const Type>>(&data);
    ENTT_ASSERT(instance);
    return static_cast<Type>(*instance);
}

/*! @copydoc any_cast */
template<typename Type, std::size_t Len>
Type any_cast(basic_any<Len> &&data) ENTT_NOEXCEPT {
    // forces const on non-reference types to make them work also with wrappers for const references
    auto * const instance = any_cast<std::conditional_t<std::is_reference_v<Type>, std::remove_reference_t<Type>, const Type>>(&data);
    ENTT_ASSERT(instance);
    return static_cast<Type>(std::move(*instance));
}

/*! @copydoc any_cast */
template<typename Type, std::size_t Len>
const Type * any_cast(const basic_any<Len> *data) ENTT_NOEXCEPT {
    return (data->type() == type_id<Type>() ? static_cast<const Type *>(data->data()) : nullptr);
}

/*! @copydoc any_cast */
template<typename Type, std::size_t Len>
Type * any_cast(basic_any<Len> *data) ENTT_NOEXCEPT {
    // last attempt to make wrappers for const references return their values
    return (data->type() == type_id<Type>() ? static_cast<Type *>(static_cast<constness_as_t<basic_any<Len>, Type> *>(data)->data()) : nullptr);
}

}

#endif
<|endoftext|>


<commit_before>/**
 * @file  main.cpp
 * @brief Two short examples in a row.
 *
 *  Demonstrate how-to use the SQLite++ wrapper
 *
 * Copyright (c) 2012 Sebastien Rombauts (sebastien dot rombauts at gmail dot com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include <iostream>

#include "../SQLiteC++/Database.h"
#include "../SQLiteC++/Statement.h"

/// Object Oriented Basic example
class Example
{
public:
    Example(void) :
        mDb("example.db3"),                                 // Open a database file
        mQuery(mDb, "SELECT * FROM test WHERE size > ?")    // Compile a SQL query, containing one parameter (index 1)
    {
    }
    virtual ~Example(void)
    {
    }

    // List the rows where the "size" column is greater than the provided aParamValue
    void ListGreaterThan (const int aParamValue)
    {
        std::cout << "ListGreaterThan (" << aParamValue << ")\n";

        // Bind the integer value provided to the first parameter of the SQL query
        mQuery.bind(1, aParamValue);

        // Loop to execute the query step by step, to get one a row of results at a time
        while (mQuery.executeStep())
        {
            std::cout << "row : (" << mQuery.getColumn(0) << ", " << mQuery.getColumn(1) << ", " << mQuery.getColumn(2) << ")\n";
        }

        // Reset the query to be able to use it again later
        mQuery.reset();
    }

private:
    SQLite::Database    mDb;
    SQLite::Statement   mQuery;
};

int main (void)
{
    // Basic example (1/2) :
    try
    {
        // Open a database file
        SQLite::Database    db("example.db3");
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        // Compile a SQL query, containing one parameter (index 1)
        SQLite::Statement   query(db, "SELECT * FROM test WHERE size > ?");
        std::cout << "SQLite statement '" << query.getQuery().c_str() << "' compiled (" << query.getColumnCount () << " columns in the result)\n";
        // Bind the integer value 6 to the first parameter of the SQL query
        query.bind(1, 6);

        // Loop to execute the query step by step, to get one a row of results at a time
        while (query.executeStep())
        {
            // Demonstrate how to get some typed column value
            int         id      = query.getColumn(0); // = query.getColumn(0).getInt()
          //const char* pvalue  = query.getColumn(1); // = query.getColumn(1).getText()
            std::string value   = query.getColumn(1); // = query.getColumn(1).getText()
            int         size    = query.getColumn(2); // = query.getColumn(2).getInt()

            std::cout << "row : (" << id << ", " << value << ", " << size << ")\n";
        }

        // Reset the query to use it again
        query.reset();
        std::cout << "SQLite statement '" << query.getQuery().c_str() << "' reseted (" << query.getColumnCount () << " columns in the result)\n";
        // Bind the string value "6" to the first parameter of the SQL query
        query.bind(1, "6");

        while (query.executeStep())
        {
            // Demonstrate that inserting column value in a std:ostream is natural
            std::cout << "row : (" << query.getColumn(0) << ", " << query.getColumn(1) << ", " << query.getColumn(2) << ")\n";
        }
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
    }

    ////////////////////////////////////////////////////////////////////////////
    // Object Oriented Basic example (2/2) :
    try
    {
        // Open the database and compile the query
        Example example;

        // Demonstrate the way to use the same query with different parameter values
        example.ListGreaterThan(8);
        example.ListGreaterThan(6);
        example.ListGreaterThan(2);
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
    }

    return 0;
}
<commit_msg>Corrected example for Windows<commit_after>/**
 * @file  main.cpp
 * @brief Two short examples in a row.
 *
 *  Demonstrate how-to use the SQLite++ wrapper
 *
 * Copyright (c) 2012 Sebastien Rombauts (sebastien dot rombauts at gmail dot com)
 *
 * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
 * or copy at http://opensource.org/licenses/MIT)
 */

#include <iostream>

#include "../SQLiteC++/Database.h"
#include "../SQLiteC++/Statement.h"

/// Object Oriented Basic example
class Example
{
public:
    Example(void) :
        mDb("example.db3"),                                 // Open a database file
        mQuery(mDb, "SELECT * FROM test WHERE size > ?")    // Compile a SQL query, containing one parameter (index 1)
    {
    }
    virtual ~Example(void)
    {
    }

    // List the rows where the "size" column is greater than the provided aParamValue
    void ListGreaterThan (const int aParamValue)
    {
        std::cout << "ListGreaterThan (" << aParamValue << ")\n";

        // Bind the integer value provided to the first parameter of the SQL query
        mQuery.bind(1, aParamValue);

        // Loop to execute the query step by step, to get one a row of results at a time
        while (mQuery.executeStep())
        {
            std::cout << "row : (" << mQuery.getColumn(0) << ", " << mQuery.getColumn(1) << ", " << mQuery.getColumn(2) << ")\n";
        }

        // Reset the query to be able to use it again later
        mQuery.reset();
    }

private:
    SQLite::Database    mDb;
    SQLite::Statement   mQuery;
};

int main (void)
{
    // Basic example (1/2) :
    try
    {
        // Open a database file
        SQLite::Database    db("example.db3");
        std::cout << "SQLite database file '" << db.getFilename().c_str() << "' opened successfully\n";

        // Compile a SQL query, containing one parameter (index 1)
        SQLite::Statement   query(db, "SELECT * FROM test WHERE size > ?");
        std::cout << "SQLite statement '" << query.getQuery().c_str() << "' compiled (" << query.getColumnCount () << " columns in the result)\n";
        // Bind the integer value 6 to the first parameter of the SQL query
        query.bind(1, 6);

        // Loop to execute the query step by step, to get one a row of results at a time
        while (query.executeStep())
        {
            // Demonstrate how to get some typed column value
            int         id      = query.getColumn(0); // = query.getColumn(0).getInt()
          //const char* pvalue  = query.getColumn(1); // = query.getColumn(1).getText()
            std::string value   = query.getColumn(1); // = query.getColumn(1).getText()
            int         size    = query.getColumn(2); // = query.getColumn(2).getInt()

            std::cout << "row : (" << id << ", " << value.c_str() << ", " << size << ")\n";
        }

        // Reset the query to use it again
        query.reset();
        std::cout << "SQLite statement '" << query.getQuery().c_str() << "' reseted (" << query.getColumnCount () << " columns in the result)\n";
        // Bind the string value "6" to the first parameter of the SQL query
        query.bind(1, "6");

        while (query.executeStep())
        {
            // Demonstrate that inserting column value in a std:ostream is natural
            std::cout << "row : (" << query.getColumn(0) << ", " << query.getColumn(1) << ", " << query.getColumn(2) << ")\n";
        }
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
    }

    ////////////////////////////////////////////////////////////////////////////
    // Object Oriented Basic example (2/2) :
    try
    {
        // Open the database and compile the query
        Example example;

        // Demonstrate the way to use the same query with different parameter values
        example.ListGreaterThan(8);
        example.ListGreaterThan(6);
        example.ListGreaterThan(2);
    }
    catch (std::exception& e)
    {
        std::cout << "SQLite exception: " << e.what() << std::endl;
    }

    return 0;
}
<|endoftext|>