<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/

#include <osgProducer/GraphicsContextImplementation>
#include <osg/TextureRectangle>
#include <osg/TextureCubeMap>
#include <osg/Notify>

using namespace osgProducer;

namespace osgProducer
{
    struct MyWindowingSystemInterface : public osg::GraphicsContext::WindowingSystemInterface
    {
        virtual unsigned int getNumScreens(const osg::GraphicsContext::ScreenIdentifier& /*screenIdentifier*/)
        {
            return Producer::RenderSurface::getNumberOfScreens();
        }

        virtual void getScreenResolution(const osg::GraphicsContext::ScreenIdentifier& screenIdentifier, unsigned int& width, unsigned int& height)
        {
            osg::ref_ptr<Producer::RenderSurface> rs = new Producer::RenderSurface;
            rs->setHostName(screenIdentifier.hostName);
            rs->setDisplayNum(screenIdentifier.displayNum);
            rs->setScreenNum(screenIdentifier.screenNum);
            rs->getScreenSize(width, height);
        }

        virtual osg::GraphicsContext* createGraphicsContext(osg::GraphicsContext::Traits* traits)
        {
            return new GraphicsContextImplementation(traits);
        }
    };

    struct RegisterWindowingSystemInterfaceProxy
    {
        RegisterWindowingSystemInterfaceProxy()
        {
            osg::GraphicsContext::setWindowingSystemInterface(new MyWindowingSystemInterface);
        }

        ~RegisterWindowingSystemInterfaceProxy()
        {
            osg::GraphicsContext::setWindowingSystemInterface(0);
        }
    };

    RegisterWindowingSystemInterfaceProxy createWindowingSystemInterfaceProxy;
};

GraphicsContextImplementation::GraphicsContextImplementation(Traits* traits)
{
    _traits = traits;

    _rs = new Producer::RenderSurface;
    _rs->setWindowName(traits->windowName);
    _rs->setWindowRectangle(traits->x, traits->y, traits->width, traits->height);
    _rs->useBorder(traits->windowDecoration);
    _rs->setDisplayNum(traits->displayNum);
    _rs->setScreenNum(traits->screenNum);

    // set the visual chooser
    Producer::VisualChooser* rs_vc = _rs->getVisualChooser();
    if (!rs_vc)
    {
        rs_vc = new Producer::VisualChooser;
        _rs->setVisualChooser(rs_vc);
    }

    rs_vc->setRedSize(_traits->red);
    rs_vc->setGreenSize(_traits->green);
    rs_vc->setBlueSize(_traits->blue);
    rs_vc->setAlphaSize(_traits->alpha);

    rs_vc->setDepthSize(_traits->depth);
    rs_vc->setStencilSize(_traits->stencil);

    if (_traits->doubleBuffer) rs_vc->useDoubleBuffer();

    rs_vc->addAttribute( Producer::VisualChooser::RGBA );

    // Always use UseGL
    rs_vc->addAttribute( Producer::VisualChooser::UseGL );

    if (traits->pbuffer)
    {
        _rs->setDrawableType(Producer::RenderSurface::DrawableType_PBuffer);

        if (traits->target)
        {

            _rs->setRenderToTextureOptions(traits->mipMapGeneration ? Producer::RenderSurface::RequestSpaceForMipMaps :
                                                                       Producer::RenderSurface::RenderToTextureOptions_Default);
            _rs->setRenderToTextureMipMapLevel(traits->level);
            _rs->setRenderToTextureMode(traits->alpha>0 ? Producer::RenderSurface::RenderToRGBATexture :
                                                           Producer::RenderSurface::RenderToRGBTexture);

            switch(traits->target)
            {
                case(GL_TEXTURE_1D) :
                    _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture1D);
                    break;
                case(GL_TEXTURE_2D) :
                    _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture2D);
                    break;
                case(GL_TEXTURE_3D) :
                    osg::notify(osg::NOTICE)<<"PBuffer render to Texture3D not supported."<<std::endl;
                    // not supported.
                    // _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture3D);
                    break;
                case(GL_TEXTURE_RECTANGLE) :
                    osg::notify(osg::NOTICE)<<"PBuffer render to TextureRectangle not supported."<<std::endl;
                    // not supported.
                    // _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureRectangle);
                    break;
                case(GL_TEXTURE_CUBE_MAP_POSITIVE_X) :
                case(GL_TEXTURE_CUBE_MAP_NEGATIVE_X) :
                case(GL_TEXTURE_CUBE_MAP_POSITIVE_Y) :
                case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) :
                case(GL_TEXTURE_CUBE_MAP_POSITIVE_Z) :
                case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) :
                    _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureCUBE);
                    _rs->setRenderToTextureFace( Producer::RenderSurface::CubeMapFace(traits->target - GL_TEXTURE_CUBE_MAP_POSITIVE_X));
                    break;
            }

        }

    }

    GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(traits->sharedContext);

    if (sharedContext)
    {
        // different graphics context so we have our own state.
        setState(new osg::State);

        if (sharedContext->getState())
        {
            getState()->setContextID( sharedContext->getState()->getContextID() );
            incrementContextIDUsageCount( sharedContext->getState()->getContextID() );
        }
        else
        {
            getState()->setContextID( osg::GraphicsContext::createNewContextID() );
        }

        // but we share texture objects etc. so we also share the same contextID
        //_rs->realize( 0, sharedContext->_rs->getGLContext() );

    }
    else
    {

        // need to do something here....
        setState( new osg::State );
        getState()->setContextID( osg::GraphicsContext::createNewContextID() );

        //_rs->realize();
    }

    // _rs->useConfigEventThread(false);

    _closeOnDestruction = true;
}

GraphicsContextImplementation::GraphicsContextImplementation(Producer::RenderSurface* rs)
{
    _rs = rs;
    _closeOnDestruction = false;

    _traits = new osg::GraphicsContext::Traits;
    _traits->windowName = _rs->getWindowName();
    _traits->displayNum = _rs->getDisplayNum();
    _traits->screenNum = _rs->getScreenNum();
}

GraphicsContextImplementation::~GraphicsContextImplementation()
{
    if (_closeOnDestruction) close();
}

bool GraphicsContextImplementation::realizeImplementation()
{
    if (_rs.valid())
    {
        GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(_traits->sharedContext);

        if (sharedContext)
        {
            _rs->realize( 0, sharedContext->_rs->getGLContext() );
        }
        else
        {
            osg::notify(osg::NOTICE)<<"GraphicsContextImplementation::realize"<<std::endl;

            _rs->realize();
        }
        return _rs->isRealized();
    }
    else
    {
        return false;
    }
}

bool GraphicsContextImplementation::makeCurrentImplementation()
{
    if (!_rs)
    {
        osg::notify(osg::NOTICE)<<"Error: GraphicsContextImplementation::makeCurrentImplementation() no RenderSurface."<<std::endl;
        return false;
    }

    if (!isRealized())
    {
        osg::notify(osg::NOTICE)<<"Error: GraphicsContextImplementation::makeCurrentImplementation() not Realized."<<std::endl;
        return false;
    }

//    osg::notify(osg::INFO)<<"GraphicsContextImplementation::makeCurrentImplementation()"<<std::endl;

    _rs->setReadDrawable( 0 );

    // comment out right now, as Producer's setReadDrawable() is doing a call for us.
    // _rs->makeCurrent();

    return true;
}

bool GraphicsContextImplementation::makeContextCurrentImplementation(osg::GraphicsContext* readContext)
{
    if (!_rs) return false;

    GraphicsContextImplementation* readContextImplemention = dynamic_cast<GraphicsContextImplementation*>(readContext);

    if (readContextImplemention)
    {
        _rs->setReadDrawable( readContextImplemention->getRenderSurface() );
    }
    else
    {
        _rs->setReadDrawable( 0 );
    }

    // comment out right now, as Producer's setReadDrawable() is doing a call for us.
    // _rs->makeCurrent();

    return true;
}

bool GraphicsContextImplementation::releaseContextImplementation()
{
    osg::notify(osg::NOTICE)<<"GraphicsContextImplementation::makeCurrentImplementation(): not implemented - release not supported under Producer."<<std::endl;
    return false;
}

void GraphicsContextImplementation::closeImplementation()
{
    if (!_rs) return;

    // close render surface by deleting it
    _rs = 0;
}

void GraphicsContextImplementation::bindPBufferToTextureImplementation(GLenum buffer)
{
    if (!_rs) return;

    Producer::RenderSurface::BufferType bufferType = Producer::RenderSurface::FrontBuffer;
    switch(buffer)
    {
        case(GL_BACK): bufferType = Producer::RenderSurface::BackBuffer; break;
        case(GL_FRONT): bufferType = Producer::RenderSurface::FrontBuffer; break;
        default: bufferType = Producer::RenderSurface::FrontBuffer; break;
    }

    _rs->bindPBufferToTexture(bufferType);
}

void GraphicsContextImplementation::swapBuffersImplementation()
{
    _rs->swapBuffers();
}
<commit_msg>Fixed comment<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * OpenSceneGraph Public License for more details.
*/

#include <osgProducer/GraphicsContextImplementation>
#include <osg/TextureRectangle>
#include <osg/TextureCubeMap>
#include <osg/Notify>

using namespace osgProducer;

namespace osgProducer
{
    struct MyWindowingSystemInterface : public osg::GraphicsContext::WindowingSystemInterface
    {
        virtual unsigned int getNumScreens(const osg::GraphicsContext::ScreenIdentifier& /*screenIdentifier*/)
        {
            return Producer::RenderSurface::getNumberOfScreens();
        }

        virtual void getScreenResolution(const osg::GraphicsContext::ScreenIdentifier& screenIdentifier, unsigned int& width, unsigned int& height)
        {
            osg::ref_ptr<Producer::RenderSurface> rs = new Producer::RenderSurface;
            rs->setHostName(screenIdentifier.hostName);
            rs->setDisplayNum(screenIdentifier.displayNum);
            rs->setScreenNum(screenIdentifier.screenNum);
            rs->getScreenSize(width, height);
        }

        virtual osg::GraphicsContext* createGraphicsContext(osg::GraphicsContext::Traits* traits)
        {
            return new GraphicsContextImplementation(traits);
        }
    };

    struct RegisterWindowingSystemInterfaceProxy
    {
        RegisterWindowingSystemInterfaceProxy()
        {
            osg::GraphicsContext::setWindowingSystemInterface(new MyWindowingSystemInterface);
        }

        ~RegisterWindowingSystemInterfaceProxy()
        {
            osg::GraphicsContext::setWindowingSystemInterface(0);
        }
    };

    RegisterWindowingSystemInterfaceProxy createWindowingSystemInterfaceProxy;
};

GraphicsContextImplementation::GraphicsContextImplementation(Traits* traits)
{
    _traits = traits;

    _rs = new Producer::RenderSurface;
    _rs->setWindowName(traits->windowName);
    _rs->setWindowRectangle(traits->x, traits->y, traits->width, traits->height);
    _rs->useBorder(traits->windowDecoration);
    _rs->setDisplayNum(traits->displayNum);
    _rs->setScreenNum(traits->screenNum);

    // set the visual chooser
    Producer::VisualChooser* rs_vc = _rs->getVisualChooser();
    if (!rs_vc)
    {
        rs_vc = new Producer::VisualChooser;
        _rs->setVisualChooser(rs_vc);
    }

    rs_vc->setRedSize(_traits->red);
    rs_vc->setGreenSize(_traits->green);
    rs_vc->setBlueSize(_traits->blue);
    rs_vc->setAlphaSize(_traits->alpha);

    rs_vc->setDepthSize(_traits->depth);
    rs_vc->setStencilSize(_traits->stencil);

    if (_traits->doubleBuffer) rs_vc->useDoubleBuffer();

    rs_vc->addAttribute( Producer::VisualChooser::RGBA );

    // Always use UseGL
    rs_vc->addAttribute( Producer::VisualChooser::UseGL );

    if (traits->pbuffer)
    {
        _rs->setDrawableType(Producer::RenderSurface::DrawableType_PBuffer);

        if (traits->target)
        {

            _rs->setRenderToTextureOptions(traits->mipMapGeneration ? Producer::RenderSurface::RequestSpaceForMipMaps :
                                                                       Producer::RenderSurface::RenderToTextureOptions_Default);
            _rs->setRenderToTextureMipMapLevel(traits->level);
            _rs->setRenderToTextureMode(traits->alpha>0 ? Producer::RenderSurface::RenderToRGBATexture :
                                                           Producer::RenderSurface::RenderToRGBTexture);

            switch(traits->target)
            {
                case(GL_TEXTURE_1D) :
                    _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture1D);
                    break;
                case(GL_TEXTURE_2D) :
                    _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture2D);
                    break;
                case(GL_TEXTURE_3D) :
                    osg::notify(osg::NOTICE)<<"PBuffer render to Texture3D not supported."<<std::endl;
                    // not supported.
                    // _rs->setRenderToTextureTarget(Producer::RenderSurface::Texture3D);
                    break;
                case(GL_TEXTURE_RECTANGLE) :
                    osg::notify(osg::NOTICE)<<"PBuffer render to TextureRectangle not supported."<<std::endl;
                    // not supported.
                    // _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureRectangle);
                    break;
                case(GL_TEXTURE_CUBE_MAP_POSITIVE_X) :
                case(GL_TEXTURE_CUBE_MAP_NEGATIVE_X) :
                case(GL_TEXTURE_CUBE_MAP_POSITIVE_Y) :
                case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Y) :
                case(GL_TEXTURE_CUBE_MAP_POSITIVE_Z) :
                case(GL_TEXTURE_CUBE_MAP_NEGATIVE_Z) :
                    _rs->setRenderToTextureTarget(Producer::RenderSurface::TextureCUBE);
                    _rs->setRenderToTextureFace( Producer::RenderSurface::CubeMapFace(traits->target - GL_TEXTURE_CUBE_MAP_POSITIVE_X));
                    break;
            }

        }

    }

    GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(traits->sharedContext);

    if (sharedContext)
    {
        // different graphics context so we have our own state.
        setState(new osg::State);

        if (sharedContext->getState())
        {
            getState()->setContextID( sharedContext->getState()->getContextID() );
            incrementContextIDUsageCount( sharedContext->getState()->getContextID() );
        }
        else
        {
            getState()->setContextID( osg::GraphicsContext::createNewContextID() );
        }

        // but we share texture objects etc. so we also share the same contextID
        //_rs->realize( 0, sharedContext->_rs->getGLContext() );

    }
    else
    {

        // need to do something here....
        setState( new osg::State );
        getState()->setContextID( osg::GraphicsContext::createNewContextID() );

        //_rs->realize();
    }

    // _rs->useConfigEventThread(false);

    _closeOnDestruction = true;
}

GraphicsContextImplementation::GraphicsContextImplementation(Producer::RenderSurface* rs)
{
    _rs = rs;
    _closeOnDestruction = false;

    _traits = new osg::GraphicsContext::Traits;
    _traits->windowName = _rs->getWindowName();
    _traits->displayNum = _rs->getDisplayNum();
    _traits->screenNum = _rs->getScreenNum();
}

GraphicsContextImplementation::~GraphicsContextImplementation()
{
    if (_closeOnDestruction) close();
}

bool GraphicsContextImplementation::realizeImplementation()
{
    if (_rs.valid())
    {
        GraphicsContextImplementation* sharedContext = dynamic_cast<GraphicsContextImplementation*>(_traits->sharedContext);

        if (sharedContext)
        {
            _rs->realize( 0, sharedContext->_rs->getGLContext() );
        }
        else
        {
            osg::notify(osg::NOTICE)<<"GraphicsContextImplementation::realize"<<std::endl;

            _rs->realize();
        }
        return _rs->isRealized();
    }
    else
    {
        return false;
    }
}

bool GraphicsContextImplementation::makeCurrentImplementation()
{
    if (!_rs)
    {
        osg::notify(osg::NOTICE)<<"Error: GraphicsContextImplementation::makeCurrentImplementation() no RenderSurface."<<std::endl;
        return false;
    }

    if (!isRealized())
    {
        osg::notify(osg::NOTICE)<<"Error: GraphicsContextImplementation::makeCurrentImplementation() not Realized."<<std::endl;
        return false;
    }

//    osg::notify(osg::INFO)<<"GraphicsContextImplementation::makeCurrentImplementation()"<<std::endl;

    _rs->setReadDrawable( 0 );

    // comment out right now, as Producer's setReadDrawable() is doing a call for us.
    // _rs->makeCurrent();

    return true;
}

bool GraphicsContextImplementation::makeContextCurrentImplementation(osg::GraphicsContext* readContext)
{
    if (!_rs) return false;

    GraphicsContextImplementation* readContextImplemention = dynamic_cast<GraphicsContextImplementation*>(readContext);

    if (readContextImplemention)
    {
        _rs->setReadDrawable( readContextImplemention->getRenderSurface() );
    }
    else
    {
        _rs->setReadDrawable( 0 );
    }

    // comment out right now, as Producer's setReadDrawable() is doing a call for us.
    // _rs->makeCurrent();

    return true;
}

bool GraphicsContextImplementation::releaseContextImplementation()
{
    osg::notify(osg::NOTICE)<<"GraphicsContextImplementation::releaseContextImplementation(): not implemented - release not supported under Producer."<<std::endl;
    return false;
}

void GraphicsContextImplementation::closeImplementation()
{
    if (!_rs) return;

    // close render surface by deleting it
    _rs = 0;
}

void GraphicsContextImplementation::bindPBufferToTextureImplementation(GLenum buffer)
{
    if (!_rs) return;

    Producer::RenderSurface::BufferType bufferType = Producer::RenderSurface::FrontBuffer;
    switch(buffer)
    {
        case(GL_BACK): bufferType = Producer::RenderSurface::BackBuffer; break;
        case(GL_FRONT): bufferType = Producer::RenderSurface::FrontBuffer; break;
        default: bufferType = Producer::RenderSurface::FrontBuffer; break;
    }

    _rs->bindPBufferToTexture(bufferType);
}

void GraphicsContextImplementation::swapBuffersImplementation()
{
    _rs->swapBuffers();
}
<|endoftext|>


<commit_before>#include <stdexcept>
#include <string>
#include <iostream>
#include <functional>
#include <chrono>
#include <GL/glew.h>
#include <SDL.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <window.h>
#include <input.h>
#include <glbuffer.h>
#include <glvertexarray.h>
#include <glshader.h>
#include <glprogram.h>
#include <gltexture.h>
#include <model.h>
#include <util.h>

//This function demos working usage of ubo for matrices
int uboWorking();

//Note that we build with console as the system so that we'll be able to see
//the debug output and have the window stay open after closing the program
int main(int argc, char** argv){
	return uboWorking();
}

const std::array<glm::vec4, 10> quad = {
	//Vertex positions
	glm::vec4(-1.0, -1.0, 0.0, 1.0),
	glm::vec4(1.0, -1.0, 0.0, 1.0),
	glm::vec4(-1.0, 1.0, 0.0, 1.0),
	glm::vec4(1.0, 1.0, 0.0, 1.0),
	//Vertex colors
	glm::vec4(1.0, 0.0, 0.0, 1.0),
	glm::vec4(0.0, 1.0, 0.0, 1.0),
	glm::vec4(0.0, 0.0, 1.0, 1.0),
	glm::vec4(1.0, 1.0, 0.0, 1.0),
	//Texture UVs, stored 2 to a vec4
	glm::vec4(0.0, 0.0, 1.0, 0.0),
	glm::vec4(0.0, 2.0, 1.0, 2.0),
};
const std::array<unsigned short, 6> quadElems = {
	0, 1, 2,
	1, 3, 2
};

int uboWorking(){
	try {
		Window::init();
	}
	catch (const std::runtime_error &e){
		std::cout << e.what() << std::endl;
	}
	Input::Init();
	Window window("Test", 640, 480);

	//Setup vbo & ebo
	GL::VertexBuffer vbo(quad, GL::USAGE::STATIC_DRAW);
	GL::ElementBuffer ebo(quadElems, GL::USAGE::STATIC_DRAW);

	Util::checkError("VBO & EBO Setup");

	GL::VertexArray vao;
	vao.elementBuffer(ebo);
	Util::checkError("VAO setup");

	//Setup program
	GL::VertexShader vShader("../res/basic.v.glsl");
	if (!vShader.status())
		std::cout << vShader.getLog() << std::endl;
	Util::checkError("Vert shader Setup");

	GL::FragmentShader fShader("../res/multitexture.f.glsl");
	if (!fShader.status())
		std::cout << fShader.getLog() << std::endl;
	Util::checkError("Frag shader Setup");

	GL::Program program(vShader, fShader);
	Util::checkError("Prog Setup");

	//Pass vertex pos into position attrib
	GLint posAttrib = program.getAttribute("position");
	if (posAttrib == -1)
		std::cout << "Invalid position attrib loc" << std::endl;

	GLint colAttrib = program.getAttribute("color");
	if (colAttrib == -1)
		std::cout << "Invalid color attrib loc" << std::endl;

	GLint uvAttrib = program.getAttribute("texUv");
	if (uvAttrib == -1)
		std::cout << "Invalid uv attrib loc" << std::endl;

	vao.setAttribPointer(vbo, posAttrib, 4, GL_FLOAT);
	vao.setAttribPointer(vbo, colAttrib, 4, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(glm::vec4) * 4));
	vao.setAttribPointer(vbo, uvAttrib, 2, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(glm::vec4) * 8));
	Util::checkError("Pos attrib Setup");

	//Set the projection and model matrices
	glm::mat4 proj = glm::perspective(60.0f, 640.f / 480.f, 0.1f, 100.0f);
	glm::mat4 model = glm::translate<float>(0, 0, -2.5) * glm::rotate<float>(45, glm::vec3(0, 0, 1));
	std::array<glm::mat4, 2> matrices = { proj, model };

	GL::UniformBuffer ubo(matrices, GL::USAGE::STATIC_DRAW);
	program.bindUniformBlock("Mat", ubo);
	Util::checkError("Proj buf Setup");

	//Creating the texture binds it to TEXTURE_2D so no need to bind again
	GL::Texture<GL::TEXTURE::T2D> texture("../res/map.png", true);
	GL::Texture<GL::TEXTURE::T2D> textureB("../res/strip.png", true);

	GL::Sampler sampler;
	sampler.parameteri(GL_TEXTURE_WRAP_S, GL_REPEAT);
	sampler.parameteri(GL_TEXTURE_WRAP_T, GL_CLAMP);
	sampler.parameteri(GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
	sampler.parameteri(GL_TEXTURE_MAG_FILTER, GL_LINEAR);

	texture.bind(GL_TEXTURE0, sampler);
	textureB.bind(GL_TEXTURE1);
	program.uniform1i("texA", 0);
	program.uniform1i("texB", 1);

	program.use();
	while (!Input::Quit()){
		Input::PollEvents();
		if (Input::KeyDown(SDL_SCANCODE_ESCAPE))
			Input::Quit(true);

		window.clear();

		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);

		window.present();
	}
	Window::quit();

	return 0;
}
<commit_msg>Now drawing two items in the scene, a cube and plane so that I can look into shadowing and lighting effects since I've reached Ch.7 light and shadow in the OpenGL Programming Guide<commit_after>#include <stdexcept>
#include <string>
#include <iostream>
#include <functional>
#include <chrono>
#include <GL/glew.h>
#include <SDL.h>
#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <window.h>
#include <input.h>
#include <glbuffer.h>
#include <glvertexarray.h>
#include <glshader.h>
#include <glprogram.h>
#include <gltexture.h>
#include <model.h>
#include <util.h>

//This function demos working usage of ubo for matrices
int uboWorking();

//Note that we build with console as the system so that we'll be able to see
//the debug output and have the window stay open after closing the program
int main(int argc, char** argv){
	return uboWorking();
}

const std::array<glm::vec4, 10> quad = {
	//Vertex positions
	glm::vec4(-1.0, -1.0, 0.0, 1.0),
	glm::vec4(1.0, -1.0, 0.0, 1.0),
	glm::vec4(-1.0, 1.0, 0.0, 1.0),
	glm::vec4(1.0, 1.0, 0.0, 1.0),
	//Vertex colors
	glm::vec4(1.0, 0.0, 0.0, 1.0),
	glm::vec4(0.0, 1.0, 0.0, 1.0),
	glm::vec4(0.0, 0.0, 1.0, 1.0),
	glm::vec4(1.0, 1.0, 0.0, 1.0),
	//Texture UVs, stored 2 to a vec4
	glm::vec4(0.0, 0.0, 1.0, 0.0),
	glm::vec4(0.0, 1.0, 1.0, 1.0),
};
const std::array<unsigned short, 6> quadElems = {
	0, 1, 2,
	1, 3, 2
};

int uboWorking(){
	try {
		Window::init();
	}
	catch (const std::runtime_error &e){
		std::cout << e.what() << std::endl;
	}
	Input::Init();
	Window window("Test", 640, 480);

	//Setup vbo & ebo
	GL::VertexBuffer vbo(quad, GL::USAGE::STATIC_DRAW);
	GL::ElementBuffer ebo(quadElems, GL::USAGE::STATIC_DRAW);

	Util::checkError("VBO & EBO Setup");

	GL::VertexArray vao;
	vao.elementBuffer(ebo);
	Util::checkError("VAO setup");

	//Setup program
	GL::VertexShader vShader("../res/basic.v.glsl");
	if (!vShader.status())
		std::cout << vShader.getLog() << std::endl;
	Util::checkError("Vert shader Setup");

	GL::FragmentShader fShader("../res/basic.f.glsl");
	if (!fShader.status())
		std::cout << fShader.getLog() << std::endl;
	Util::checkError("Frag shader Setup");

	GL::Program program(vShader, fShader);
	Util::checkError("Prog Setup");

	//Pass vertex pos into position attrib
	GLint posAttrib = program.getAttribute("position");
	if (posAttrib == -1)
		std::cout << "Invalid position attrib loc" << std::endl;

	GLint colAttrib = program.getAttribute("color");
	if (colAttrib == -1)
		std::cout << "Invalid color attrib loc" << std::endl;

	GLint uvAttrib = program.getAttribute("texUv");
	if (uvAttrib == -1)
		std::cout << "Invalid uv attrib loc" << std::endl;

	vao.setAttribPointer(vbo, posAttrib, 4, GL_FLOAT);
	vao.setAttribPointer(vbo, colAttrib, 4, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(glm::vec4) * 4));
	vao.setAttribPointer(vbo, uvAttrib, 2, GL_FLOAT, GL_FALSE, 0, (void*)(sizeof(glm::vec4) * 8));
	Util::checkError("Pos attrib Setup");

	//Set the projection and model matrices
	glm::mat4 proj = glm::perspective(60.0f, 640.f / 480.f, 0.1f, 100.0f)
		* glm::lookAt(glm::vec3(0.f, 1.f, 2.f), glm::vec3(0.f, -1.f, -1.f), glm::vec3(0.f, 1.f, 0.f));
	glm::mat4 model = glm::translate(0.f, -1.f, 0.f) * glm::rotate(-90.f, glm::vec3(1.f, 0.f, 0.f));
	std::array<glm::mat4, 2> matrices = { proj, model };

	GL::UniformBuffer ubo(matrices, GL::USAGE::STATIC_DRAW);
	program.bindUniformBlock("Mat", ubo);
	Util::checkError("quad buf setup");

	//Creating the texture binds it to TEXTURE_2D so no need to bind again
	GL::Texture<GL::TEXTURE::T2D> texture("../res/map.png");
	texture.bind(GL_TEXTURE0);
	program.uniform1i("tex2D", 0);

	//Setup a simple cube model to draw
	GL::VertexArray cubeVAO;
	GL::VertexBuffer cubeVBO;
	Model::loadObj("../res/cube.obj", cubeVAO, cubeVBO);

	GL::Program cubeProg("../res/cube_simple.v.glsl", "../res/cube_simple.f.glsl");
	cubeVAO.setAttribPointer(cubeVBO, cubeProg.getAttribute("position"), 3, GL_FLOAT, GL_FALSE, 3 * sizeof(glm::vec3));

	std::array<glm::mat4, 2> cubeMats = { proj,
		glm::translate(0.f, -0.5f, 0.f) * glm::rotate(45.f, glm::vec3(0.f, 1.f, 0.f)) * glm::scale(0.3f, 0.3f, 0.3f)
	};
	GL::UniformBuffer cubeUBO(cubeMats, GL::USAGE::STATIC_DRAW);
	window.logMessage("SETTING CUBE UBO");
	cubeProg.bindUniformBlock("Mat", cubeUBO);

	//Testing an idea
	GLuint quadMatBind = program.getUniformBlockIndex("Mat");
	GLuint cubeMatBind = cubeProg.getUniformBlockIndex("Mat");

	//It seems that uniform block indices are a global thing, similar to how TEXTURE0 and such work
	glUniformBlockBinding(program, quadMatBind, 0);
	glBindBufferBase(static_cast<GLenum>(GL::BUFFER::UNIFORM), 0, ubo);
	glUniformBlockBinding(cubeProg, cubeMatBind, 1);
	glBindBufferBase(static_cast<GLenum>(GL::BUFFER::UNIFORM), 1, cubeUBO);

	std::cout << "cube ubo #: " << static_cast<GLuint>(cubeUBO)
		<< " cube ubo idx: " << cubeProg.getUniformBlockIndex("Mat") << "\n"
		<< "quad ubo #: " << static_cast<GLenum>(ubo)
		<< " quad ubo idx: " << program.getUniformBlockIndex("Mat") << std::endl;

	Util::checkError("cube setup");

	while (!Input::Quit()){
		Input::PollEvents();
		if (Input::KeyDown(SDL_SCANCODE_ESCAPE))
			Input::Quit(true);

		window.clear();

		program.use();
		glBindVertexArray(vao);
		glDrawElements(GL_TRIANGLES, 6, GL_UNSIGNED_SHORT, 0);

		cubeProg.use();
		glBindVertexArray(cubeVAO);
		glDrawElements(GL_TRIANGLES, cubeVAO.numElements(), GL_UNSIGNED_SHORT, 0);

		window.present();
	}
	Window::quit();

	return 0;
}
<|endoftext|>


<commit_before>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "bytearrayinputstream.h"

namespace Debugger {
namespace Internal {

ByteArrayInputStream::ByteArrayInputStream(QByteArray &ba) :
    m_target(ba), m_integerBase(10), m_hexPrefix(false), m_width(0)
{
}

void ByteArrayInputStream::appendSeparator(char c)
{
    if (!m_target.isEmpty() && !m_target.endsWith(c))
        m_target.append(c);
}

void hexPrefixOn(ByteArrayInputStream &bs)
{
    bs.setHexPrefix(true);
}

void hexPrefixOff(ByteArrayInputStream &bs)
{
    bs.setHexPrefix(false);
}

void hex(ByteArrayInputStream &bs)
{
    bs.setIntegerBase(16);
}

void dec(ByteArrayInputStream &bs)
{
    bs.setIntegerBase(10);
}

void blankSeparator(ByteArrayInputStream &bs)
{
    bs.appendSeparator();
}

QByteArray trimFront(QByteArray in)
{
    if (in.isEmpty())
        return in;
    const int size = in.size();
    int pos = 0;
    for ( ; pos < size && isspace(in.at(pos)); pos++) ;
    if (pos)
        in.remove(0, pos);
    return in;
}

QByteArray trimBack(QByteArray in)
{
    if (in.isEmpty())
        return in;
    const int size = in.size();
    int pos = size - 1;
    for ( ; pos >= 0 && isspace(in.at(pos)); pos--) ;
    if (pos != size - 1)
        in.truncate(pos + 1);
    return in;
}

// Simplify: replace tabs, find all occurrences
// of 2 blanks, check further up for blanks and remove that bit.
QByteArray simplify(const QByteArray &inIn)
{
    if (inIn.isEmpty())
        return inIn;
    QByteArray in = trimFront(trimBack(inIn));
    in.replace('\t', ' ');
    in.replace('\n', ' ');
    in.replace('\r', ' ');
    const QByteArray twoBlanks = "  ";
    while (true) {
        const int pos = in.indexOf(twoBlanks);
        if (pos != -1) {
            const int size = in.size();
            int endPos = pos + twoBlanks.size();
            for ( ; endPos < size && in.at(endPos) == ' '; endPos++) ;
            in.remove(pos + 1, endPos - pos - 1);
        } else {
            break;
        }
    }
    return in;
}

} // namespace Internal
} // namespace Debugger
<commit_msg>debugger:compile fix for -no-stl'ed Qt<commit_after>/**************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2011 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** No Commercial Usage
**
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
**
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**************************************************************************/

#include "bytearrayinputstream.h"

#include <ctype.h>

namespace Debugger {
namespace Internal {

ByteArrayInputStream::ByteArrayInputStream(QByteArray &ba) :
    m_target(ba), m_integerBase(10), m_hexPrefix(false), m_width(0)
{
}

void ByteArrayInputStream::appendSeparator(char c)
{
    if (!m_target.isEmpty() && !m_target.endsWith(c))
        m_target.append(c);
}

void hexPrefixOn(ByteArrayInputStream &bs)
{
    bs.setHexPrefix(true);
}

void hexPrefixOff(ByteArrayInputStream &bs)
{
    bs.setHexPrefix(false);
}

void hex(ByteArrayInputStream &bs)
{
    bs.setIntegerBase(16);
}

void dec(ByteArrayInputStream &bs)
{
    bs.setIntegerBase(10);
}

void blankSeparator(ByteArrayInputStream &bs)
{
    bs.appendSeparator();
}

QByteArray trimFront(QByteArray in)
{
    if (in.isEmpty())
        return in;
    const int size = in.size();
    int pos = 0;
    for ( ; pos < size && isspace(in.at(pos)); pos++) ;
    if (pos)
        in.remove(0, pos);
    return in;
}

QByteArray trimBack(QByteArray in)
{
    if (in.isEmpty())
        return in;
    const int size = in.size();
    int pos = size - 1;
    for ( ; pos >= 0 && isspace(in.at(pos)); pos--) ;
    if (pos != size - 1)
        in.truncate(pos + 1);
    return in;
}

// Simplify: replace tabs, find all occurrences
// of 2 blanks, check further up for blanks and remove that bit.
QByteArray simplify(const QByteArray &inIn)
{
    if (inIn.isEmpty())
        return inIn;
    QByteArray in = trimFront(trimBack(inIn));
    in.replace('\t', ' ');
    in.replace('\n', ' ');
    in.replace('\r', ' ');
    const QByteArray twoBlanks = "  ";
    while (true) {
        const int pos = in.indexOf(twoBlanks);
        if (pos != -1) {
            const int size = in.size();
            int endPos = pos + twoBlanks.size();
            for ( ; endPos < size && in.at(endPos) == ' '; endPos++) ;
            in.remove(pos + 1, endPos - pos - 1);
        } else {
            break;
        }
    }
    return in;
}

} // namespace Internal
} // namespace Debugger
<|endoftext|>


<commit_before><commit_msg>deleted temporary file<commit_after><|endoftext|>


<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <string>

#include "Options.hpp"
#include "Compiler.hpp"
#include "Utils.hpp"
#include "Platform.hpp"

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE EddicTestSuites
#include <boost/test/unit_test.hpp>

#define TEST_SAMPLE(file)\
BOOST_AUTO_TEST_CASE( samples_##file ){\
    assertCompiles("samples/" #file ".eddi", "--32");\
    assertCompiles("samples/" #file ".eddi", "--64");\
}

#define ASSERT_OUTPUT(file, output)\
    assertOutputEquals(file, output, "--32");\
    assertOutputEquals(file, output, "--64");

#include <iostream>

void assertCompiles(const std::string& file, const std::string& param){
    const char* options[3] = {"./bin/test", param.c_str(), file.c_str()};
    eddic::parseOptions(3, options);

    eddic::Compiler compiler;

    eddic::Platform platform = eddic::Platform::INTEL_X86;
    int code = compiler.compileOnly(file, platform);

    BOOST_CHECK_EQUAL (code, 0);
}

void assertOutputEquals(const std::string& file, const std::string& output, const std::string& param){
    assertCompiles("test/cases/" + file, param);

    std::string out = eddic::execCommand("./a.out");

    BOOST_CHECK_EQUAL (output, out);
}

/* Compiles all the samples */

BOOST_AUTO_TEST_SUITE(SamplesSuite)

TEST_SAMPLE(arrays)
TEST_SAMPLE(asm)
TEST_SAMPLE(assembly)
TEST_SAMPLE(bool)
TEST_SAMPLE(compound)
TEST_SAMPLE(concat)
TEST_SAMPLE(const)
TEST_SAMPLE(functions)
TEST_SAMPLE(float)
TEST_SAMPLE(casts)
TEST_SAMPLE(inc)
TEST_SAMPLE(includes)
TEST_SAMPLE(optimize)
TEST_SAMPLE(problem)
TEST_SAMPLE(sort)
TEST_SAMPLE(identifiers)
TEST_SAMPLE(structures)

BOOST_AUTO_TEST_SUITE_END()

/* Specific tests */

BOOST_AUTO_TEST_SUITE(SpecificSuite)

BOOST_AUTO_TEST_CASE( if_ ){
    ASSERT_OUTPUT("if.eddi", "Cool");
}

BOOST_AUTO_TEST_CASE( while_ ){
    ASSERT_OUTPUT("while.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( do_while_ ){
    ASSERT_OUTPUT("do_while.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( for_ ){
    ASSERT_OUTPUT("for.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( foreach_ ){
    ASSERT_OUTPUT("foreach.eddi", "012345");
}

BOOST_AUTO_TEST_CASE( globals_ ){
    assertOutputEquals("globals.eddi", "1000a2000aa", "-32");
    assertOutputEquals("globals.eddi", "1000a2000aa", "-64");
}

BOOST_AUTO_TEST_CASE( void_functions ){
    assertOutputEquals("void.eddi", "4445", "-32");
    assertOutputEquals("void.eddi", "4445", "-64");
}

BOOST_AUTO_TEST_CASE( string_functions ){
    assertOutputEquals("return_string.eddi", "abcdef", "-32");
    assertOutputEquals("return_string.eddi", "abcdef", "-64");
}

BOOST_AUTO_TEST_CASE( int_functions ){
    assertOutputEquals("return_int.eddi", "484", "-32");
    assertOutputEquals("return_int.eddi", "484", "-64");
}

BOOST_AUTO_TEST_CASE( recursive_functions ){
    assertOutputEquals("recursive.eddi", "362880", "-32");
    assertOutputEquals("recursive.eddi", "362880", "-64");
}

BOOST_AUTO_TEST_CASE( math ){
    assertOutputEquals("math.eddi", "333|111|-111|0|24642|2|-2|-1|1|2|0|-111|", "-32");
    assertOutputEquals("math.eddi", "333|111|-111|0|24642|2|-2|-1|1|2|0|-111|", "-64");
}

BOOST_AUTO_TEST_CASE( builtin ){
    assertOutputEquals("builtin.eddi", "10|11|12|13|12|13|10|11|4|8|13|8|0|3|", "-32");
    assertOutputEquals("builtin.eddi", "10|11|12|13|12|13|10|11|4|8|13|8|0|3|", "-64");
}

BOOST_AUTO_TEST_CASE( assign_value ){
    assertOutputEquals("assign_value.eddi", "66779921", "-32");
    assertOutputEquals("assign_value.eddi", "66779921", "-64");
}

BOOST_AUTO_TEST_CASE( args ){
    assertCompiles("test/cases/args.eddi", "-32");

    std::string out = eddic::execCommand("./a.out");
    BOOST_CHECK_EQUAL ("./a.out|", out);

    out = eddic::execCommand("./a.out arg1 arg2 arg3");
    BOOST_CHECK_EQUAL ("./a.out|arg1|arg2|arg3|", out);

    assertCompiles("test/cases/args.eddi", "-64");

    out = eddic::execCommand("./a.out");
    BOOST_CHECK_EQUAL ("./a.out|", out);

    out = eddic::execCommand("./a.out arg1 arg2 arg3");
    BOOST_CHECK_EQUAL ("./a.out|arg1|arg2|arg3|", out);
}

BOOST_AUTO_TEST_SUITE_END()

/* Unit test for bug fixes regression */

BOOST_AUTO_TEST_SUITE(BugFixesSuite)

BOOST_AUTO_TEST_CASE( while_bug ){
    assertOutputEquals("while_bug.eddi", "W1W2W3W4W5", "-32");
    assertOutputEquals("while_bug.eddi", "W1W2W3W4W5", "-64");
}

BOOST_AUTO_TEST_SUITE_END()
<commit_msg>USE REQUIRE instead of CHECK for the tests that the compilation has been successfull to block from executing wrong file<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
//  http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================

#include <string>

#include "Options.hpp"
#include "Compiler.hpp"
#include "Utils.hpp"
#include "Platform.hpp"

#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE EddicTestSuites
#include <boost/test/unit_test.hpp>

#define TEST_SAMPLE(file)\
BOOST_AUTO_TEST_CASE( samples_##file ){\
    assertCompiles("samples/" #file ".eddi", "--32");\
    assertCompiles("samples/" #file ".eddi", "--64");\
}

#define ASSERT_OUTPUT(file, output)\
    assertOutputEquals(file, output, "--32");\
    assertOutputEquals(file, output, "--64");

#include <iostream>

void assertCompiles(const std::string& file, const std::string& param){
    const char* options[3] = {"./bin/test", param.c_str(), file.c_str()};
    BOOST_REQUIRE (eddic::parseOptions(3, options));

    eddic::Compiler compiler;

    eddic::Platform platform = eddic::Platform::INTEL_X86;
    int code = compiler.compileOnly(file, platform);

    BOOST_REQUIRE_EQUAL (code, 0);
}

void assertOutputEquals(const std::string& file, const std::string& output, const std::string& param){
    assertCompiles("test/cases/" + file, param);

    std::string out = eddic::execCommand("./a.out");

    BOOST_CHECK_EQUAL (output, out);
}

/* Compiles all the samples */

BOOST_AUTO_TEST_SUITE(SamplesSuite)

TEST_SAMPLE(arrays)
TEST_SAMPLE(asm)
TEST_SAMPLE(assembly)
TEST_SAMPLE(bool)
TEST_SAMPLE(compound)
TEST_SAMPLE(concat)
TEST_SAMPLE(const)
TEST_SAMPLE(functions)
TEST_SAMPLE(float)
TEST_SAMPLE(casts)
TEST_SAMPLE(inc)
TEST_SAMPLE(includes)
TEST_SAMPLE(optimize)
TEST_SAMPLE(problem)
TEST_SAMPLE(sort)
TEST_SAMPLE(identifiers)
TEST_SAMPLE(structures)

BOOST_AUTO_TEST_SUITE_END()

/* Specific tests */

BOOST_AUTO_TEST_SUITE(SpecificSuite)

BOOST_AUTO_TEST_CASE( if_ ){
    ASSERT_OUTPUT("if.eddi", "Cool");
}

BOOST_AUTO_TEST_CASE( while_ ){
    ASSERT_OUTPUT("while.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( do_while_ ){
    ASSERT_OUTPUT("do_while.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( for_ ){
    ASSERT_OUTPUT("for.eddi", "01234");
}

BOOST_AUTO_TEST_CASE( foreach_ ){
    ASSERT_OUTPUT("foreach.eddi", "012345");
}

BOOST_AUTO_TEST_CASE( globals_ ){
    assertOutputEquals("globals.eddi", "1000a2000aa", "-32");
    assertOutputEquals("globals.eddi", "1000a2000aa", "-64");
}

BOOST_AUTO_TEST_CASE( void_functions ){
    assertOutputEquals("void.eddi", "4445", "-32");
    assertOutputEquals("void.eddi", "4445", "-64");
}

BOOST_AUTO_TEST_CASE( string_functions ){
    assertOutputEquals("return_string.eddi", "abcdef", "-32");
    assertOutputEquals("return_string.eddi", "abcdef", "-64");
}

BOOST_AUTO_TEST_CASE( int_functions ){
    assertOutputEquals("return_int.eddi", "484", "-32");
    assertOutputEquals("return_int.eddi", "484", "-64");
}

BOOST_AUTO_TEST_CASE( recursive_functions ){
    assertOutputEquals("recursive.eddi", "362880", "-32");
    assertOutputEquals("recursive.eddi", "362880", "-64");
}

BOOST_AUTO_TEST_CASE( math ){
    assertOutputEquals("math.eddi", "333|111|-111|0|24642|2|-2|-1|1|2|0|-111|", "-32");
    assertOutputEquals("math.eddi", "333|111|-111|0|24642|2|-2|-1|1|2|0|-111|", "-64");
}

BOOST_AUTO_TEST_CASE( builtin ){
    assertOutputEquals("builtin.eddi", "10|11|12|13|12|13|10|11|4|8|13|8|0|3|", "-32");
    assertOutputEquals("builtin.eddi", "10|11|12|13|12|13|10|11|4|8|13|8|0|3|", "-64");
}

BOOST_AUTO_TEST_CASE( assign_value ){
    assertOutputEquals("assign_value.eddi", "66779921", "-32");
    assertOutputEquals("assign_value.eddi", "66779921", "-64");
}

BOOST_AUTO_TEST_CASE( args ){
    assertCompiles("test/cases/args.eddi", "-32");

    std::string out = eddic::execCommand("./a.out");
    BOOST_CHECK_EQUAL ("./a.out|", out);

    out = eddic::execCommand("./a.out arg1 arg2 arg3");
    BOOST_CHECK_EQUAL ("./a.out|arg1|arg2|arg3|", out);

    assertCompiles("test/cases/args.eddi", "-64");

    out = eddic::execCommand("./a.out");
    BOOST_CHECK_EQUAL ("./a.out|", out);

    out = eddic::execCommand("./a.out arg1 arg2 arg3");
    BOOST_CHECK_EQUAL ("./a.out|arg1|arg2|arg3|", out);
}

BOOST_AUTO_TEST_SUITE_END()

/* Unit test for bug fixes regression */

BOOST_AUTO_TEST_SUITE(BugFixesSuite)

BOOST_AUTO_TEST_CASE( while_bug ){
    assertOutputEquals("while_bug.eddi", "W1W2W3W4W5", "-32");
    assertOutputEquals("while_bug.eddi", "W1W2W3W4W5", "-64");
}

BOOST_AUTO_TEST_SUITE_END()
<|endoftext|>


<commit_before>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2015
Raffaello D. Di Napoli

This file is part of Abaclade.

Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.

You should have received a copy of the GNU General Public License along with Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abaclade.hxx>
#include <abaclade/app.hxx>
#include <abaclade/coroutine.hxx>
#include <abaclade/range.hxx>

using namespace abc;

////////////////////////////////////////////////////////////////////////////////////////////////////
// coroutines_app

class coroutines_app : public app {
public:
   /*! Main function of the program.

   @param vsArgs
      Arguments that were provided to this program via command line.
   @return
      Return value of this program.
   */
   virtual int main(collections::mvector<istr const> const & vsArgs) override {
      ABC_TRACE_FUNC(this, vsArgs);

      auto & pcorosched = this_thread::attach_coroutine_scheduler();

      // Open a pipe in asynchronous I/O mode.
      auto pair(io::binary::pipe(true));

      // Schedule the reader.
      pcorosched->add(coroutine([this, &pair] () -> void {
         ABC_TRACE_FUNC(this/*, pair*/);

         io::text::stdout()->write_line(ABC_SL("reader: starting"));
         for (;;) {
            int i;
            io::text::stdout()->print(ABC_SL("reader: reading\n"));
            // This will cause a context switch if the read would block.
            std::size_t cbRead = pair.first->read(&i, sizeof i);
            // Execution resumes here, after other coroutines have received CPU time.
            io::text::stdout()->print(ABC_SL("reader: read {}\n"), i);
            if (!cbRead) {
               // Detect EOF.
               break;
            }
            // Consume i.
         }
         io::text::stdout()->write_line(ABC_SL("reader: terminating"));
      }));

      // Schedule the writer.
      pcorosched->add(coroutine([this, &pair] () -> void {
         ABC_TRACE_FUNC(this/*, pair*/);

         io::text::stdout()->write_line(ABC_SL("writer: starting"));
         ABC_FOR_EACH(int i, make_range(1, 10)) {
            io::text::stdout()->print(ABC_SL("writer: writing {}\n"), i);
            // This will cause a context switch if the write would block.
            pair.second->write(&i, sizeof i);
            // Execution resumes here, after other coroutines have received CPU time.

            /* Halt this coroutine for a few milliseconds. This will give the reader a chance to be
            scheduled, as well as create a more realistic non-continuous data flow into the pipe. */
            io::text::stdout()->write_line(ABC_SL("writer: yielding"));
            this_thread::coroutine_scheduler()->yield_for(50);
            // Execution resumes here, after other coroutines have received CPU time.
         }
         // Close the writing end of the pipe to report EOF on the reading end.
         pair.second.reset();
         io::text::stdout()->write_line(ABC_SL("writer: terminating"));
      }));

      // Switch this thread to run coroutines, until they all terminate.
      pcorosched->run();
      // Execution resumes here, after all coroutines have terminated.
      io::text::stdout()->write_line(ABC_SL("main: terminating"));
      return 0;
   }
};

ABC_APP_CLASS(coroutines_app)
<commit_msg>Make coroutines example fancier<commit_after>/* -*- coding: utf-8; mode: c++; tab-width: 3; indent-tabs-mode: nil -*-

Copyright 2015
Raffaello D. Di Napoli

This file is part of Abaclade.

Abaclade is free software: you can redistribute it and/or modify it under the terms of the GNU
General Public License as published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.

Abaclade is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
Public License for more details.

You should have received a copy of the GNU General Public License along with Abaclade. If not, see
<http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------------------*/

#include <abaclade.hxx>
#include <abaclade/app.hxx>
#include <abaclade/coroutine.hxx>
#include <abaclade/range.hxx>

using namespace abc;

////////////////////////////////////////////////////////////////////////////////////////////////////
// coroutines_app

class coroutines_app : public app {
public:
   /*! Main function of the program.

   @param vsArgs
      Arguments that were provided to this program via command line.
   @return
      Return value of this program.
   */
   virtual int main(collections::mvector<istr const> const & vsArgs) override {
      ABC_TRACE_FUNC(this, vsArgs);

      auto & pcorosched = this_thread::attach_coroutine_scheduler();

      // Open a pipe in asynchronous I/O mode.
      auto pair(io::binary::pipe(true));

      // Schedule the reader.
      pcorosched->add(coroutine([this, &pair] () -> void {
         ABC_TRACE_FUNC(this/*, pair*/);

         io::text::stdout()->write_line(ABC_SL("reader: starting"));
         for (;;) {
            int i;
            io::text::stdout()->print(ABC_SL("reader: reading\n"));
            // This will cause a context switch if the read would block.
            std::size_t cbRead = pair.first->read(&i, sizeof i);
            // Execution resumes here, after other coroutines have received CPU time.
            io::text::stdout()->print(ABC_SL("reader: read {}\n"), i);
            if (!cbRead) {
               // Detect EOF.
               break;
            }

            // Consume i.
            if (i == 3) {
               // Add a coroutine that will display a message in a quarter of a second.
               this_thread::coroutine_scheduler()->add(coroutine([] () -> void {
                  io::text::stdout()->write_line(ABC_SL("delayed message: starting"));
                  this_thread::coroutine_scheduler()->yield_for(250);
                  io::text::stdout()->write_line(ABC_SL("delayed message: this is it"));
                  io::text::stdout()->write_line(ABC_SL("delayed message: terminating"));
               }));
            }
         }
         io::text::stdout()->write_line(ABC_SL("reader: terminating"));
      }));

      // Schedule the writer.
      pcorosched->add(coroutine([this, &pair] () -> void {
         ABC_TRACE_FUNC(this/*, pair*/);

         io::text::stdout()->write_line(ABC_SL("writer: starting"));
         ABC_FOR_EACH(int i, make_range(1, 10)) {
            io::text::stdout()->print(ABC_SL("writer: writing {}\n"), i);
            // This will cause a context switch if the write would block.
            pair.second->write(&i, sizeof i);
            // Execution resumes here, after other coroutines have received CPU time.

            /* Halt this coroutine for a few milliseconds. This will give the reader a chance to be
            scheduled, as well as create a more realistic non-continuous data flow into the pipe. */
            io::text::stdout()->write_line(ABC_SL("writer: yielding"));
            this_thread::coroutine_scheduler()->yield_for(50);
            // Execution resumes here, after other coroutines have received CPU time.
         }
         // Close the writing end of the pipe to report EOF on the reading end.
         pair.second.reset();
         io::text::stdout()->write_line(ABC_SL("writer: terminating"));
      }));

      // Switch this thread to run coroutines, until they all terminate.
      pcorosched->run();
      // Execution resumes here, after all coroutines have terminated.
      io::text::stdout()->write_line(ABC_SL("main: terminating"));
      return 0;
   }
};

ABC_APP_CLASS(coroutines_app)
<|endoftext|>


<commit_before>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2017 Intel Corporation. All Rights Reserved.

#include <librealsense/rs2.hpp>
#include <iostream>
#include <iomanip>
#include <core/streaming.h> //TODO: remove
#include <sensor.h>
#include <record_device.h>

#include "tclap/CmdLine.h"

using namespace std;
using namespace TCLAP;

//TODO: remove when a sensor class actually exists in rs2.hpp
class sensor_REMOVE_ME
{
public:
    sensor_REMOVE_ME(rs2::device sensor) : m_sensor(sensor)
    {

    }

    vector<rsimpl2::stream_profile> get_principal_requests()
    {
        throw std::runtime_error("Not Implemented: get_principal_requests()");
    }
    void open(const vector<rsimpl2::stream_profile>& requests)
    {
        std::vector<rs2::stream_profile> profiles;
        std::transform(requests.begin(),requests.end(), std::back_inserter(profiles),[](const rsimpl2::stream_profile& p)
        {
            return rs2::stream_profile{ p.stream, p.width, p.height, p.fps, p.format};
        } );
        m_sensor.open(profiles);
    }
    void close()
    {
        m_sensor.close();
    }
    void start(rsimpl2::frame_callback_ptr callback)
    {
        //m_sensor.start(callback);
        throw std::runtime_error("Not Implementer: start() ");

    }
    void stop()
    {
        m_sensor.stop();
    }
    rsimpl2::option& get_option(rs2_option id)
    {
        throw std::runtime_error("Not Implemented: get_option()");
    }
    const rsimpl2::option& get_option(rs2_option id) const
    {
        throw std::runtime_error("Not Implemented: get_option() const");
    }
    bool supports_option(rs2_option id) const
    {
        return false;
    }
    const string& get_info(rs2_camera_info info) const
    {
        throw std::runtime_error("Not Implemented: get_info() const");
    }
    bool supports_info(rs2_camera_info info) const
    {
        return false;
    }
    void register_notifications_callback(rsimpl2::notifications_callback_ptr callback)
    {
        throw std::runtime_error("Not Implemented: register_notifications_callback()");
    }
    bool is_streaming() const
    {
        throw std::runtime_error("Not Implemented: is_streaming()");
    }

private:
    rs2::device m_sensor;
};
//TODO: remove when a device class actually exists in rs2.hpp
class device_REMOVE_ME_WHEN_DEVICE_CLASS_EXISTS : public rsimpl2::device_interface
{
public:
    device_REMOVE_ME_WHEN_DEVICE_CLASS_EXISTS()
    {
        m_sensors = m_ctx.query_devices();
        if(m_sensors.empty())
            throw std::runtime_error("No device connected");

        for (auto s: m_sensors)
        {
            //m_sensors_interface.emplace_back<sensor_REMOVE_ME>(std::make_shared<rs2_sensor>());
        }
    }
    const string& get_info(rs2_camera_info info) const override
    {
        return m_sensors[0].get_camera_info(info);
    }
    bool supports_info(rs2_camera_info info) const override
    {
        return m_sensors[0].supports(info);
    }
    rsimpl2::sensor_interface& get_sensor(size_t i) override
    {
        throw std::runtime_error("Not Implementer: get_sensor() ");
    }
    const rsimpl2::sensor_interface& get_sensor(size_t i) const override
    {
        throw std::runtime_error("Not Implementer: get_sensor() const");
    }
    size_t get_sensors_count() const override
    {
        throw std::runtime_error("Not Implementer: get_sensor_count() ");
    }
    void hardware_reset() override
    {
        m_sensors[0].hardware_reset();
    }
    rs2_extrinsics get_extrinsics(size_t from, rs2_stream from_stream, size_t to, rs2_stream to_stream) const override
    {
        return m_ctx.get_extrinsics(m_sensors[from],from_stream,m_sensors[to],to_stream);

    }

    const rs2_device* get() const
    {
        return m_sensors[0].get();
    }

    rs2::context m_ctx;
    vector<rs2::device> m_sensors;
    //vector<std::shared_ptr<rs2_sensor>> m_sensors_interface;
};
//TODO: move to rs2.hpp
class recorder
{
public:
    recorder(std::string file, device_REMOVE_ME_WHEN_DEVICE_CLASS_EXISTS device) :
        m_file(file)
    {
        std::ifstream f(file);
        if(!f.good())
            throw std::invalid_argument(std::string("File ") + file + " does not exists or cannot be opened");

        rs2_error* e = nullptr;
        m_serializer = std::shared_ptr<rs2_device_serializer>(
            rs2_create_device_serializer(file.c_str(), &e),
            rs2_delete_device_serializer);
        rs2::error::handle(e);

        e = nullptr;
        m_record_device = std::shared_ptr<rs2_record_device>(
            rs2_create_record_device(m_live_device.get(), m_serializer.get(), &e),
            rs2_delete_record_device);
        rs2::error::handle(e);
    }
private:
    std::string m_file;
    std::shared_ptr<rs2_device_serializer> m_serializer;
    std::shared_ptr<rs2_device> m_live_device; //TODO: use a pointer to the c struct instead (when there will be one)
    std::shared_ptr<rs2_record_device> m_record_device;
};
int main(int argc, const char** argv) try
{
    CmdLine cmd("librealsense cpp-record example", ' ', RS2_API_VERSION_STR);
    ValueArg<std::string> file_path("f", "file_path", "File path for recording output", false, "record_example.bag", "string");
    cmd.add( file_path );
    cmd.parse(argc, argv);

    device_REMOVE_ME_WHEN_DEVICE_CLASS_EXISTS ds5_device;
    recorder record_device(file_path.getValue(), ds5_device);

    std::cout << "Recording to file: " << file_path.getValue() << std::endl;
    return 0;
}
catch (const rs2::error & e)
{
    cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n    " << e.what() << endl;
    return EXIT_FAILURE;
}<commit_msg>removed somw annoying warnings<commit_after>// License: Apache 2.0. See LICENSE file in root directory.
// Copyright(c) 2017 Intel Corporation. All Rights Reserved.

#include <librealsense/rs2.hpp>
#include <iostream>
#include <iomanip>
#include <core/streaming.h> //TODO: remove
#include <sensor.h>
#include <record_device.h>

#include "tclap/CmdLine.h"

using namespace std;
using namespace TCLAP;

//TODO: remove when a sensor class actually exists in rs2.hpp
class sensor_REMOVE_ME
{
public:
    sensor_REMOVE_ME(rs2::device sensor) : m_sensor(sensor)
    {

    }

    vector<rsimpl2::stream_profile> get_principal_requests()
    {
        throw std::runtime_error("Not Implemented: get_principal_requests()");
    }
    void open(const vector<rsimpl2::stream_profile>& requests)
    {
        std::vector<rs2::stream_profile> profiles;
        std::transform(requests.begin(),requests.end(), std::back_inserter(profiles),[](const rsimpl2::stream_profile& p)
        {
            return rs2::stream_profile{ p.stream,
                                        static_cast<int>(p.width),
                                        static_cast<int>(p.height),
                                        static_cast<int>(p.fps),
                                        p.format};
        } );
        m_sensor.open(profiles);
    }
    void close()
    {
        m_sensor.close();
    }
    void start(rsimpl2::frame_callback_ptr callback)
    {
        //m_sensor.start(callback);
        throw std::runtime_error("Not Implementer: start() ");

    }
    void stop()
    {
        m_sensor.stop();
    }
    rsimpl2::option& get_option(rs2_option id)
    {
        throw std::runtime_error("Not Implemented: get_option()");
    }
    const rsimpl2::option& get_option(rs2_option id) const
    {
        throw std::runtime_error("Not Implemented: get_option() const");
    }
    bool supports_option(rs2_option id) const
    {
        return false;
    }
    const string& get_info(rs2_camera_info info) const
    {
        throw std::runtime_error("Not Implemented: get_info() const");
    }
    bool supports_info(rs2_camera_info info) const
    {
        return false;
    }
    void register_notifications_callback(rsimpl2::notifications_callback_ptr callback)
    {
        throw std::runtime_error("Not Implemented: register_notifications_callback()");
    }
    bool is_streaming() const
    {
        throw std::runtime_error("Not Implemented: is_streaming()");
    }

private:
    rs2::device m_sensor;
};
//TODO: remove when a device class actually exists in rs2.hpp
class device_REMOVE_ME_WHEN_DEVICE_CLASS_EXISTS : public rsimpl2::device_interface
{
public:
    device_REMOVE_ME_WHEN_DEVICE_CLASS_EXISTS()
    {
        m_sensors = m_ctx.query_devices();
        if(m_sensors.empty())
            throw std::runtime_error("No device connected");

        for (auto s: m_sensors)
        {
            //m_sensors_interface.emplace_back<sensor_REMOVE_ME>(std::make_shared<rs2_sensor>());
        }
    }
    const string& get_info(rs2_camera_info info) const override
    {
        throw std::runtime_error("Not Implementer: get_info() const ");
    }
    bool supports_info(rs2_camera_info info) const override
    {
        return m_sensors[0].supports(info);
    }
    rsimpl2::sensor_interface& get_sensor(size_t i) override
    {
        throw std::runtime_error("Not Implementer: get_sensor() ");
    }
    const rsimpl2::sensor_interface& get_sensor(size_t i) const override
    {
        throw std::runtime_error("Not Implementer: get_sensor() const");
    }
    size_t get_sensors_count() const override
    {
        throw std::runtime_error("Not Implementer: get_sensor_count() ");
    }
    void hardware_reset() override
    {
        m_sensors[0].hardware_reset();
    }
    rs2_extrinsics get_extrinsics(size_t from, rs2_stream from_stream, size_t to, rs2_stream to_stream) const override
    {
        return m_ctx.get_extrinsics(m_sensors[from],from_stream,m_sensors[to],to_stream);

    }

    const rs2_device* get() const
    {
        return m_sensors[0].get();
    }

    rs2::context m_ctx;
    vector<rs2::device> m_sensors;
    //vector<std::shared_ptr<rs2_sensor>> m_sensors_interface;
};
//TODO: move to rs2.hpp
class recorder
{
public:
    recorder(std::string file, device_REMOVE_ME_WHEN_DEVICE_CLASS_EXISTS device) :
        m_file(file)
    {
        std::ifstream f(file);
        if(!f.good())
            throw std::invalid_argument(std::string("File ") + file + " does not exists or cannot be opened");

        rs2_error* e = nullptr;
        m_serializer = std::shared_ptr<rs2_device_serializer>(
            rs2_create_device_serializer(file.c_str(), &e),
            rs2_delete_device_serializer);
        rs2::error::handle(e);

        e = nullptr;
        m_record_device = std::shared_ptr<rs2_record_device>(
            rs2_create_record_device(m_live_device.get(), m_serializer.get(), &e),
            rs2_delete_record_device);
        rs2::error::handle(e);
    }
private:
    std::string m_file;
    std::shared_ptr<rs2_device_serializer> m_serializer;
    std::shared_ptr<rs2_device> m_live_device; //TODO: use a pointer to the c struct instead (when there will be one)
    std::shared_ptr<rs2_record_device> m_record_device;
};
int main(int argc, const char** argv) try
{
    CmdLine cmd("librealsense cpp-record example", ' ', RS2_API_VERSION_STR);
    ValueArg<std::string> file_path("f", "file_path", "File path for recording output", false, "record_example.bag", "string");
    cmd.add( file_path );
    cmd.parse(argc, argv);

    device_REMOVE_ME_WHEN_DEVICE_CLASS_EXISTS ds5_device;
    recorder record_device(file_path.getValue(), ds5_device);

    std::cout << "Recording to file: " << file_path.getValue() << std::endl;
    return 0;
}
catch (const rs2::error & e)
{
    cerr << "RealSense error calling " << e.get_failed_function() << "(" << e.get_failed_args() << "):\n    " << e.what() << endl;
    return EXIT_FAILURE;
}<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 *
 * hash_join.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 * /peloton/src/executor/hash_join_executor.cpp
 *
 *-------------------------------------------------------------------------
 */

#include <vector>

#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/hash_join_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"

namespace peloton {
namespace executor {

/**
 * @brief Constructor for nested loop join executor.
 * @param node Nested loop join node corresponding to this executor.
 */
HashJoinExecutor::HashJoinExecutor(const planner::AbstractPlan *node,
                                   ExecutorContext *executor_context)
: AbstractJoinExecutor(node, executor_context) {
}

bool HashJoinExecutor::DInit() {
  assert(children_.size() == 2);

  auto status = AbstractJoinExecutor::DInit();
  if (status == false)
    return status;

  assert(children_[1]->GetRawNode()->GetPlanNodeType() == PLAN_NODE_TYPE_HASH);

  hash_executor_ = reinterpret_cast<HashExecutor*>(children_[1]);

  return true;
}

/**
 * @brief Creates logical tiles from the two input logical tiles after applying
 * join predicate.
 * @return true on success, false otherwise.
 */
bool HashJoinExecutor::DExecute() {

  // Loop until we have non-empty result join logical tile or exit

  // Build outer join output when done

  //===--------------------------------------------------------------------===//
  // Pick right and left tiles
  //===--------------------------------------------------------------------===//

  // Get all the logical tiles from RIGHT child

  // Get next logical tile from LEFT child

  //===--------------------------------------------------------------------===//
  // Build Join Tile
  //===--------------------------------------------------------------------===//

  // Build output join logical tile

  // Build position lists

  // Get the hash table from the hash executor

  // Go over the left logical tile
  // For each tuple, find matching tuples in the hash table built on top of the right table
  // Go over the matching right tuples

  // Check if we have any join tuples

  return false;
}

}  // namespace executor
}  // namespace peloton
<commit_msg>Removed 'Nested Loop' comments<commit_after>/*-------------------------------------------------------------------------
 *
 * hash_join.cpp
 * file description
 *
 * Copyright(c) 2015, CMU
 *
 * /peloton/src/executor/hash_join_executor.cpp
 *
 *-------------------------------------------------------------------------
 */

#include <vector>

#include "backend/common/types.h"
#include "backend/common/logger.h"
#include "backend/executor/logical_tile_factory.h"
#include "backend/executor/hash_join_executor.h"
#include "backend/expression/abstract_expression.h"
#include "backend/expression/container_tuple.h"

namespace peloton {
namespace executor {

/**
 * @brief Constructor for hash join executor.
 * @param node Hash join node corresponding to this executor.
 */
HashJoinExecutor::HashJoinExecutor(const planner::AbstractPlan *node,
                                   ExecutorContext *executor_context)
: AbstractJoinExecutor(node, executor_context) {
}

bool HashJoinExecutor::DInit() {
  assert(children_.size() == 2);

  auto status = AbstractJoinExecutor::DInit();
  if (status == false)
    return status;

  assert(children_[1]->GetRawNode()->GetPlanNodeType() == PLAN_NODE_TYPE_HASH);

  hash_executor_ = reinterpret_cast<HashExecutor*>(children_[1]);

  return true;
}

/**
 * @brief Creates logical tiles from the two input logical tiles after applying
 * join predicate.
 * @return true on success, false otherwise.
 */
bool HashJoinExecutor::DExecute() {

  // Loop until we have non-empty result join logical tile or exit

  // Build outer join output when done

  //===--------------------------------------------------------------------===//
  // Pick right and left tiles
  //===--------------------------------------------------------------------===//

  // Get all the logical tiles from RIGHT child

  // Get next logical tile from LEFT child

  //===--------------------------------------------------------------------===//
  // Build Join Tile
  //===--------------------------------------------------------------------===//

  // Build output join logical tile

  // Build position lists

  // Get the hash table from the hash executor

  // Go over the left logical tile
  // For each tuple, find matching tuples in the hash table built on top of the right table
  // Go over the matching right tuples

  // Check if we have any join tuples

  return false;
}

}  // namespace executor
}  // namespace peloton
<|endoftext|>


<commit_before>#include <yuni/yuni.h>
#include <yuni/core/process/program.h>
#include <yuni/datetime/timestamp.h>
#include <yuni/core/getopt.h>
#include <iostream>

using namespace Yuni;

int main(int argc, char* argv[])
{
	if (argc < 2)
	{
		std::cout << "Usage: " << argv[0] << " <program> [<args>]\n";
		return EXIT_FAILURE;
	}

	Process::Program process;

	// providing arguments
	process.program(argv[1]);
	for (int i = 2; i < argc; ++i)
		process.argumentAdd(argv[i]);

	// use milliseconds instead of seconds
	process.durationPrecision(Process::Program::dpMilliseconds);
	// redirect the output to the console
	process.redirectToConsole(true);

	// execute the command
	sint64 duration = 0;
	int exitStatus = process.execute() ? process.wait(&duration) : EXIT_FAILURE;

	// display the result nearly like `time`
	std::cout << argv[1];
	for (int i = 2; i < argc; ++i)
		std::cout << ' ' << argv[i];

	std::cout << "  " << duration << "ms\n";
	return exitStatus;
}

<commit_msg>sample: Yuni::Process::Program: time: broadcast signals SIGINT (SIGTERM as a bonus) on UNIX to properly handle ctrl-c<commit_after>#include <yuni/yuni.h>
#include <yuni/core/process/program.h>
#include <yuni/datetime/timestamp.h>
#include <yuni/core/getopt.h>
#include <iostream>
#ifdef YUNI_OS_UNIX
#include <signal.h>
#endif

using namespace Yuni;

static Process::Program process;

#ifdef YUNI_OS_UNIX
void signalHandler(int sig)
{
	// sending the same signal to the sub-process. If the sub-process
	// handles the signal, it may have a chance to stop properly and should behave
	// the same than without being executed by this program.
	process.signal(sig);

	if (sig == SIGINT) // ctrl-c
	{
		// a new line to keep the output clean (^C)
		std::cout << std::endl;
	}
}
#endif

int main(int argc, char* argv[])
{
	if (argc < 2)
	{
		std::cout << "Usage: " << argv[0] << " <program> [<args>]\n";
		return EXIT_FAILURE;
	}

	// providing arguments
	process.program(argv[1]);
	for (int i = 2; i < argc; ++i)
		process.argumentAdd(argv[i]);

	// use milliseconds instead of seconds
	process.durationPrecision(Process::Program::dpMilliseconds);
	// redirect the output to the console
	process.redirectToConsole(true);

	#ifdef YUNI_OS_UNIX
	// install signal handler for SIGINT (ctrl-c) and SIGTERM (quit)
	// see note in the 'signalHandler' routine
	::signal(SIGINT,  signalHandler); // interrupt program (^C ctrl-c)
	::signal(SIGTERM, signalHandler); // software termination signal
	#endif

	// execute the command
	sint64 duration = 0;
	int exitStatus = process.execute() ? process.wait(&duration) : EXIT_FAILURE;

	// display the result nearly like `time`
	std::cout << argv[1];
	for (int i = 2; i < argc; ++i)
		std::cout << ' ' << argv[i];

	std::cout << "  " << duration << "ms";
	if (exitStatus != 0)
		std::cout << " (exit: " << exitStatus << ')';
	std::cout << '\n';
	return exitStatus;
}

<|endoftext|>


<commit_before>#include <re2/re2.h>
#include <iostream>

#define arraysize(array) (sizeof(array)/sizeof((array)[0]))

bool ExtractAll(const re2::StringPiece &text,
                 const re2::RE2& re,
                 const re2::StringPiece &rewrite,
                std::string *out) {
  re2::StringPiece vec[1234];//[kVecSize];
  int nvec = 1 + RE2::MaxSubmatch(rewrite);
  if (nvec > arraysize(vec))
    return false;

  bool any = false;
  out->clear();
  int consumed = 0;
  while(re.Match(text, consumed, text.size(), RE2::UNANCHORED, vec, nvec)){
    consumed = vec[0].end() - text.begin();
    if(re.Rewrite(out, rewrite, vec, nvec)) {
      any = true;
    }
  }
  return any;
}

int main(int argc,char** argv){
  int o_global=0,
    o_usage=0,
    o_print_match=0,
    o_also_print_unreplaced=0,
    o_negate_match=0;

  if(argc>1){
    if(argv[1][0] == '-'){
      if ( argv[1][1] == '-'){
        //ignore standalone '--' as argv[1];
      } else {
        // we have flags
        char* fs=argv[1]+1;
        char c;
        while((c=*fs++)){
          switch (c) {
          case 'g':
            o_global = 1;
            break;
          case 'o':
            o_print_match = 1;
            break;
          case 'p':
            o_also_print_unreplaced = 1;
            break;
          case 'v':
            o_negate_match = 1;
            break;
          default:
            o_usage = 1;
          }
        }
      }
      argv[1] = argv[0];
      argv++;
      argc--;
    }
  }

  if(o_usage){
    std::cout << argv[0] << " [-flags] text pattern [replacement]" << std::endl
              << std:: endl
              << "TEXT text to search" << std::endl
              << "PATTERN re2 expression to apply" << std::endl
              << "REPLACEMENT optional replacement string, supports \\0 .. \\9 references"  << std::endl
              << "FLAGS modifiers to operation"  << std::endl
              << std::endl
              << "   h: display help"  << std::endl
              << "   v: invert match"  << std::endl
              << "   o: only print matching portion"  << std::endl
              << "   p: (when replacing) print lines where no replacement was made"  << std::endl
              << "   g: (when replacing) global replace, default is one per line"  << std::endl
         << std::endl;
    return 0;
  }

  /*
  std::cout << "g:" << o_global << std::endl <<
    "u:" << o_usage << std::endl <<
    "p:" << o_print_match << std::endl <<
    "u:" << o_also_print_unreplaced << std::endl <<
    "n:" << o_negate_match << std::endl;*/

  std::string in = std::string(argv[1]);
  std::string out;
  std::string *to_print = NULL;
  RE2::RE2 pat(argv[2]);

  //rationalize flags
  if(o_negate_match && o_print_match){
    o_print_match = 0;
  }

  bool matched;
  bool print;
  if(argc==3){
    // re2g str pat
    // ignores o_global
    if(o_print_match){
      matched = RE2::Extract(in,pat,"\\0",&out);
      to_print=&out;

    } else {
      matched = RE2::PartialMatch(in,pat);
      to_print= ∈
    }
    to_print=(matched^o_negate_match)?to_print:NULL;
  } else if(argc==4) {
    // re2g str pat rep
    // ignores o_print_match

    std::string rep = std::string(argv[3]);

    // need to pick: (-o) Extract, (default)Replace, (-g)GlobalReplace
    // also, print non matching lines? (-p)
    if(o_print_match && !o_global){
      matched = RE2::Extract(in,pat,rep,&out);
      to_print=&out;
    } else if(o_global && !o_print_match) {
      matched = RE2::GlobalReplace(&in,pat,rep);
      to_print=∈
    } else if(o_global && o_print_match){
      matched = ExtractAll(in,pat,rep,&out);
      to_print=&out;
    } else {
      matched = RE2::Replace(&in,pat,rep);
      to_print=∈
    }
    to_print=(matched^o_negate_match)?to_print:NULL;

    if(o_also_print_unreplaced && !to_print){
      out = std::string(argv[1]);
      to_print = & out;
    }
  } else {
    std::cout << RE2::PartialMatch("f", "f") << std::endl;
    std::cout << RE2::PartialMatch("fred", "z") << std::endl;
    std::cout << RE2::PartialMatch("fred", "[fz]") << std::endl;
  }
  if(to_print){
    std::cout << *to_print << std::endl;
  } else {
    std::cout << std::endl;
  }
}

<commit_msg>spacing cleanup<commit_after>#include <re2/re2.h>
#include <iostream>

#define arraysize(array) (sizeof(array)/sizeof((array)[0]))

bool ExtractAll(const re2::StringPiece &text,
                 const re2::RE2& re,
                 const re2::StringPiece &rewrite,
                std::string *out) {
  re2::StringPiece vec[1234];//[kVecSize];
  int nvec = 1 + RE2::MaxSubmatch(rewrite);
  if (nvec > arraysize(vec))
    return false;

  bool any = false;
  out->clear();
  int consumed = 0;
  while(re.Match(text, consumed, text.size(), RE2::UNANCHORED, vec, nvec)){
    consumed = vec[0].end() - text.begin();
    if(re.Rewrite(out, rewrite, vec, nvec)) {
      any = true;
    }
  }
  return any;
}

int main(int argc,char** argv){
  int o_global=0,
    o_usage=0,
    o_print_match=0,
    o_also_print_unreplaced=0,
    o_negate_match=0;

  if(argc>1){
    if(argv[1][0] == '-'){
      if ( argv[1][1] == '-'){
        //ignore standalone '--' as argv[1];
      } else {
        // we have flags
        char* fs=argv[1]+1;
        char c;
        while((c=*fs++)){
          switch (c) {
          case 'g':
            o_global = 1;
            break;
          case 'o':
            o_print_match = 1;
            break;
          case 'p':
            o_also_print_unreplaced = 1;
            break;
          case 'v':
            o_negate_match = 1;
            break;
          default:
            o_usage = 1;
          }
        }
      }
      argv[1] = argv[0];
      argv++;
      argc--;
    }
  }

  if(o_usage){
    std::cout << argv[0] << " [-flags] text pattern [replacement]" << std::endl
              << std:: endl
              << "TEXT text to search" << std::endl
              << "PATTERN re2 expression to apply" << std::endl
              << "REPLACEMENT optional replacement string, supports \\0 .. \\9 references"  << std::endl
              << "FLAGS modifiers to operation"  << std::endl
              << std::endl
              << "   h: display help"  << std::endl
              << "   v: invert match"  << std::endl
              << "   o: only print matching portion"  << std::endl
              << "   p: (when replacing) print lines where no replacement was made"  << std::endl
              << "   g: (when replacing) global replace, default is one per line"  << std::endl
         << std::endl;
    return 0;
  }

  /*
  std::cout << "g:" << o_global << std::endl <<
    "u:" << o_usage << std::endl <<
    "p:" << o_print_match << std::endl <<
    "u:" << o_also_print_unreplaced << std::endl <<
    "n:" << o_negate_match << std::endl;*/

  std::string in = std::string(argv[1]);
  std::string out;
  std::string *to_print = NULL;
  RE2::RE2 pat(argv[2]);

  //rationalize flags
  if(o_negate_match && o_print_match){
    o_print_match = 0;
  }

  bool matched;
  bool print;
  if(argc==3){
    // re2g str pat
    // ignores o_global
    if(o_print_match){
      matched = RE2::Extract(in,pat,"\\0",&out);
      to_print=&out;

    } else {
      matched = RE2::PartialMatch(in,pat);
      to_print= ∈
    }
    to_print=(matched^o_negate_match)?to_print:NULL;
  } else if(argc==4) {
    // re2g str pat rep
    // ignores o_print_match

    std::string rep = std::string(argv[3]);

    // need to pick: (-o) Extract, (default)Replace, (-g)GlobalReplace
    // also, print non matching lines? (-p)
    if(o_print_match && !o_global){
      matched = RE2::Extract(in,pat,rep,&out);
      to_print=&out;
    } else if(o_global && !o_print_match) {
      matched = RE2::GlobalReplace(&in,pat,rep);
      to_print=∈
    } else if(o_global && o_print_match){
      matched = ExtractAll(in,pat,rep,&out);
      to_print=&out;
    } else {
      matched = RE2::Replace(&in,pat,rep);
      to_print=∈
    }
    to_print=(matched ^ o_negate_match)?to_print:NULL;

    if(o_also_print_unreplaced && !to_print){
      out = std::string(argv[1]);
      to_print = & out;
    }
  } else {
    std::cout << RE2::PartialMatch("f", "f") << std::endl;
    std::cout << RE2::PartialMatch("fred", "z") << std::endl;
    std::cout << RE2::PartialMatch("fred", "[fz]") << std::endl;
  }
  if(to_print){
    std::cout << *to_print << std::endl;
  } else {
    std::cout << std::endl;
  }
}

<|endoftext|>


<commit_before><commit_msg>`SymbiontMaterial`: remove obsolete member function declarations.<commit_after><|endoftext|>