<commit_before>/************************************************************************
    filename:   CEGuiOpenGLBaseApplication.cpp
    created:    24/9/2004
    author:     Paul D Turner
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://www.cegui.org.uk)
    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#ifdef HAVE_CONFIG_H
#   include "config.h"
#endif

// this controls conditional compile of file for MSVC
#include "CEGUIConfig.h"
#ifdef CEGUI_SAMPLES_USE_OPENGL

#include "CEGuiOpenGLBaseApplication.h"
#include "renderers/OpenGLGUIRenderer/openglrenderer.h"
#include "CEGuiSample.h"
#include "CEGUI.h"

#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>

#include <stdexcept>
#include <stdlib.h>

#ifdef _MSC_VER
# if defined(DEBUG) || defined (_DEBUG)
#   pragma comment (lib, "OpenGLGUIRenderer_d.lib")
# else
#   pragma comment (lib, "OpenGLGUIRenderer.lib")
# endif
#endif

/*************************************************************************
    Simple key-map used to translate glut special keys to CEGUI keys.
    See: CEGuiOpenGLBaseApplication::keySpecial method.
*************************************************************************/
struct GlutKeyMapping
{
    int glutKey;
    CEGUI::uint  ceguiKey;
};

GlutKeyMapping specialKeyMap[] =
{
    {GLUT_KEY_F1, CEGUI::Key::F1},
    {GLUT_KEY_F2, CEGUI::Key::F2},
    {GLUT_KEY_F3, CEGUI::Key::F3},
    {GLUT_KEY_F4, CEGUI::Key::F4},
    {GLUT_KEY_F5, CEGUI::Key::F5},
    {GLUT_KEY_F6, CEGUI::Key::F6},
    {GLUT_KEY_F7, CEGUI::Key::F7},
    {GLUT_KEY_F8, CEGUI::Key::F8},
    {GLUT_KEY_F9, CEGUI::Key::F9},
    {GLUT_KEY_F10, CEGUI::Key::F10},
    {GLUT_KEY_F11, CEGUI::Key::F11},
    {GLUT_KEY_F12, CEGUI::Key::F12},
    {GLUT_KEY_LEFT, CEGUI::Key::ArrowLeft},
    {GLUT_KEY_UP, CEGUI::Key::ArrowUp},
    {GLUT_KEY_RIGHT, CEGUI::Key::ArrowRight},
    {GLUT_KEY_DOWN, CEGUI::Key::ArrowDown},
    {GLUT_KEY_PAGE_UP, CEGUI::Key::PageUp},
    {GLUT_KEY_PAGE_DOWN, CEGUI::Key::PageDown},
    {GLUT_KEY_HOME, CEGUI::Key::Home},
    {GLUT_KEY_END, CEGUI::Key::End},
    {GLUT_KEY_INSERT, CEGUI::Key::Insert},
    {-1, 0}
};

/*************************************************************************
    Static Data
*************************************************************************/
bool CEGuiOpenGLBaseApplication::d_quitFlag = false;

/*************************************************************************
    Constructor.
*************************************************************************/
CEGuiOpenGLBaseApplication::CEGuiOpenGLBaseApplication()
{
    // fake args for glutInit
    int argc = 1;
    char* argv = "SampleApp";

    // Do GLUT init
    glutInit(&argc, &argv);
    glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);
    glutInitWindowSize(800, 600);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("Crazy Eddie's GUI Mk-2 - Sample Application");
    glutSetCursor(GLUT_CURSOR_NONE);

    glutDisplayFunc(&CEGuiOpenGLBaseApplication::drawFrame);
    glutReshapeFunc(&CEGuiOpenGLBaseApplication::reshape);
    glutMotionFunc(&CEGuiOpenGLBaseApplication::mouseMotion);
    glutPassiveMotionFunc(&CEGuiOpenGLBaseApplication::mouseMotion);
    glutMouseFunc(&CEGuiOpenGLBaseApplication::mouseButton);
    glutKeyboardFunc(&CEGuiOpenGLBaseApplication::keyChar);
    glutSpecialFunc(&CEGuiOpenGLBaseApplication::keySpecial);

    // Set the clear color
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

    d_renderer = new CEGUI::OpenGLRenderer(1024);
    new CEGUI::System(d_renderer);
}

/*************************************************************************
    Destructor.
*************************************************************************/
CEGuiOpenGLBaseApplication::~CEGuiOpenGLBaseApplication()
{
    delete CEGUI::System::getSingletonPtr();
    delete d_renderer;
}

/*************************************************************************
    Start the base application
*************************************************************************/
bool CEGuiOpenGLBaseApplication::execute(CEGuiSample* sampleApp)
{
    sampleApp->initialiseSample();

    glutMainLoop();

    return true;
}

/*************************************************************************
    Performs any required cleanup of the base application system.
*************************************************************************/
void CEGuiOpenGLBaseApplication::cleanup()
{
    // nothing to do here.
}

/*************************************************************************
    Set whether the app should quit
*************************************************************************/
void CEGuiOpenGLBaseApplication::setQuitting(bool quit)
{
    d_quitFlag = quit;
}

/*************************************************************************
    Is this app quitting
*************************************************************************/
bool CEGuiOpenGLBaseApplication::isQuitting() const
{
    return d_quitFlag;
}

/*************************************************************************
    Does whatever is required in one single frame
*************************************************************************/
void CEGuiOpenGLBaseApplication::drawFrame(void)
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0.0, 0.0, 12, 0.0, 0.0, -100, 0.0, 1.0, 0.0);

    CEGUI::System::getSingleton().renderGUI();

    glFlush();
    glutPostRedisplay();
    glutSwapBuffers();

    // here we check the 'quitting' state and cleanup as required.
    // this is probably not the best way to do this, but since we're
    // using glut, and glutMainLoop can never return, we need some
    // way of checking when to exit.  And this is it...
    if (d_quitFlag)
    {
        // cleanup cegui system
        CEGUI::Renderer* renderer = CEGUI::System::getSingleton().getRenderer();
        delete CEGUI::System::getSingletonPtr();
        delete renderer;

        // exit
        exit(0);
    }
}

void CEGuiOpenGLBaseApplication::reshape(int w, int h)
{
    glViewport (0, 0, (GLsizei) w, (GLsizei) h);
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity ();
    gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 50.0);
    glMatrixMode(GL_MODELVIEW);
}

void CEGuiOpenGLBaseApplication::mouseMotion(int x, int y)
{
    CEGUI::System::getSingleton().injectMousePosition(x, y);
}

void CEGuiOpenGLBaseApplication::mouseButton(int button, int state, int x, int y)
{
    switch(button)
    {
    case  GLUT_LEFT_BUTTON:
        if (state == GLUT_UP)
        {
            CEGUI::System::getSingleton().injectMouseButtonUp(CEGUI::LeftButton);
        }
        else
        {
            CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::LeftButton);

        }
        break;

    case GLUT_RIGHT_BUTTON:
        if (state == GLUT_UP)
        {
            CEGUI::System::getSingleton().injectMouseButtonUp(CEGUI::RightButton);
        }
        else
        {
            CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::RightButton);
        }
        break;

    case GLUT_MIDDLE_BUTTON:
        if (state == GLUT_UP)
        {
            CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::MiddleButton);
        }
        else
        {
            CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::MiddleButton);
        }
        break;
    }

}

void CEGuiOpenGLBaseApplication::keyChar(unsigned char key, int x, int y)
{
    // extract some keys may be handled via key code and generate those too
    switch (key)
    {
    case 0x08:  // backspace
        CEGUI::System::getSingleton().injectKeyDown(CEGUI::Key::Backspace);
        break;
    case 0x7F:  // delete
        CEGUI::System::getSingleton().injectKeyDown(CEGUI::Key::Delete);
        break;
    case 0x1B:  // Escape
        d_quitFlag = true;
        break;
    case 0x0D:  // CR (Return)
        CEGUI::System::getSingleton().injectKeyDown(CEGUI::Key::Return);
        break;
    }

    // always inject Character even if we have done key-down injection
    CEGUI::System::getSingleton().injectChar(static_cast<CEGUI::utf32>(key));
}

void CEGuiOpenGLBaseApplication::keySpecial(int key, int x, int y)
{
    GlutKeyMapping* mapping = specialKeyMap;

    while (mapping->glutKey != -1)
    {
        if (mapping->glutKey == key)
        {
            CEGUI::System::getSingleton().injectKeyDown(mapping->ceguiKey);
            return;
        }

        ++mapping;
    }
}

#endif

<commit_msg>Bug Fix: Minor fix to glut base app so some <32 chars are not entered into edit boxes as text<commit_after>/************************************************************************
    filename:   CEGuiOpenGLBaseApplication.cpp
    created:    24/9/2004
    author:     Paul D Turner
*************************************************************************/
/*************************************************************************
    Crazy Eddie's GUI System (http://www.cegui.org.uk)
    Copyright (C)2004 - 2005 Paul D Turner (paul@cegui.org.uk)

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

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

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*************************************************************************/
#ifdef HAVE_CONFIG_H
#   include "config.h"
#endif

// this controls conditional compile of file for MSVC
#include "CEGUIConfig.h"
#ifdef CEGUI_SAMPLES_USE_OPENGL

#include "CEGuiOpenGLBaseApplication.h"
#include "renderers/OpenGLGUIRenderer/openglrenderer.h"
#include "CEGuiSample.h"
#include "CEGUI.h"

#include <GL/glut.h>
#include <GL/gl.h>
#include <GL/glu.h>

#include <stdexcept>
#include <stdlib.h>

#ifdef _MSC_VER
# if defined(DEBUG) || defined (_DEBUG)
#   pragma comment (lib, "OpenGLGUIRenderer_d.lib")
# else
#   pragma comment (lib, "OpenGLGUIRenderer.lib")
# endif
#endif

/*************************************************************************
    Simple key-map used to translate glut special keys to CEGUI keys.
    See: CEGuiOpenGLBaseApplication::keySpecial method.
*************************************************************************/
struct GlutKeyMapping
{
    int glutKey;
    CEGUI::uint  ceguiKey;
};

GlutKeyMapping specialKeyMap[] =
{
    {GLUT_KEY_F1, CEGUI::Key::F1},
    {GLUT_KEY_F2, CEGUI::Key::F2},
    {GLUT_KEY_F3, CEGUI::Key::F3},
    {GLUT_KEY_F4, CEGUI::Key::F4},
    {GLUT_KEY_F5, CEGUI::Key::F5},
    {GLUT_KEY_F6, CEGUI::Key::F6},
    {GLUT_KEY_F7, CEGUI::Key::F7},
    {GLUT_KEY_F8, CEGUI::Key::F8},
    {GLUT_KEY_F9, CEGUI::Key::F9},
    {GLUT_KEY_F10, CEGUI::Key::F10},
    {GLUT_KEY_F11, CEGUI::Key::F11},
    {GLUT_KEY_F12, CEGUI::Key::F12},
    {GLUT_KEY_LEFT, CEGUI::Key::ArrowLeft},
    {GLUT_KEY_UP, CEGUI::Key::ArrowUp},
    {GLUT_KEY_RIGHT, CEGUI::Key::ArrowRight},
    {GLUT_KEY_DOWN, CEGUI::Key::ArrowDown},
    {GLUT_KEY_PAGE_UP, CEGUI::Key::PageUp},
    {GLUT_KEY_PAGE_DOWN, CEGUI::Key::PageDown},
    {GLUT_KEY_HOME, CEGUI::Key::Home},
    {GLUT_KEY_END, CEGUI::Key::End},
    {GLUT_KEY_INSERT, CEGUI::Key::Insert},
    {-1, 0}
};

/*************************************************************************
    Static Data
*************************************************************************/
bool CEGuiOpenGLBaseApplication::d_quitFlag = false;

/*************************************************************************
    Constructor.
*************************************************************************/
CEGuiOpenGLBaseApplication::CEGuiOpenGLBaseApplication()
{
    // fake args for glutInit
    int argc = 1;
    char* argv = "SampleApp";

    // Do GLUT init
    glutInit(&argc, &argv);
    glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);
    glutInitWindowSize(800, 600);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("Crazy Eddie's GUI Mk-2 - Sample Application");
    glutSetCursor(GLUT_CURSOR_NONE);

    glutDisplayFunc(&CEGuiOpenGLBaseApplication::drawFrame);
    glutReshapeFunc(&CEGuiOpenGLBaseApplication::reshape);
    glutMotionFunc(&CEGuiOpenGLBaseApplication::mouseMotion);
    glutPassiveMotionFunc(&CEGuiOpenGLBaseApplication::mouseMotion);
    glutMouseFunc(&CEGuiOpenGLBaseApplication::mouseButton);
    glutKeyboardFunc(&CEGuiOpenGLBaseApplication::keyChar);
    glutSpecialFunc(&CEGuiOpenGLBaseApplication::keySpecial);

    // Set the clear color
    glClearColor(0.0f, 0.0f, 0.0f, 1.0f);

    d_renderer = new CEGUI::OpenGLRenderer(1024);
    new CEGUI::System(d_renderer);
}

/*************************************************************************
    Destructor.
*************************************************************************/
CEGuiOpenGLBaseApplication::~CEGuiOpenGLBaseApplication()
{
    delete CEGUI::System::getSingletonPtr();
    delete d_renderer;
}

/*************************************************************************
    Start the base application
*************************************************************************/
bool CEGuiOpenGLBaseApplication::execute(CEGuiSample* sampleApp)
{
    sampleApp->initialiseSample();

    glutMainLoop();

    return true;
}

/*************************************************************************
    Performs any required cleanup of the base application system.
*************************************************************************/
void CEGuiOpenGLBaseApplication::cleanup()
{
    // nothing to do here.
}

/*************************************************************************
    Set whether the app should quit
*************************************************************************/
void CEGuiOpenGLBaseApplication::setQuitting(bool quit)
{
    d_quitFlag = quit;
}

/*************************************************************************
    Is this app quitting
*************************************************************************/
bool CEGuiOpenGLBaseApplication::isQuitting() const
{
    return d_quitFlag;
}

/*************************************************************************
    Does whatever is required in one single frame
*************************************************************************/
void CEGuiOpenGLBaseApplication::drawFrame(void)
{
    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glEnable(GL_DEPTH_TEST);
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    gluLookAt(0.0, 0.0, 12, 0.0, 0.0, -100, 0.0, 1.0, 0.0);

    CEGUI::System::getSingleton().renderGUI();

    glFlush();
    glutPostRedisplay();
    glutSwapBuffers();

    // here we check the 'quitting' state and cleanup as required.
    // this is probably not the best way to do this, but since we're
    // using glut, and glutMainLoop can never return, we need some
    // way of checking when to exit.  And this is it...
    if (d_quitFlag)
    {
        // cleanup cegui system
        CEGUI::Renderer* renderer = CEGUI::System::getSingleton().getRenderer();
        delete CEGUI::System::getSingletonPtr();
        delete renderer;

        // exit
        exit(0);
    }
}

void CEGuiOpenGLBaseApplication::reshape(int w, int h)
{
    glViewport (0, 0, (GLsizei) w, (GLsizei) h);
    glMatrixMode (GL_PROJECTION);
    glLoadIdentity ();
    gluPerspective(60.0, (GLfloat) w/(GLfloat) h, 1.0, 50.0);
    glMatrixMode(GL_MODELVIEW);
}

void CEGuiOpenGLBaseApplication::mouseMotion(int x, int y)
{
    CEGUI::System::getSingleton().injectMousePosition(x, y);
}

void CEGuiOpenGLBaseApplication::mouseButton(int button, int state, int x, int y)
{
    switch(button)
    {
    case  GLUT_LEFT_BUTTON:
        if (state == GLUT_UP)
        {
            CEGUI::System::getSingleton().injectMouseButtonUp(CEGUI::LeftButton);
        }
        else
        {
            CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::LeftButton);

        }
        break;

    case GLUT_RIGHT_BUTTON:
        if (state == GLUT_UP)
        {
            CEGUI::System::getSingleton().injectMouseButtonUp(CEGUI::RightButton);
        }
        else
        {
            CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::RightButton);
        }
        break;

    case GLUT_MIDDLE_BUTTON:
        if (state == GLUT_UP)
        {
            CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::MiddleButton);
        }
        else
        {
            CEGUI::System::getSingleton().injectMouseButtonDown(CEGUI::MiddleButton);
        }
        break;
    }

}

void CEGuiOpenGLBaseApplication::keyChar(unsigned char key, int x, int y)
{
    // extract some keys may be handled via key code and generate those too
    switch (key)
    {
    case 0x08:  // backspace
        CEGUI::System::getSingleton().injectKeyDown(CEGUI::Key::Backspace);
        break;
    case 0x7F:  // delete
        CEGUI::System::getSingleton().injectKeyDown(CEGUI::Key::Delete);
        break;
    case 0x1B:  // Escape
        d_quitFlag = true;
        break;
    case 0x0D:  // CR (Return)
        CEGUI::System::getSingleton().injectKeyDown(CEGUI::Key::Return);
        break;
    default:
        // inject Character code
        CEGUI::System::getSingleton().injectChar(static_cast<CEGUI::utf32>(key));
        break;
    }

}

void CEGuiOpenGLBaseApplication::keySpecial(int key, int x, int y)
{
    GlutKeyMapping* mapping = specialKeyMap;

    while (mapping->glutKey != -1)
    {
        if (mapping->glutKey == key)
        {
            CEGUI::System::getSingleton().injectKeyDown(mapping->ceguiKey);
            return;
        }

        ++mapping;
    }
}

#endif

<|endoftext|>


<commit_before>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <vector>

// void shrink_to_fit();

#include <vector>
#include <cassert>
#include "../../../stack_allocator.h"

int main()
{
    {
        std::vector<int> v(100);
        v.push_back(1);
        v.shrink_to_fit();
        assert(v.capacity() == 101);
        assert(v.size() == 101);
    }
    {
        std::vector<int, stack_allocator<int, 401> > v(100);
        v.push_back(1);
        v.shrink_to_fit();
        assert(v.capacity() == 101);
        assert(v.size() == 101);
    }
    {
        std::vector<int, stack_allocator<int, 400> > v(100);
        v.push_back(1);
        v.shrink_to_fit();
        assert(v.capacity() == 200);
        assert(v.size() == 101);
    }
}
<commit_msg>The 3rd test in shrink_to_fit.pass.cpp can't possibly pass if exceptions are disabled, so #ifdef'ing out the test.<commit_after>//===----------------------------------------------------------------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is dual licensed under the MIT and the University of Illinois Open
// Source Licenses. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// <vector>

// void shrink_to_fit();

#include <vector>
#include <cassert>
#include "../../../stack_allocator.h"

int main()
{
    {
        std::vector<int> v(100);
        v.push_back(1);
        v.shrink_to_fit();
        assert(v.capacity() == 101);
        assert(v.size() == 101);
    }
    {
        std::vector<int, stack_allocator<int, 401> > v(100);
        v.push_back(1);
        v.shrink_to_fit();
        assert(v.capacity() == 101);
        assert(v.size() == 101);
    }
#ifndef _LIBCPP_NO_EXCEPTIONS
    {
        std::vector<int, stack_allocator<int, 400> > v(100);
        v.push_back(1);
        v.shrink_to_fit();
        assert(v.capacity() == 200);
        assert(v.size() == 101);
    }
#endif
}
<|endoftext|>


<commit_before>// Intro.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Parser.h"

#if defined(_MSC_VER) && defined(_DEBUG)
#include <vld.h>
#endif

#include <stdio.h>
#include "Environment.h"
#include <string>
#include "JIT.h"

#include "llvm/Support/CommandLine.h"
#include "llvm/IR/Verifier.h"
#include "CodeGenEnvironment.h"
#include "CodeGenModule.h"

#include "Runtime.h"

void runBasicTests(void);

namespace intro
{
	void initModule(void);
	void initRuntime(void);
	void deleteRuntime(void);
	void dumpModule(void);
	void runStatements(const std::list<intro::Statement*> &statements);

	extern llvm::LLVMContext theContext;
	extern std::unique_ptr<llvm::Module> TheModule;
	extern intro::CodeGenEnvironment global;
	extern llvm::IRBuilder<> Builder;
}

namespace llvm
{
	void llvm_shutdown();
}

void cleanupSourceFiles();

llvm::cl::opt<std::string> Script(llvm::cl::Positional, llvm::cl::desc("<input script>"), llvm::cl::init("-"));
llvm::cl::list<std::string>  Argv(llvm::cl::ConsumeAfter, llvm::cl::desc("<program arguments>..."));
llvm::cl::opt<bool> runTests("test", llvm::cl::desc("Run hard-coded basic tests"));

//int _tmain(int argc, _TCHAR* argv[])
#ifdef WIN32
int main(int argc,const char *argv[])
//int wmain(int argc, const wchar_t *argv[])
#else
int main(int argc, char *argv[])
#endif
{
	llvm::cl::ParseCommandLineOptions(argc, argv);

	intro::initRuntime();
	if (runTests)
	{
		intro::initModule();
		runBasicTests();
		intro::dumpModule();
		printf("Done!\n");
		//return 0;
	}
	else
	{
		intro::Environment global;
		if (Script=="-") // Interactive Mode
		{
			// run interactive command line
			intro::initModule();
			parse::Scanner scanner(stdin);
			parse::Parser parser(&scanner);
			parser.isInteractive=true;
			parser.Parse();
			parser.deleteStatements();
		}
		else // Run script
		{
			intro::initModule();
			parse::Scanner scanner(Script.c_str());
			parse::Parser parser(&scanner);
			parser.isInteractive=false;
			parser.Parse();

			if (parser.errors->count>0)
			{
				std::wcout << L"Found " << parser.errors->count << L" errors while parsing!\n";
			}
			else
			{
				intro::Environment global;
				bool isOK = true;
				for (auto iter = parser.parseResult.begin();isOK && iter != parser.parseResult.end();iter++)
				{
					isOK = (*iter)->makeType(&global);
					if (!isOK)
					{
						std::wcout << L"Error in line:\n";
						(*iter)->print(std::wcout);
						std::wcout << L"\n";
					}
				}
				if (isOK)
					runStatements(parser.parseResult);
				else
					std::wcout << L"Type errors detected!\n";
			}
			//getchar();
			parser.deleteStatements();

			// Run script
		}
	}
	intro::Environment::deleteAllModules();
	cleanupSourceFiles();
	intro::Environment::clearTypeVariables();
	intro::deleteRuntime();
	intro::CodeGenModule::deleteRootModule();
	intro::Environment::deleteRootModule();
	llvm::llvm_shutdown();

	return 0;
}

<commit_msg>Check if file from parameter exists...<commit_after>// Intro.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include "Parser.h"

#if defined(_MSC_VER) && defined(_DEBUG)
#include <vld.h>
#endif

#include <stdio.h>
#include "Environment.h"
#include <string>
#include "JIT.h"

#include "llvm/Support/CommandLine.h"
#include "llvm/IR/Verifier.h"
#include "CodeGenEnvironment.h"
#include "CodeGenModule.h"

#include "Runtime.h"

void runBasicTests(void);

namespace intro
{
	void initModule(void);
	void initRuntime(void);
	void deleteRuntime(void);
	void dumpModule(void);
	void runStatements(const std::list<intro::Statement*> &statements);

	extern llvm::LLVMContext theContext;
	extern std::unique_ptr<llvm::Module> TheModule;
	extern intro::CodeGenEnvironment global;
	extern llvm::IRBuilder<> Builder;
}

namespace llvm
{
	void llvm_shutdown();
}

void cleanupSourceFiles();

llvm::cl::opt<std::string> Script(llvm::cl::Positional, llvm::cl::desc("<input script>"), llvm::cl::init("-"));
llvm::cl::list<std::string>  Argv(llvm::cl::ConsumeAfter, llvm::cl::desc("<program arguments>..."));
llvm::cl::opt<bool> runTests("test", llvm::cl::desc("Run hard-coded basic tests"));

//int _tmain(int argc, _TCHAR* argv[])
#ifdef WIN32
int main(int argc,const char *argv[])
//int wmain(int argc, const wchar_t *argv[])
#else
int main(int argc, char *argv[])
#endif
{
	llvm::cl::ParseCommandLineOptions(argc, argv);

	intro::initRuntime();
	if (runTests)
	{
		intro::initModule();
		runBasicTests();
		intro::dumpModule();
		printf("Done!\n");
		//return 0;
	}
	else
	{
		intro::Environment global;
		if (Script=="-") // Interactive Mode
		{
			// run interactive command line
			intro::initModule();
			parse::Scanner scanner(stdin);
			parse::Parser parser(&scanner);
			parser.isInteractive=true;
			parser.Parse();
			parser.deleteStatements();
		}
		else // Run script
		{
			intro::initModule();
			parse::Scanner scanner(Script.c_str());
			if (!scanner.isOk())
			{
				std::cout << "Error: File '" << Script << "'not found!\n";
			}
			else
			{
				parse::Parser parser(&scanner);
				parser.isInteractive = false;
				parser.Parse();

				if (parser.errors->count > 0)
				{
					std::wcout << L"Found " << parser.errors->count << L" errors while parsing!\n";
				}
				else
				{
					intro::Environment global;
					bool isOK = true;
					for (auto iter = parser.parseResult.begin();isOK && iter != parser.parseResult.end();iter++)
					{
						isOK = (*iter)->makeType(&global);
						if (!isOK)
						{
							std::wcout << L"Error in line:\n";
							(*iter)->print(std::wcout);
							std::wcout << L"\n";
						}
					}
					if (isOK)
						runStatements(parser.parseResult);
					else
						std::wcout << L"Type errors detected!\n";
				}
				//getchar();
				parser.deleteStatements();
			}
		}
	}
	intro::Environment::deleteAllModules();
	cleanupSourceFiles();
	intro::Environment::clearTypeVariables();
	intro::deleteRuntime();
	intro::CodeGenModule::deleteRootModule();
	intro::Environment::deleteRootModule();
	llvm::llvm_shutdown();

	return 0;
}

<|endoftext|>


<commit_before>#include "infrastructure.hpp"

namespace fc
{

std::shared_ptr<parallel_region> infrastructure::add_region(const std::string& name,
		const virtual_clock::steady::duration& tick_rate)
{
	auto region = std::make_shared<parallel_region>(name);

	auto work_tick = region->ticks.in_work();
	auto tick_cycle = fc::thread::periodic_task(
			[work_tick](){ work_tick(); });

	tick_cycle.out_switch_tick() >> region->ticks.in_switch_buffers();
	scheduler.add_task(std::move(tick_cycle),tick_rate);

	return region;
}

infrastructure::infrastructure() :
	// abstract_graph(),
		scheduler(),
		forest_root("root",
				add_region("root_region", thread::cycle_control::medium_tick))
{
}

void infrastructure::iterate_main_loop()
{
	using namespace std::chrono_literals;
	std::this_thread::sleep_for(0.5s);
	if (auto ex = scheduler.last_exception())
	{
		std::rethrow_exception(ex);
	}
}

void infrastructure::infinite_main_loop()
{
	while( true )
	{
		iterate_main_loop();
	}
}

} /* namespace fc */
<commit_msg>infrastructure: capture region in periodic_task.<commit_after>#include "infrastructure.hpp"

namespace fc
{

std::shared_ptr<parallel_region> infrastructure::add_region(const std::string& name,
		const virtual_clock::steady::duration& tick_rate)
{
	auto region = std::make_shared<parallel_region>(name);

	auto work_tick = region->ticks.in_work();
	// tick_cycle captures region to prevent dangling reference after return
	// (if no one stores the region in a variable).
	// TODO: evaluate storing the region in a vector inside infrastructure.
	auto tick_cycle = fc::thread::periodic_task(
			[work_tick,region](){ work_tick(); });

	tick_cycle.out_switch_tick() >> region->ticks.in_switch_buffers();
	scheduler.add_task(std::move(tick_cycle),tick_rate);

	return region;
}

infrastructure::infrastructure() :
	// abstract_graph(),
		scheduler(),
		forest_root("root",
				add_region("root_region", thread::cycle_control::medium_tick))
{
}

void infrastructure::iterate_main_loop()
{
	using namespace std::chrono_literals;
	std::this_thread::sleep_for(0.5s);
	if (auto ex = scheduler.last_exception())
	{
		std::rethrow_exception(ex);
	}
}

void infrastructure::infinite_main_loop()
{
	while( true )
	{
		iterate_main_loop();
	}
}

} /* namespace fc */
<|endoftext|>


<commit_before>/**
 * ZNC Mailer Module
 *
 * A ZNC Module that uses the Unix mail command to send mentions and private
 * messages to an email address when you are not connected to ZNC.
 *
 * Copyright (c) 2011 Dougal Matthews
 * Licensed under the MIT license
 */

#include <main.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <list>

#include <Modules.h>
#include <IRCSock.h>
#include <User.h>
#include <Nick.h>
#include <Chan.h>

class CMailerTimer: public CTimer {
public:

    CMailerTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {}
    virtual ~CMailerTimer() {}

protected:
    virtual void RunJob();

};

class CMailer : public CModule {

protected:
    CUser *ConnectedUser;
    list<CString> MessagesList;
    CString NotificationSubject;
    CString NotificationEmail;
    unsigned int MaxNotifications;
    bool DebugMode;

public:

    MODCONSTRUCTOR(CMailer) {
        ConnectedUser = GetUser();
        DebugMode = false;
        NotificationSubject = "IRC Notification";
    }

    virtual ~CMailer() {}

    void DebugPrint(string sMessage){
        if (DebugMode){
            PutModule(sMessage);
        }
    }

    virtual bool OnLoad(const CString& sArgs, CString& sErrorMsg) {

        AddTimer(new CMailerTimer(this, 1200, 0, "Mail", "Send emails every 20 mins."));
        MaxNotifications = 50;

        PutModule("Please tell me what email address you want notifications to be sent to with 'email <address>'");

        VCString tokens;
        int token_count = sArgs.Split(" ", tokens, false);

        if (token_count < 1)
        {
            return true;
        }

        CString action = tokens[0].AsLower();

        if (action == "debug"){
            PutModule("DEBUG ON");
            DebugMode = true;
        }

        return true;

    }

    virtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) {

        Handle(Nick, Channel.GetName(), sMessage);

        return CONTINUE;
    }

    virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage) {

        Handle(Nick, "PRIVATE", sMessage);

        return CONTINUE;
    }

    void OnModCommand(const CString& command)
    {
        VCString tokens;
        int token_count = command.Split(" ", tokens, false);

        if (token_count < 1)
        {
            return;
        }

        CString action = tokens[0].AsLower();

        if (action == "email"){

            if (token_count < 2)
            {
                PutModule("Email: " + NotificationEmail);
                PutModule("Usage: email <email address>");
                return;
            }

            NotificationEmail = tokens[1].AsLower();

            PutModule("email address set");

        } else if (action == "subject"){

            if (token_count < 2)
            {
                PutModule("Subject: " + NotificationSubject);
                PutModule("Usage: subject <email subject>");
                return;
            }

            NotificationSubject = tokens[1].AsLower();

            PutModule("email subject set.");

        } else if (action == "help") {

                PutModule("View the documentation at...");

        } else {

            if (!DebugMode){
                PutModule("Error: invalid command, try `help`");
            }

        }

        DebugCommands(command);

    }

    void DebugCommands(const CString& command){

        if (!DebugMode){
            return;
        }

        VCString tokens;
        int token_count = command.Split(" ", tokens, false);

        if (token_count < 1)
        {
            return;
        }

        CString action = tokens[0].AsLower();

        if (action == "testemail"){

            CString message;
            message = "This is a testing email.";
            Send(message);

        } else if (action == "testfull"){

            CString message = "Testing";
            MessagesList.push_front(message);
            BatchSend();
        }

    }

    void Handle(CNick& Nick, const CString& location, CString& sMessage){

        if (SendNotification(Nick, sMessage) || location == "PRIVATE"){

            CString message = "<" + location + ":" + Nick.GetNick() + "> " + sMessage + "\n\n";
            MessagesList.push_front(message);

            if (MessagesList.size() > MaxNotifications){
                MessagesList.pop_back();
            }

        }
    }

    bool SendNotification(CNick& Nick, CString& sMessage){

        // Don't send notifications if DebugMode is off and the ConnectedUser is not attached.
        if (!DebugMode && ConnectedUser->IsUserAttached()){
            return false;
        }

        CString UserNick = ConnectedUser->GetNick().AsLower();

        size_t found = sMessage.AsLower().find(UserNick);

        if (found!=string::npos){
            return true;
        } else {
            return false;
        }

    }

    void BatchSend(){

        if (!DebugMode && ConnectedUser->IsUserAttached()){
            return;
        }

        list<CString>::iterator it;

        CString message;

        if (MessagesList.size() <= 0){
            return;
        }

        for ( it=MessagesList.begin() ; it != MessagesList.end(); it++ ){
            message = message + *it;
        }

        Send(message);

        MessagesList.erase(MessagesList.begin(),MessagesList.end());

    }

    void Send(CString& sMessage){

        CString command;
        command = "mail -s '" + NotificationSubject + "' " + NotificationEmail;

        if (DebugMode){
            DebugPrint(command);
        }

        DebugPrint("Sending");

        FILE *email= popen(command.c_str(), "w");

        if (!email){
            PutModule("Problems with mail command.");
            return;
        }

        DebugPrint(sMessage);

        fprintf(email, "%s", (char*) sMessage.c_str());
        pclose(email);

        DebugPrint("Sent");

    }

};

void CMailerTimer::RunJob(){

    CMailer *p = (CMailer *)m_pModule;

    p->BatchSend();

}

MODULEDEFS(CMailer, "To be used to send mentions as an email")
<commit_msg>Added some testing methods to view the queue and trigger the batch job<commit_after>/**
 * ZNC Mailer Module
 *
 * A ZNC Module that uses the Unix mail command to send mentions and private
 * messages to an email address when you are not connected to ZNC.
 *
 * Copyright (c) 2011 Dougal Matthews
 * Licensed under the MIT license
 */

#include <main.h>
#include <string>
#include <stdio.h>
#include <stdlib.h>
#include <list>

#include <Modules.h>
#include <IRCSock.h>
#include <User.h>
#include <Nick.h>
#include <Chan.h>

class CMailerTimer: public CTimer {
public:

    CMailerTimer(CModule* pModule, unsigned int uInterval, unsigned int uCycles, const CString& sLabel, const CString& sDescription) : CTimer(pModule, uInterval, uCycles, sLabel, sDescription) {}
    virtual ~CMailerTimer() {}

protected:
    virtual void RunJob();

};

class CMailer : public CModule {

protected:
    CUser *ConnectedUser;
    list<CString> MessagesList;
    CString NotificationSubject;
    CString NotificationEmail;
    unsigned int MaxNotifications;
    bool DebugMode;

public:

    MODCONSTRUCTOR(CMailer) {
        ConnectedUser = GetUser();
        DebugMode = false;
        NotificationSubject = "IRC Notification";
    }

    virtual ~CMailer() {}

    void DebugPrint(string sMessage){
        if (DebugMode){
            PutModule(sMessage);
        }
    }

    virtual bool OnLoad(const CString& sArgs, CString& sErrorMsg) {

        AddTimer(new CMailerTimer(this, 1200, 0, "Mail", "Send emails every 20 mins."));
        MaxNotifications = 50;

        PutModule("Please tell me what email address you want notifications to be sent to with 'email <address>'");

        VCString tokens;
        int token_count = sArgs.Split(" ", tokens, false);

        if (token_count < 1)
        {
            return true;
        }

        CString action = tokens[0].AsLower();

        if (action == "debug"){
            PutModule("DEBUG ON");
            DebugMode = true;
        }

        return true;

    }

    virtual EModRet OnChanMsg(CNick& Nick, CChan& Channel, CString& sMessage) {

        Handle(Nick, Channel.GetName(), sMessage);

        return CONTINUE;
    }

    virtual EModRet OnPrivMsg(CNick& Nick, CString& sMessage) {

        Handle(Nick, "PRIVATE", sMessage);

        return CONTINUE;
    }

    void OnModCommand(const CString& command)
    {
        VCString tokens;
        int token_count = command.Split(" ", tokens, false);

        if (token_count < 1)
        {
            return;
        }

        CString action = tokens[0].AsLower();

        if (action == "email"){

            if (token_count < 2)
            {
                PutModule("Email: " + NotificationEmail);
                PutModule("Usage: email <email address>");
                return;
            }

            NotificationEmail = tokens[1].AsLower();

            PutModule("email address set");

        } else if (action == "subject"){

            if (token_count < 2)
            {
                PutModule("Subject: " + NotificationSubject);
                PutModule("Usage: subject <email subject>");
                return;
            }

            NotificationSubject = tokens[1].AsLower();

            PutModule("email subject set.");

        } else if (action == "help") {

                PutModule("View the documentation at...");

        } else {

            if (!DebugMode){
                PutModule("Error: invalid command, try `help`");
            }

        }

        DebugCommands(command);

    }

    void DebugCommands(const CString& command){

        if (!DebugMode){
            return;
        }

        VCString tokens;
        int token_count = command.Split(" ", tokens, false);

        if (token_count < 1)
        {
            return;
        }

        CString action = tokens[0].AsLower();

        if (action == "testemail"){

            CString message;
            message = "This is a testing email.";
            Send(message);

        } else if (action == "testfull"){

            CString message = "Testing";
            MessagesList.push_front(message);
            BatchSend();
        } else if (action == "testshowqueue"){

            list<CString>::iterator it;

            CString message;

            for ( it=MessagesList.begin() ; it != MessagesList.end(); it++ ){
                DebugPrint(*it);
            }

        } else if (action == "testbatchsend"){

            BatchSend();

        }

    }

    void Handle(CNick& Nick, const CString& location, CString& sMessage){

        if (SendNotification(Nick, sMessage) || location == "PRIVATE"){

            CString message = "<" + location + ":" + Nick.GetNick() + "> " + sMessage + "\n\n";
            MessagesList.push_front(message);

            DebugPrint("Added message...");
            DebugPrint(message);

            if (MessagesList.size() > MaxNotifications){
                MessagesList.pop_back();
            }

        }
    }

    bool SendNotification(CNick& Nick, CString& sMessage){

        // Don't send notifications if DebugMode is off and the ConnectedUser is not attached.
        if (!DebugMode && ConnectedUser->IsUserAttached()){
            return false;
        }

        CString UserNick = ConnectedUser->GetNick().AsLower();

        size_t found = sMessage.AsLower().find(UserNick);

        if (found!=string::npos){
            return true;
        } else {
            return false;
        }

    }

    void BatchSend(){

        if (!DebugMode && ConnectedUser->IsUserAttached()){
            return;
        }

        list<CString>::iterator it;

        CString message;

        if (MessagesList.size() <= 0){
            return;
        }

        for ( it=MessagesList.begin() ; it != MessagesList.end(); it++ ){
            message = message + *it;
        }

        Send(message);

        MessagesList.erase(MessagesList.begin(),MessagesList.end());

    }

    void Send(CString& sMessage){

        CString command;
        command = "mail -s '" + NotificationSubject + "' " + NotificationEmail;

        if (DebugMode){
            DebugPrint(command);
        }

        DebugPrint("Sending");

        FILE *email= popen(command.c_str(), "w");

        if (!email){
            PutModule("Problems with mail command.");
            return;
        }

        fprintf(email, "%s", (char*) sMessage.c_str());
        pclose(email);

        DebugPrint(sMessage);
        DebugPrint("Sent");

    }

};

void CMailerTimer::RunJob(){

    CMailer *p = (CMailer *)m_pModule;

    p->BatchSend();

}

MODULEDEFS(CMailer, "To be used to send mentions as an email")
<|endoftext|>


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

  Library: CTK

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

#include "ctkTrackedService_p.h"

#include "ctkPluginContext.h"
#include "ctkPluginConstants.h"
#include "ctkLDAPSearchFilter.h"

#include <stdexcept>

template<class S, class T>
const bool ctkServiceTrackerPrivate<S,T>::DEBUG	= true;

template<class S, class T>
ctkServiceTrackerPrivate<S,T>::ctkServiceTrackerPrivate(
    ctkServiceTracker<S,T>* st, ctkPluginContext* context,
    const ctkServiceReference& reference,
    ctkServiceTrackerCustomizer<T>* customizer)
  : context(context), customizer(customizer), trackReference(reference),
    trackedService(0), cachedReference(0), cachedService(0), q_ptr(st)
{
  this->customizer = customizer ? customizer : q_func();
  this->listenerFilter = QString("(") + ctkPluginConstants::SERVICE_ID +
                         "=" + reference.getProperty(ctkPluginConstants::SERVICE_ID).toString() + ")";
  try
  {
    this->filter = ctkLDAPSearchFilter(listenerFilter);
  }
  catch (const std::invalid_argument& e)
  {
    /*
     * we could only get this exception if the ServiceReference was
     * invalid
     */
    std::invalid_argument ia(std::string("unexpected std::invalid_argument exception: ") + e.what());
    throw ia;
  }
}

template<class S, class T>
ctkServiceTrackerPrivate<S,T>::ctkServiceTrackerPrivate(
    ctkServiceTracker<S,T>* st,
    ctkPluginContext* context, const QString& clazz,
    ctkServiceTrackerCustomizer<T>* customizer)
      : context(context), customizer(customizer), trackClass(clazz),
        trackReference(0), trackedService(0), cachedReference(0),
        cachedService(0), q_ptr(st)
{
  this->customizer = customizer ? customizer : q_func();
  this->listenerFilter = QString("(") + ctkPluginConstants::OBJECTCLASS + "="
                        + clazz + ")";
  try
  {
    this->filter = ctkLDAPSearchFilter(listenerFilter);
  }
  catch (const std::invalid_argument& e)
  {
    /*
     * we could only get this exception if the clazz argument was
     * malformed
     */
    std::invalid_argument ia(
        std::string("unexpected std::invalid_argument exception: ") + e.what());
    throw ia;
  }
}

template<class S, class T>
ctkServiceTrackerPrivate<S,T>::ctkServiceTrackerPrivate(
    ctkServiceTracker<S,T>* st,
    ctkPluginContext* context, const ctkLDAPSearchFilter& filter,
    ctkServiceTrackerCustomizer<T>* customizer)
      : context(context), filter(filter), customizer(customizer),
        listenerFilter(filter.toString()), trackReference(0),
        trackedService(0), cachedReference(0), cachedService(0), q_ptr(st)
{
  this->customizer = customizer ? customizer : q_func();
  if (context == 0)
  {
    throw std::invalid_argument("The plugin context cannot be null.");
  }
}

template<class S, class T>
ctkServiceTrackerPrivate<S,T>::~ctkServiceTrackerPrivate()
{

}

template<class S, class T>
QList<ctkServiceReference> ctkServiceTrackerPrivate<S,T>::getInitialReferences(const QString& className,
                                                const QString& filterString)
{
  return context->getServiceReferences(className, filterString);
}

template<class S, class T>
QSharedPointer<ctkTrackedService<S,T> > ctkServiceTrackerPrivate<S,T>::tracked() const
{
  return trackedService;
}

template<class S, class T>
void ctkServiceTrackerPrivate<S,T>::modified()
{
  cachedReference = 0; /* clear cached value */
  cachedService = 0; /* clear cached value */
  if (DEBUG)
  {
    qDebug() << "ctkServiceTracker::modified:" << filter;
  }
}
<commit_msg>Disabling debug output of ctkServiceTracker.<commit_after>/*=============================================================================

  Library: CTK

  Copyright (c) German Cancer Research Center,
    Division of Medical and Biological Informatics

  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.

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

#include "ctkTrackedService_p.h"

#include "ctkPluginContext.h"
#include "ctkPluginConstants.h"
#include "ctkLDAPSearchFilter.h"

#include <stdexcept>

template<class S, class T>
const bool ctkServiceTrackerPrivate<S,T>::DEBUG = false;

template<class S, class T>
ctkServiceTrackerPrivate<S,T>::ctkServiceTrackerPrivate(
    ctkServiceTracker<S,T>* st, ctkPluginContext* context,
    const ctkServiceReference& reference,
    ctkServiceTrackerCustomizer<T>* customizer)
  : context(context), customizer(customizer), trackReference(reference),
    trackedService(0), cachedReference(0), cachedService(0), q_ptr(st)
{
  this->customizer = customizer ? customizer : q_func();
  this->listenerFilter = QString("(") + ctkPluginConstants::SERVICE_ID +
                         "=" + reference.getProperty(ctkPluginConstants::SERVICE_ID).toString() + ")";
  try
  {
    this->filter = ctkLDAPSearchFilter(listenerFilter);
  }
  catch (const std::invalid_argument& e)
  {
    /*
     * we could only get this exception if the ServiceReference was
     * invalid
     */
    std::invalid_argument ia(std::string("unexpected std::invalid_argument exception: ") + e.what());
    throw ia;
  }
}

template<class S, class T>
ctkServiceTrackerPrivate<S,T>::ctkServiceTrackerPrivate(
    ctkServiceTracker<S,T>* st,
    ctkPluginContext* context, const QString& clazz,
    ctkServiceTrackerCustomizer<T>* customizer)
      : context(context), customizer(customizer), trackClass(clazz),
        trackReference(0), trackedService(0), cachedReference(0),
        cachedService(0), q_ptr(st)
{
  this->customizer = customizer ? customizer : q_func();
  this->listenerFilter = QString("(") + ctkPluginConstants::OBJECTCLASS + "="
                        + clazz + ")";
  try
  {
    this->filter = ctkLDAPSearchFilter(listenerFilter);
  }
  catch (const std::invalid_argument& e)
  {
    /*
     * we could only get this exception if the clazz argument was
     * malformed
     */
    std::invalid_argument ia(
        std::string("unexpected std::invalid_argument exception: ") + e.what());
    throw ia;
  }
}

template<class S, class T>
ctkServiceTrackerPrivate<S,T>::ctkServiceTrackerPrivate(
    ctkServiceTracker<S,T>* st,
    ctkPluginContext* context, const ctkLDAPSearchFilter& filter,
    ctkServiceTrackerCustomizer<T>* customizer)
      : context(context), filter(filter), customizer(customizer),
        listenerFilter(filter.toString()), trackReference(0),
        trackedService(0), cachedReference(0), cachedService(0), q_ptr(st)
{
  this->customizer = customizer ? customizer : q_func();
  if (context == 0)
  {
    throw std::invalid_argument("The plugin context cannot be null.");
  }
}

template<class S, class T>
ctkServiceTrackerPrivate<S,T>::~ctkServiceTrackerPrivate()
{

}

template<class S, class T>
QList<ctkServiceReference> ctkServiceTrackerPrivate<S,T>::getInitialReferences(const QString& className,
                                                const QString& filterString)
{
  return context->getServiceReferences(className, filterString);
}

template<class S, class T>
QSharedPointer<ctkTrackedService<S,T> > ctkServiceTrackerPrivate<S,T>::tracked() const
{
  return trackedService;
}

template<class S, class T>
void ctkServiceTrackerPrivate<S,T>::modified()
{
  cachedReference = 0; /* clear cached value */
  cachedService = 0; /* clear cached value */
  if (DEBUG)
  {
    qDebug() << "ctkServiceTracker::modified:" << filter;
  }
}
<|endoftext|>


<commit_before>// Test for the leak_check_at_exit flag.
// RUN: LSAN_BASE="use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -o %t
// RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do
// RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-do
// RUN: LSAN_OPTIONS=$LSAN_BASE:"leak_check_at_exit=0" not %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do
// RUN: LSAN_OPTIONS=%LSAN_BASE:"leak_check_at_exit=0" %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-dont

#include <stdio.h>
#include <stdlib.h>
#include <sanitizer/lsan_interface.h>

int main(int argc, char *argv[]) {
  fprintf(stderr, "Test alloc: %p.\n", malloc(1337));
  if (argc > 1)
    __lsan_do_leak_check();
  return 0;
}

// CHECK-do: SUMMARY: {{(Leak|Address)}}Sanitizer:
// CHECK-dont-NOT: SUMMARY: {{(Leak|Address)}}Sanitizer:
<commit_msg>[lsan] Fix a typo in a test.<commit_after>// Test for the leak_check_at_exit flag.
// RUN: LSAN_BASE="use_stacks=0:use_registers=0"
// RUN: %clangxx_lsan %s -o %t
// RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do
// RUN: LSAN_OPTIONS=$LSAN_BASE not %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-do
// RUN: LSAN_OPTIONS=$LSAN_BASE:"leak_check_at_exit=0" not %run %t foo 2>&1 | FileCheck %s --check-prefix=CHECK-do
// RUN: LSAN_OPTIONS=$LSAN_BASE:"leak_check_at_exit=0" %run %t 2>&1 | FileCheck %s --check-prefix=CHECK-dont

#include <stdio.h>
#include <stdlib.h>
#include <sanitizer/lsan_interface.h>

int main(int argc, char *argv[]) {
  fprintf(stderr, "Test alloc: %p.\n", malloc(1337));
  if (argc > 1)
    __lsan_do_leak_check();
  return 0;
}

// CHECK-do: SUMMARY: {{(Leak|Address)}}Sanitizer:
// CHECK-dont-NOT: SUMMARY: {{(Leak|Address)}}Sanitizer:
<|endoftext|>


<commit_before>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "PlatformAbstractionsFacade.h"

namespace ExampleApp
{
    PlatformAbstractionsFacade::PlatformAbstractionsFacade(Eegeo::Modules::IPlatformAbstractionModule& wrappedPlatformAbstractions,
                                                           Net::SdkModel::INetworkCapabilities& networkCapabilities)
    : m_wrappedPlatformAbstractions(wrappedPlatformAbstractions)
    , m_pWebLoadRequestFactory(NULL)
    , m_pPlatformWebLoadRequestFactory(NULL)
    {

        m_pWebLoadRequestFactory = Eegeo_NEW(ExampleApp::Net::SdkModel::ExampleAppCustomWebLoadRequestFactory)(wrappedPlatformAbstractions.GetHttpCache(),
                                                                                wrappedPlatformAbstractions.GetWebLoadRequestFactory(),
                                                                                networkCapabilities);

        m_pPlatformWebLoadRequestFactory = Eegeo_NEW(ExampleApp::Net::SdkModel::ExampleAppCustomWebLoadRequestFactory)(wrappedPlatformAbstractions.GetHttpCache(),
                                                                                wrappedPlatformAbstractions.GetPlatformWebLoadRequestFactory(),
                                                                                networkCapabilities);
    }

    PlatformAbstractionsFacade::~PlatformAbstractionsFacade()
    {
        Eegeo_DELETE m_pPlatformWebLoadRequestFactory;
        Eegeo_DELETE m_pWebLoadRequestFactory;
    }

    Eegeo::Helpers::ITextureFileLoader& PlatformAbstractionsFacade::GetTextureFileLoader() const
    {
        return m_wrappedPlatformAbstractions.GetTextureFileLoader();
    }

    Eegeo::Web::IWebLoadRequestFactory& PlatformAbstractionsFacade::GetWebLoadRequestFactory() const
    {
        return *m_pWebLoadRequestFactory;
    }

    Eegeo::Web::IWebLoadRequestFactory& PlatformAbstractionsFacade::GetPlatformWebLoadRequestFactory() const
    {
        return *m_pPlatformWebLoadRequestFactory;
    }

    Eegeo::Helpers::IHttpCache& PlatformAbstractionsFacade::GetHttpCache() const
    {
        return m_wrappedPlatformAbstractions.GetHttpCache();
    }

    Eegeo::Helpers::IFileIO& PlatformAbstractionsFacade::GetFileIO() const
    {
        return m_wrappedPlatformAbstractions.GetFileIO();
    }

    Eegeo::Helpers::UrlHelpers::IUrlEncoder& PlatformAbstractionsFacade::GetUrlEncoder() const
    {
        return m_wrappedPlatformAbstractions.GetUrlEncoder();
    }

    Eegeo::Concurrency::Tasks::IGlTaskContextFactory& PlatformAbstractionsFacade::GetGlTaskContextFactory() const
    {
        return m_wrappedPlatformAbstractions.GetGlTaskContextFactory();
    }

    Eegeo::Helpers::IResourceCacheCleaner& PlatformAbstractionsFacade::GetResourceCacheCleaner() const
    {
        return m_wrappedPlatformAbstractions.GetResourceCacheCleaner();
    }

    Eegeo::Web::IConnectivityService& PlatformAbstractionsFacade::GetConnectivityService() const
    {
        return m_wrappedPlatformAbstractions.GetConnectivityService();
    }

    void PlatformAbstractionsFacade::OnPause()
    {
        return m_wrappedPlatformAbstractions.OnPause();
    }

    void PlatformAbstractionsFacade::Update()
    {
        return m_wrappedPlatformAbstractions.Update();
    }

    void PlatformAbstractionsFacade::OnResume()
    {
        return m_wrappedPlatformAbstractions.OnResume();
    }
}
<commit_msg>Fix missing include<commit_after>// Copyright eeGeo Ltd (2012-2015), All Rights Reserved

#include "PlatformAbstractionsFacade.h"
#include "IConnectivityService.h"

namespace ExampleApp
{
    PlatformAbstractionsFacade::PlatformAbstractionsFacade(Eegeo::Modules::IPlatformAbstractionModule& wrappedPlatformAbstractions,
                                                           Net::SdkModel::INetworkCapabilities& networkCapabilities)
    : m_wrappedPlatformAbstractions(wrappedPlatformAbstractions)
    , m_pWebLoadRequestFactory(NULL)
    , m_pPlatformWebLoadRequestFactory(NULL)
    {

        m_pWebLoadRequestFactory = Eegeo_NEW(ExampleApp::Net::SdkModel::ExampleAppCustomWebLoadRequestFactory)(wrappedPlatformAbstractions.GetHttpCache(),
                                                                                wrappedPlatformAbstractions.GetWebLoadRequestFactory(),
                                                                                networkCapabilities);

        m_pPlatformWebLoadRequestFactory = Eegeo_NEW(ExampleApp::Net::SdkModel::ExampleAppCustomWebLoadRequestFactory)(wrappedPlatformAbstractions.GetHttpCache(),
                                                                                wrappedPlatformAbstractions.GetPlatformWebLoadRequestFactory(),
                                                                                networkCapabilities);
    }

    PlatformAbstractionsFacade::~PlatformAbstractionsFacade()
    {
        Eegeo_DELETE m_pPlatformWebLoadRequestFactory;
        Eegeo_DELETE m_pWebLoadRequestFactory;
    }

    Eegeo::Helpers::ITextureFileLoader& PlatformAbstractionsFacade::GetTextureFileLoader() const
    {
        return m_wrappedPlatformAbstractions.GetTextureFileLoader();
    }

    Eegeo::Web::IWebLoadRequestFactory& PlatformAbstractionsFacade::GetWebLoadRequestFactory() const
    {
        return *m_pWebLoadRequestFactory;
    }

    Eegeo::Web::IWebLoadRequestFactory& PlatformAbstractionsFacade::GetPlatformWebLoadRequestFactory() const
    {
        return *m_pPlatformWebLoadRequestFactory;
    }

    Eegeo::Helpers::IHttpCache& PlatformAbstractionsFacade::GetHttpCache() const
    {
        return m_wrappedPlatformAbstractions.GetHttpCache();
    }

    Eegeo::Helpers::IFileIO& PlatformAbstractionsFacade::GetFileIO() const
    {
        return m_wrappedPlatformAbstractions.GetFileIO();
    }

    Eegeo::Helpers::UrlHelpers::IUrlEncoder& PlatformAbstractionsFacade::GetUrlEncoder() const
    {
        return m_wrappedPlatformAbstractions.GetUrlEncoder();
    }

    Eegeo::Concurrency::Tasks::IGlTaskContextFactory& PlatformAbstractionsFacade::GetGlTaskContextFactory() const
    {
        return m_wrappedPlatformAbstractions.GetGlTaskContextFactory();
    }

    Eegeo::Helpers::IResourceCacheCleaner& PlatformAbstractionsFacade::GetResourceCacheCleaner() const
    {
        return m_wrappedPlatformAbstractions.GetResourceCacheCleaner();
    }

    Eegeo::Web::IConnectivityService& PlatformAbstractionsFacade::GetConnectivityService() const
    {
        return m_wrappedPlatformAbstractions.GetConnectivityService();
    }

    void PlatformAbstractionsFacade::OnPause()
    {
        return m_wrappedPlatformAbstractions.OnPause();
    }

    void PlatformAbstractionsFacade::Update()
    {
        return m_wrappedPlatformAbstractions.Update();
    }

    void PlatformAbstractionsFacade::OnResume()
    {
        return m_wrappedPlatformAbstractions.OnResume();
    }
}
<|endoftext|>


<commit_before>#ifndef KMC_KLANG_LEXICAL_ANALYSIS_HPP
#define KMC_KLANG_LEXICAL_ANALYSIS_HPP

#include <fstream>
#include <string>
#include <vector>

namespace klang {

enum class TokenType {
  IDENTIFIER,
  DIGIT,
  RESERVED,
  CHARACTER,
  STRING
};

class Token {
 public:
  Token();
  Token(TokenType type, const std::string& str, int line);
  TokenType type() const;
  std::string str() const;
  int number() const;
  int line() const;
 private:
  TokenType type_;
  std::string str_;
  int number_;
  int line_;
};

class TokenVector {
 public:
  bool unget_token(int times = 1);
  bool next_token();
  bool push_token(Token token);
  Token get_token() const;
  TokenType current_type() const;
  std::string current_string() const;
  int current_value() const;
  int current_index() const;
  bool set_index(int index);
  bool print_tokens() const;
 private:
  std::vector<Token> tokens_;
  int current_index_;
};

TokenVector LexicalAnalysis(std::ifstream& is);

}  // klang

#endif  // KMC_KLANG_LEXICAL_ANALYSIS_HPP
<commit_msg>number_メンバを削除。<commit_after>#ifndef KMC_KLANG_LEXICAL_ANALYSIS_HPP
#define KMC_KLANG_LEXICAL_ANALYSIS_HPP

#include <fstream>
#include <string>
#include <vector>

namespace klang {

enum class TokenType {
  IDENTIFIER,
  DIGIT,
  RESERVED,
  CHARACTER,
  STRING
};

class Token {
 public:
  Token();
  Token(TokenType type, const std::string& str, int line);
  TokenType type() const;
  std::string str() const;
  int line() const;
 private:
  TokenType type_;
  std::string str_;
  int line_;
};

class TokenVector {
 public:
  bool unget_token(int times = 1);
  bool next_token();
  bool push_token(Token token);
  Token get_token() const;
  TokenType current_type() const;
  std::string current_string() const;
  int current_value() const;
  int current_index() const;
  bool set_index(int index);
  bool print_tokens() const;
 private:
  std::vector<Token> tokens_;
  int current_index_;
};

TokenVector LexicalAnalysis(std::ifstream& is);

}  // klang

#endif  // KMC_KLANG_LEXICAL_ANALYSIS_HPP
<|endoftext|>


<commit_before>#include "OptixRender.h"
#include "../Scene/proto_camera.h"
//#include "../Kernel.h"
//#include "../File/TextureLoader.h"

#include "../Render/Passes/GBuffer/GBuffer_Pass.h"

#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <iostream>

using namespace Raytracer;
using namespace optix;

OptixRender::OptixRender(const Render::GBuffer_PassPtr &g_buffer_pass, unsigned int w, unsigned int h, const std::string& baseDir)
	: g_buffer_pass(g_buffer_pass), w(w), h(h), baseDir(baseDir)
{
    GLenum error = glGetError();
	tex = std::make_shared<Render::Tex2D>();
    error = glGetError();
    Render::T2DTexParams params((unsigned int)GL_BGRA, (unsigned int)GL_BGRA, (unsigned int)GL_UNSIGNED_BYTE, 4, (unsigned int)w, (unsigned int)h, (unsigned int)GL_CLAMP_TO_EDGE, (unsigned char*)nullptr);
    error = glGetError();
	tex->update(params);
    error = glGetError();

    context  = createContext();
    sphere   = createGeometry( context );
    material = createMaterial( context );
    createInstance( context, sphere, material );
	//createTextureSamplers( context );

    // Run
	try{
    context->validate();
    context->compile();
    //context->launch( 0, w, h);
	}catch(const optix::Exception &e){
	}
}

void OptixRender::_displayFrame( Buffer buffer )
{
  // Draw the resulting image
  RTsize buffer_width_rts, buffer_height_rts;
  buffer->getSize( buffer_width_rts, buffer_height_rts );
  int buffer_width  = static_cast<int>(buffer_width_rts);
  int buffer_height = static_cast<int>(buffer_height_rts);
  RTformat buffer_format = buffer->getFormat();

  auto buf = (unsigned char*)buffer->map();
  std::vector<unsigned char> imageData(buf, buf + buffer_width*buffer_height*4*sizeof(unsigned char));

    //assert( &imageData[0] );

    GLenum gl_data_type = GL_FALSE;
    GLenum gl_format = GL_FALSE;

    switch (buffer_format) {
          case RT_FORMAT_UNSIGNED_BYTE4:
            gl_data_type = GL_UNSIGNED_BYTE;
            gl_format    = GL_BGRA;
            break;

          case RT_FORMAT_FLOAT:
            gl_data_type = GL_FLOAT;
            break;

          case RT_FORMAT_FLOAT3:
            gl_data_type = GL_FLOAT;
            gl_format    = GL_RGB;
            break;

          case RT_FORMAT_FLOAT4:
            gl_data_type = GL_FLOAT;
            gl_format    = GL_RGBA;
            break;

          default:
            fprintf(stderr, "Unrecognized buffer data type or format.\n");
            exit(2);
            break;
    }

	Render::T2DTexParams params((unsigned int)gl_format, (unsigned int)gl_format, (unsigned int)gl_data_type, 4, (unsigned int)buffer_width, (unsigned int)buffer_height, (unsigned int)GL_CLAMP_TO_EDGE, (unsigned char*)&imageData[0]);
	tex->update(params);

	//Kernel::getSingleton()->getTextureLoader()->save(tex, Kernel::getSingleton()->getResourceDir()+"screens\\raytraced.png");

    /*static GLuint idk = 0;
    if ( !idk ) {
      glGenTextures(1, &idk );
    }
    glBindTexture( GL_TEXTURE_2D, idk );
    // Change these to GL_LINEAR for super- or sub-sampling
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    // GL_CLAMP_TO_EDGE for linear filtering, not relevant for nearest.
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, buffer_width, buffer_height, gl_format, gl_data_type, imageData );*/
    //glDrawPixels( static_cast<GLsizei>( buffer_width),
      //static_cast<GLsizei>( buffer_height ),
      //gl_format, gl_data_type, imageData);

    buffer->unmap();
}

// C++ version of sutil.c code
void CalculateCameraVariables(  glm::vec3 eye, glm::vec3 lookAt, glm::vec3 up,
                                float hfov,
                                float aspect_ratio,
                                glm::vec3& U,
                                glm::vec3& V,
                                glm::vec3& W )
{

  W = lookAt - eye;  /* Do not normalize W -- it implies focal length */
  U = glm::normalize( glm::cross(W, up) );
  V = glm::normalize( glm::cross( U, W ) );
  float wlen = sqrtf( glm::dot( W, W ) );
  float ulen = wlen * tanf( hfov / 2.0f * 3.14159265358979323846f / 180.0f );
  float vlen =  ulen/aspect_ratio;
  U *= ulen;
  V *= vlen;
}

void CalculateCameraVariables(  float hfov,
                                float aspect_ratio,
                                glm::vec3& U,
                                glm::vec3& V,
                                glm::vec3& W )
{
    auto &cam = Scene::FirstPersonCamera::getSingleton();
    glm::vec3 side = cam->getStrafeDirection();
    glm::vec3 up = cam->getUpDirection();
    glm::vec3 fwd = cam->getLookDirection();

    // set up the coordinate system
    W = fwd;//glm::normalize (fwd);
    U = side;//glm::normalize (glm::cross(up, W));
    V = up;//glm::normalize (glm::cross(W, U));

    float wlen = sqrtf( glm::dot( W, W ) );
    float ulen = wlen * tanf( glm::radians(hfov) / 2.0f );
    U *= ulen;
    float vlen = ulen/aspect_ratio;
    V *= vlen;
}

void OptixRender::render()
{
  //unsigned int pbo = context["output_buffer"]->getBuffer()->getGLBOId(); // not a pbo!
	auto camera = Scene::FirstPersonCamera::getSingleton();
	auto &world_to_view = camera->getWorldToViewMatrix();
	auto pos = camera->getPos();

    float aspect_ratio = static_cast<float>(w) / static_cast<float>(h);
    float inv_aspect_ratio = static_cast<float>(h) / static_cast<float>(w);

    float vfov = camera->getFov();
    float hfov = vfov * aspect_ratio;

    glm::vec3 U,V,W;
    //CalculateCameraVariables( hfov, aspect_ratio, U, V, W );
    CalculateCameraVariables( pos, pos+camera->getLookDirection(), camera->getUpDirection(), hfov, aspect_ratio, U, V, W );

    context["eye"]->set3fv( glm::value_ptr(pos) );
    context["U"]->set3fv( glm::value_ptr(U) );
    context["V"]->set3fv( glm::value_ptr(V) );
    context["W"]->set3fv( glm::value_ptr(W) );

	try {
		context->launch(0, w,h);
	} catch (optix::Exception& e) {
		std::cout << e.getErrorString();
		return;
	}
	_displayFrame( context["output_buffer"]->getBuffer() );
	//glClearColor(1,0,0,0);
}

void OptixRender::reshape(unsigned int w, unsigned int h)
{
	this->w = w;
	this->h = h;
}

Context OptixRender::createContext()
{
  // Set up context
  Context context = Context::create();
  context->setRayTypeCount( 1 );
  context->setEntryPointCount( 1 );

  context["radiance_ray_type"]->setUint( 0u );
  context["scene_epsilon"]->setFloat( 1.e-4f );

  Variable output_buffer = context["output_buffer"];
  Buffer buffer = context->createBuffer( RT_BUFFER_OUTPUT, RT_FORMAT_UNSIGNED_BYTE4, w, h );

  output_buffer->set(buffer);

  // Ray generation program
  std::string ptx_path( baseDir + "pinhole_camera.cu.ptx" );
  try{
	Program ray_gen_program = context->createProgramFromPTXFile( ptx_path, "pinhole_camera" );
	context->setRayGenerationProgram( 0, ray_gen_program );
  }catch(optix::Exception &e)
  {
      std::string w(e.what());
      std::cout << w << std::endl;
  }

  // Exception program
  Program exception_program = context->createProgramFromPTXFile( ptx_path, "exception" );
  context->setExceptionProgram( 0, exception_program );
  context["bad_color"]->setFloat( 1.0f, 1.0f, 0.0f );

  // Miss program
  ptx_path = baseDir + "constantbg.cu.ptx";
  context->setMissProgram( 0, context->createProgramFromPTXFile( ptx_path, "miss" ) );
  context["bg_color"]->setFloat( 0.3f, 0.1f, 0.2f );

  return context;
}

Geometry OptixRender::createGeometry( Context context )
{
  Geometry sphere = context->createGeometry();
  sphere->setPrimitiveCount( 1u );
  sphere->setBoundingBoxProgram( context->createProgramFromPTXFile( baseDir + "sphere.cu.ptx", "bounds" ) );
  sphere->setIntersectionProgram( context->createProgramFromPTXFile( baseDir + "sphere.cu.ptx", "intersect" ) );
  //sphere["sphere"]->setFloat( 0.f, 0.f, 0.f, 1.0f );
  sphere["sphere"]->setFloat( 5, 3, -20.0f, 1.0f );
  return sphere;
}

Material OptixRender::createMaterial( Context context )
{
    Program chp = context->createProgramFromPTXFile( baseDir + "normal_shader.cu.ptx" , "closest_hit_radiance" );

  Material matl = context->createMaterial();
  matl->setClosestHitProgram( 0, chp );
  return matl;
}

void OptixRender::createInstance( Context context, Geometry sphere, Material material )
{
  // Create geometry instance
  GeometryInstance gi = context->createGeometryInstance();
  gi->setMaterialCount( 1 );
  gi->setGeometry( sphere );
  gi->setMaterial( 0, material );

  // Create geometry group
  GeometryGroup geometrygroup = context->createGeometryGroup();
  geometrygroup->setChildCount( 1 );
  geometrygroup->setChild( 0, gi );
  geometrygroup->setAcceleration( context->createAcceleration("NoAccel","NoAccel") );

  context["top_object"]->set( geometrygroup );
}

void OptixRender::createTextureSamplers( optix::Context context )
{
	//Upload rasterized g-buffer info here:
	auto raster_fbo = g_buffer_pass->getFBO();
	auto raster_diffuse = raster_fbo->getRenderTexture(0);
	auto raster_position = raster_fbo->getRenderTexture(1);
	auto raster_normal = raster_fbo->getRenderTexture(2);
	//TODO: Upload to optix!
	addTextureSampler(raster_diffuse_sampler, raster_diffuse->getHandle(), 1.0f, "raster_diffuse");
	addTextureSampler(raster_position_sampler, raster_position->getHandle(), 1.0f, "raster_position");
	addTextureSampler(raster_normal_sampler, raster_normal->getHandle(), 1.0f, "raster_normal");
}

void OptixRender::addTextureSampler(optix::TextureSampler sampler, unsigned int gl_tex_handle, float max_anisotropy, const std::string &sampler_name)
{
	sampler = context->createTextureSamplerFromGLImage( gl_tex_handle, RT_TARGET_GL_TEXTURE_2D );
	sampler->setWrapMode( 0, RT_WRAP_REPEAT );
	sampler->setWrapMode( 1, RT_WRAP_REPEAT );
	sampler->setWrapMode( 2, RT_WRAP_REPEAT );
	sampler->setIndexingMode( RT_TEXTURE_INDEX_NORMALIZED_COORDINATES );
	sampler->setReadMode( RT_TEXTURE_READ_NORMALIZED_FLOAT );
	sampler->setMaxAnisotropy( max_anisotropy );
	sampler->setFilteringModes( RT_FILTER_LINEAR, RT_FILTER_LINEAR, RT_FILTER_NONE );

	context[sampler_name.c_str()]->setTextureSampler( sampler );
}
<commit_msg>clamp to edge<commit_after>#include "OptixRender.h"
#include "../Scene/proto_camera.h"
//#include "../Kernel.h"
//#include "../File/TextureLoader.h"

#include "../Render/Passes/GBuffer/GBuffer_Pass.h"

#include <glm/glm.hpp>
#include <glm/ext.hpp>
#include <iostream>

using namespace Raytracer;
using namespace optix;

OptixRender::OptixRender(const Render::GBuffer_PassPtr &g_buffer_pass, unsigned int w, unsigned int h, const std::string& baseDir)
	: g_buffer_pass(g_buffer_pass), w(w), h(h), baseDir(baseDir)
{
    GLenum error = glGetError();
	tex = std::make_shared<Render::Tex2D>();
    error = glGetError();
    Render::T2DTexParams params((unsigned int)GL_BGRA, (unsigned int)GL_BGRA, (unsigned int)GL_UNSIGNED_BYTE, 4, (unsigned int)w, (unsigned int)h, (unsigned int)GL_CLAMP_TO_EDGE, (unsigned char*)nullptr);
    error = glGetError();
	tex->update(params);
    error = glGetError();

    context  = createContext();
    sphere   = createGeometry( context );
    material = createMaterial( context );
    createInstance( context, sphere, material );
	//createTextureSamplers( context );

    // Run
	try{
    context->validate();
    context->compile();
    //context->launch( 0, w, h);
	}catch(const optix::Exception &e){
	}
}

void OptixRender::_displayFrame( Buffer buffer )
{
  // Draw the resulting image
  RTsize buffer_width_rts, buffer_height_rts;
  buffer->getSize( buffer_width_rts, buffer_height_rts );
  int buffer_width  = static_cast<int>(buffer_width_rts);
  int buffer_height = static_cast<int>(buffer_height_rts);
  RTformat buffer_format = buffer->getFormat();

  auto buf = (unsigned char*)buffer->map();
  std::vector<unsigned char> imageData(buf, buf + buffer_width*buffer_height*4*sizeof(unsigned char));

    //assert( &imageData[0] );

    GLenum gl_data_type = GL_FALSE;
    GLenum gl_format = GL_FALSE;

    switch (buffer_format) {
          case RT_FORMAT_UNSIGNED_BYTE4:
            gl_data_type = GL_UNSIGNED_BYTE;
            gl_format    = GL_BGRA;
            break;

          case RT_FORMAT_FLOAT:
            gl_data_type = GL_FLOAT;
            break;

          case RT_FORMAT_FLOAT3:
            gl_data_type = GL_FLOAT;
            gl_format    = GL_RGB;
            break;

          case RT_FORMAT_FLOAT4:
            gl_data_type = GL_FLOAT;
            gl_format    = GL_RGBA;
            break;

          default:
            fprintf(stderr, "Unrecognized buffer data type or format.\n");
            exit(2);
            break;
    }

	Render::T2DTexParams params((unsigned int)gl_format, (unsigned int)gl_format, (unsigned int)gl_data_type, 4, (unsigned int)buffer_width, (unsigned int)buffer_height, (unsigned int)GL_CLAMP_TO_EDGE, (unsigned char*)&imageData[0]);
	tex->update(params);

	//Kernel::getSingleton()->getTextureLoader()->save(tex, Kernel::getSingleton()->getResourceDir()+"screens\\raytraced.png");

    /*static GLuint idk = 0;
    if ( !idk ) {
      glGenTextures(1, &idk );
    }
    glBindTexture( GL_TEXTURE_2D, idk );
    // Change these to GL_LINEAR for super- or sub-sampling
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    // GL_CLAMP_TO_EDGE for linear filtering, not relevant for nearest.
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);

    glTexSubImage2D( GL_TEXTURE_2D, 0, 0, 0, buffer_width, buffer_height, gl_format, gl_data_type, imageData );*/
    //glDrawPixels( static_cast<GLsizei>( buffer_width),
      //static_cast<GLsizei>( buffer_height ),
      //gl_format, gl_data_type, imageData);

    buffer->unmap();
}

// C++ version of sutil.c code
void CalculateCameraVariables(  glm::vec3 eye, glm::vec3 lookAt, glm::vec3 up,
                                float hfov,
                                float aspect_ratio,
                                glm::vec3& U,
                                glm::vec3& V,
                                glm::vec3& W )
{

  W = lookAt - eye;  /* Do not normalize W -- it implies focal length */
  U = glm::normalize( glm::cross(W, up) );
  V = glm::normalize( glm::cross( U, W ) );
  float wlen = sqrtf( glm::dot( W, W ) );
  float ulen = wlen * tanf( hfov / 2.0f * 3.14159265358979323846f / 180.0f );
  float vlen =  ulen/aspect_ratio;
  U *= ulen;
  V *= vlen;
}

void CalculateCameraVariables(  float hfov,
                                float aspect_ratio,
                                glm::vec3& U,
                                glm::vec3& V,
                                glm::vec3& W )
{
    auto &cam = Scene::FirstPersonCamera::getSingleton();
    glm::vec3 side = cam->getStrafeDirection();
    glm::vec3 up = cam->getUpDirection();
    glm::vec3 fwd = cam->getLookDirection();

    // set up the coordinate system
    W = fwd;//glm::normalize (fwd);
    U = side;//glm::normalize (glm::cross(up, W));
    V = up;//glm::normalize (glm::cross(W, U));

    float wlen = sqrtf( glm::dot( W, W ) );
    float ulen = wlen * tanf( glm::radians(hfov) / 2.0f );
    U *= ulen;
    float vlen = ulen/aspect_ratio;
    V *= vlen;
}

void OptixRender::render()
{
  //unsigned int pbo = context["output_buffer"]->getBuffer()->getGLBOId(); // not a pbo!
	auto camera = Scene::FirstPersonCamera::getSingleton();
	auto &world_to_view = camera->getWorldToViewMatrix();
	auto pos = camera->getPos();

    float aspect_ratio = static_cast<float>(w) / static_cast<float>(h);
    float inv_aspect_ratio = static_cast<float>(h) / static_cast<float>(w);

    float vfov = camera->getFov();
    float hfov = vfov * aspect_ratio;

    glm::vec3 U,V,W;
    //CalculateCameraVariables( hfov, aspect_ratio, U, V, W );
    CalculateCameraVariables( pos, pos+camera->getLookDirection(), camera->getUpDirection(), hfov, aspect_ratio, U, V, W );

    context["eye"]->set3fv( glm::value_ptr(pos) );
    context["U"]->set3fv( glm::value_ptr(U) );
    context["V"]->set3fv( glm::value_ptr(V) );
    context["W"]->set3fv( glm::value_ptr(W) );

	try {
		context->launch(0, w,h);
	} catch (optix::Exception& e) {
		std::cout << e.getErrorString();
		return;
	}
	_displayFrame( context["output_buffer"]->getBuffer() );
	//glClearColor(1,0,0,0);
}

void OptixRender::reshape(unsigned int w, unsigned int h)
{
	this->w = w;
	this->h = h;
}

Context OptixRender::createContext()
{
  // Set up context
  Context context = Context::create();
  context->setRayTypeCount( 1 );
  context->setEntryPointCount( 1 );

  context["radiance_ray_type"]->setUint( 0u );
  context["scene_epsilon"]->setFloat( 1.e-4f );

  Variable output_buffer = context["output_buffer"];
  Buffer buffer = context->createBuffer( RT_BUFFER_OUTPUT, RT_FORMAT_UNSIGNED_BYTE4, w, h );

  output_buffer->set(buffer);

  // Ray generation program
  std::string ptx_path( baseDir + "pinhole_camera.cu.ptx" );
  try{
	Program ray_gen_program = context->createProgramFromPTXFile( ptx_path, "pinhole_camera" );
	context->setRayGenerationProgram( 0, ray_gen_program );
  }catch(optix::Exception &e)
  {
      std::string w(e.what());
      std::cout << w << std::endl;
  }

  // Exception program
  Program exception_program = context->createProgramFromPTXFile( ptx_path, "exception" );
  context->setExceptionProgram( 0, exception_program );
  context["bad_color"]->setFloat( 1.0f, 1.0f, 0.0f );

  // Miss program
  ptx_path = baseDir + "constantbg.cu.ptx";
  context->setMissProgram( 0, context->createProgramFromPTXFile( ptx_path, "miss" ) );
  context["bg_color"]->setFloat( 0.3f, 0.1f, 0.2f );

  return context;
}

Geometry OptixRender::createGeometry( Context context )
{
  Geometry sphere = context->createGeometry();
  sphere->setPrimitiveCount( 1u );
  sphere->setBoundingBoxProgram( context->createProgramFromPTXFile( baseDir + "sphere.cu.ptx", "bounds" ) );
  sphere->setIntersectionProgram( context->createProgramFromPTXFile( baseDir + "sphere.cu.ptx", "intersect" ) );
  //sphere["sphere"]->setFloat( 0.f, 0.f, 0.f, 1.0f );
  sphere["sphere"]->setFloat( 5, 3, -20.0f, 1.0f );
  return sphere;
}

Material OptixRender::createMaterial( Context context )
{
    Program chp = context->createProgramFromPTXFile( baseDir + "normal_shader.cu.ptx" , "closest_hit_radiance" );

  Material matl = context->createMaterial();
  matl->setClosestHitProgram( 0, chp );
  return matl;
}

void OptixRender::createInstance( Context context, Geometry sphere, Material material )
{
  // Create geometry instance
  GeometryInstance gi = context->createGeometryInstance();
  gi->setMaterialCount( 1 );
  gi->setGeometry( sphere );
  gi->setMaterial( 0, material );

  // Create geometry group
  GeometryGroup geometrygroup = context->createGeometryGroup();
  geometrygroup->setChildCount( 1 );
  geometrygroup->setChild( 0, gi );
  geometrygroup->setAcceleration( context->createAcceleration("NoAccel","NoAccel") );

  context["top_object"]->set( geometrygroup );
}

void OptixRender::createTextureSamplers( optix::Context context )
{
	//Upload rasterized g-buffer info here:
	auto raster_fbo = g_buffer_pass->getFBO();
	auto raster_diffuse = raster_fbo->getRenderTexture(0);
	auto raster_position = raster_fbo->getRenderTexture(1);
	auto raster_normal = raster_fbo->getRenderTexture(2);
	//TODO: Upload to optix!
	addTextureSampler(raster_diffuse_sampler, raster_diffuse->getHandle(), 1.0f, "raster_diffuse");
	addTextureSampler(raster_position_sampler, raster_position->getHandle(), 1.0f, "raster_position");
	addTextureSampler(raster_normal_sampler, raster_normal->getHandle(), 1.0f, "raster_normal");
}

void OptixRender::addTextureSampler(optix::TextureSampler sampler, unsigned int gl_tex_handle, float max_anisotropy, const std::string &sampler_name)
{
	sampler = context->createTextureSamplerFromGLImage( gl_tex_handle, RT_TARGET_GL_TEXTURE_2D );
	sampler->setWrapMode( 0, RT_WRAP_CLAMP_TO_EDGE );
	sampler->setWrapMode( 1, RT_WRAP_CLAMP_TO_EDGE );
	sampler->setWrapMode( 2, RT_WRAP_CLAMP_TO_EDGE );
	sampler->setIndexingMode( RT_TEXTURE_INDEX_NORMALIZED_COORDINATES );
	sampler->setReadMode( RT_TEXTURE_READ_NORMALIZED_FLOAT );
	sampler->setMaxAnisotropy( max_anisotropy );
	sampler->setFilteringModes( RT_FILTER_LINEAR, RT_FILTER_LINEAR, RT_FILTER_NONE );

	context[sampler_name.c_str()]->setTextureSampler( sampler );
}
<|endoftext|>