<commit_before>#include "GPU.H"

#include "PROFILE.H"
#include "PSXINPUT.H"
#include "SHADOWS.H"
#include "FXTRIG.H"
#include "TEXT_S.H"

#include <LIBETC.H>
#if PSXPC_TEST
#include <stdio.h>
#elif PSX_VERSION
#include <STDIO.H>
#endif
#include <EMULATOR.H>
#include <LIBGPU.H>
#include "CONTROL.H"

unsigned long GnFrameCounter = 19;
unsigned long GnLastFrameCount = 19;
struct PSXTEXTSTRUCT* psxtextinfo;
struct PSXSPRITESTRUCT* psxspriteinfo;
int rgbscaleme = 256;
int gfx_debugging_mode;
struct DB_STRUCT db;
struct MMTEXTURE* RoomTextInfo;
#if __linux__ || __APPLE__
unsigned long* GadwOrderingTables_V2;
#else
unsigned long GadwOrderingTables_V2[512];
#endif
static int LnFlipFrame;
#if __linux__ || __APPLE__
unsigned long* GadwOrderingTables;
unsigned long* GadwPolygonBuffers;
#else
unsigned long GadwOrderingTables[5128];
unsigned long GadwPolygonBuffers[52260];
#endif

void GPU_UseOrderingTables(unsigned long* pBuffers, int nOTSize)//5DF68(<), 5F1C8(<) (D) (ND)
{
	db.order_table[0] = (unsigned long*)((unsigned long)&pBuffers[0]);
	db.order_table[1] = (unsigned long*)((unsigned long)&pBuffers[nOTSize]);
	db.nOTSize = nOTSize;
	db.pickup_order_table[0] = (unsigned long*)((unsigned long)&GadwOrderingTables_V2[0]);
	db.pickup_order_table[1] = (unsigned long*)((unsigned long)&GadwOrderingTables_V2[256]);
	return;
}

void GPU_UsePolygonBuffers(unsigned long* pBuffers, int nPBSize)//5DFB0(<),
{
	db.nPBSize = nPBSize;
	db.poly_buffer[0] = (unsigned long*)((unsigned long)&pBuffers[0]);
	db.poly_buffer[1] = (unsigned long*)((unsigned long)&pBuffers[nPBSize]);
	return;
}

void GPU_EndScene()//5DFDC(<), 5F23C(<) (F)
{
#if DEBUG_VERSION
	int nPolys;
	static int nWorstPolys;

	nPolys = (((unsigned long)db.polyptr - (unsigned long)db.curpolybuf) * 0x4EC4EC4F) >> 4 - ((unsigned long)db.polyptr - (unsigned long)db.curpolybuf) >> 31;

	if (nWorstPolys < nPolys)
	{
		nWorstPolys = nPolys;
	}
#endif

	//loc_5E020
	OptimiseOTagR(&db.ot[0], db.nOTSize);

#if DEBUG_VERSION
	ProfileRGB(255, 255, 255);
	//do_gfx_debug_mode(&db.ot[db.nOTSize - 1]);
	ProfileRGB(0, 255, 255);
#endif

	Emulator_EndScene();

	return;
}

int GPU_FlipNoIdle()//5E078(<), 5F264(<) (F)
{
#if DEBUG_VERSION
	if (ProfileDraw)
	{
		ProfileRGB(255, 255, 255);
		ProfileAddOT(&db.ot[0]);
	}
#endif

	//loc_5E0B0
	DrawSync(0);

#if DEBUG_VERSION
	if (ProfileDraw)
	{
		ProfileAddDrawOT(&db.ot[0]);
	}
#endif

	LnFlipFrame = GnLastFrameCount;

	//loc_5E0D8
	if (LnFlipFrame < 2)
	{
		do
		{
			VSync(0);
			LnFlipFrame++;
		} while (LnFlipFrame < 2);
	}
	else
	{
		//loc_5E120
		VSync(0);
		LnFlipFrame++;
	}

	GnLastFrameCount = 0;
	PutDispEnv(&db.disp[db.current_buffer]);
	DrawOTagEnv(&db.ot[db.nOTSize-1], &db.draw[db.current_buffer]);

#if DEBUG_VERSION
	ProfileStartCount();
#endif

	db.current_buffer ^= 1;

	return LnFlipFrame;
}

void do_gfx_debug_mode(unsigned long* otstart)//5E1B4(<) ? (F)
{
	unsigned long* data;
	unsigned char code;
	int ntri;
	int nquad;
	unsigned short x0;
	unsigned short y0;
	unsigned short x1;
	unsigned short y1;
	unsigned short x2;
	unsigned short y2;
	LINE_F2* line2;
	char txbuf[64];

	if (RawEdge & IN_UNK8)
	{
		gfx_debugging_mode++;
	}

	//loc_5E1E0
	nquad = 0;

	if (gfx_debugging_mode > 2)
	{
		gfx_debugging_mode = 0;
	}

	//loc_5E1F8
	data = (unsigned long*)(otstart[0] & 0xFFFFFF);
	ntri = 0;

	if ((unsigned long)data != 0xFFFFFF)
	{
		do
		{
			if ((data[0] & 0xFF000000) != 0)
			{
				code = ((char*)data)[7];//getcode

				if (gfx_debugging_mode < 2)
				{
					if ((code & 0xFC) == 0x7C)
					{
						if (gfx_debugging_mode != 0)
						{
							((short*)data)[13] &= 0xFF9F;
						}
						else
						{
							//loc_5E27C
							((char*)data)[7] = (code & 2) | 0x3C;//setcode
						}

						nquad = 1;
					}
					else if ((code & 0xFC) == 0x74)
					{
						//loc_5E290
						if (gfx_debugging_mode != 0)
						{
							((char*)data)[7] = 0x36;
							((short*)data)[13] &= 0xFF9F;
						}
						else
						{
							//loc_5E2B4
							((char*)data)[7] = (code & 2) | 0x34;
						}

						ntri = 1;
					}//loc_5E3C4
				}
				else if (gfx_debugging_mode == 2)
				{
					//loc_5E2C8

					if ((code & 0xFC) == 0x7C)
					{
						x0 = ((unsigned short*)data)[4];
						y0 = ((unsigned short*)data)[5];
						x1 = ((unsigned short*)data)[10];
						y1 = ((unsigned short*)data)[11];
						x2 = ((unsigned short*)data)[16];
						y2 = ((unsigned short*)data)[17];

						nquad++;

						((char*)data)[7] = 0x4C;
						((char*)data)[4] = 0x0;
						((char*)data)[5] = 0x50;
						((char*)data)[6] = 0x0;
						((long*)data)[6] = 0x55555555;

						((short*)data)[8] = ((unsigned short*)data)[22];

						line2 = (LINE_F2*)&data[6];

						((short*)data)[9] = ((unsigned short*)data)[23];

						((short*)data)[4] = x0;
						((short*)data)[5] = y0;
						((short*)data)[6] = x1;
						((short*)data)[7] = y1;
						((short*)data)[10] = x2;
						((short*)data)[11] = y2;

						line2->code = 0x40;
						line2->x0 = x0;
						line2->y0 = y0;
						line2->x1 = x2;
						line2->y1 = y2;
						line2->r0 = 0;
						line2->g0 = 80;
						line2->b0 = 0;

						((char*)data)[3] = 9;
					}
					else if ((code & 0xFC) == 0x74)
					{
						//loc_5E368
						ntri++;

						x0 = ((unsigned short*)data)[4];
						y0 = ((unsigned short*)data)[5];
						x1 = ((unsigned short*)data)[10];
						y1 = ((unsigned short*)data)[11];
						x2 = ((unsigned short*)data)[16];
						y2 = ((unsigned short*)data)[17];

						((char*)data)[7] = 76;
						((char*)data)[4] = 0;
						((char*)data)[5] = 80;
						((char*)data)[6] = 0;
						((long*)data)[6] = 0x55555555;
						((char*)data)[3] = 6;
						((short*)data)[4] = x0;
						((short*)data)[5] = y0;
						((short*)data)[6] = x1;
						((short*)data)[7] = y1;
						((short*)data)[8] = x2;
						((short*)data)[9] = y2;
						((short*)data)[10] = x0;
						((short*)data)[11] = y0;
					}
				}//loc_5E3C4
			}

			data = (unsigned long*)(data[0] & 0xFFFFFF);
		}while ((unsigned long)data != 0xFFFFFF);
		//loc_5E3C4
	}

	//loc_5E3D8
	if (gfx_debugging_mode == 0)
	{
		return;
	}

	sprintf(&txbuf[0], "TRI %d", ntri);
	PrintString(34, 220, 3, &txbuf[0], FF_NONE);

	sprintf(&txbuf[0], "QUAD %d", nquad);
	PrintString(34, 232, 3, &txbuf[0], FF_NONE);
}

void GPU_FlipStory(unsigned long* gfx)//5E448(<), * (F)
{
	RECT16 r;
	RECT16* fuckmyanalpassage;

	DrawSync(0);
	VSync(0);

	GnLastFrameCount = 0;
	PutDispEnv(&db.disp[db.current_buffer]);
	fuckmyanalpassage = (RECT16*) &db.disp[db.current_buffer ^ 1].disp;
	r.x = fuckmyanalpassage->x;
	r.y = fuckmyanalpassage->y;
	r.w = fuckmyanalpassage->w;
	r.h = fuckmyanalpassage->h;
	LoadImagePSX(&r, gfx);
	DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[db.current_buffer]);
	db.current_buffer ^= 1;
}<commit_msg>[Specific-PSXPC_N] Hack framerate to 60<commit_after>#include "GPU.H"

#include "PROFILE.H"
#include "PSXINPUT.H"
#include "SHADOWS.H"
#include "FXTRIG.H"
#include "TEXT_S.H"

#include <LIBETC.H>
#if PSXPC_TEST
#include <stdio.h>
#elif PSX_VERSION
#include <STDIO.H>
#endif
#include <EMULATOR.H>
#include <LIBGPU.H>
#include "CONTROL.H"

unsigned long GnFrameCounter = 19;
unsigned long GnLastFrameCount = 19;
struct PSXTEXTSTRUCT* psxtextinfo;
struct PSXSPRITESTRUCT* psxspriteinfo;
int rgbscaleme = 256;
int gfx_debugging_mode;
struct DB_STRUCT db;
struct MMTEXTURE* RoomTextInfo;
#if __linux__ || __APPLE__
unsigned long* GadwOrderingTables_V2;
#else
unsigned long GadwOrderingTables_V2[512];
#endif
static int LnFlipFrame;
#if __linux__ || __APPLE__
unsigned long* GadwOrderingTables;
unsigned long* GadwPolygonBuffers;
#else
unsigned long GadwOrderingTables[5128];
unsigned long GadwPolygonBuffers[52260];
#endif

void GPU_UseOrderingTables(unsigned long* pBuffers, int nOTSize)//5DF68(<), 5F1C8(<) (D) (ND)
{
	db.order_table[0] = (unsigned long*)((unsigned long)&pBuffers[0]);
	db.order_table[1] = (unsigned long*)((unsigned long)&pBuffers[nOTSize]);
	db.nOTSize = nOTSize;
	db.pickup_order_table[0] = (unsigned long*)((unsigned long)&GadwOrderingTables_V2[0]);
	db.pickup_order_table[1] = (unsigned long*)((unsigned long)&GadwOrderingTables_V2[256]);
	return;
}

void GPU_UsePolygonBuffers(unsigned long* pBuffers, int nPBSize)//5DFB0(<),
{
	db.nPBSize = nPBSize;
	db.poly_buffer[0] = (unsigned long*)((unsigned long)&pBuffers[0]);
	db.poly_buffer[1] = (unsigned long*)((unsigned long)&pBuffers[nPBSize]);
	return;
}

void GPU_EndScene()//5DFDC(<), 5F23C(<) (F)
{
#if DEBUG_VERSION
	int nPolys;
	static int nWorstPolys;

	nPolys = (((unsigned long)db.polyptr - (unsigned long)db.curpolybuf) * 0x4EC4EC4F) >> 4 - ((unsigned long)db.polyptr - (unsigned long)db.curpolybuf) >> 31;

	if (nWorstPolys < nPolys)
	{
		nWorstPolys = nPolys;
	}
#endif

	//loc_5E020
	OptimiseOTagR(&db.ot[0], db.nOTSize);

#if DEBUG_VERSION
	ProfileRGB(255, 255, 255);
	//do_gfx_debug_mode(&db.ot[db.nOTSize - 1]);
	ProfileRGB(0, 255, 255);
#endif

	//specific hack, should be enough to hack the framerate from 90 to 60
	//todo: emulator, only allow 60 flips per second, in TRC flip is called twice per frame
	if (LnFlipFrame % 2)
	{
		Emulator_EndScene();
	}
	return;
}

int GPU_FlipNoIdle()//5E078(<), 5F264(<) (F)
{
#if DEBUG_VERSION
	if (ProfileDraw)
	{
		ProfileRGB(255, 255, 255);
		ProfileAddOT(&db.ot[0]);
	}
#endif

	//loc_5E0B0
	DrawSync(0);

#if DEBUG_VERSION
	if (ProfileDraw)
	{
		ProfileAddDrawOT(&db.ot[0]);
	}
#endif

	LnFlipFrame = GnLastFrameCount;

	//loc_5E0D8
	if (LnFlipFrame < 2)
	{
		do
		{
			VSync(0);
			LnFlipFrame++;
		} while (LnFlipFrame < 2);
	}
	else
	{
		//loc_5E120
		VSync(0);
		LnFlipFrame++;
	}

	GnLastFrameCount = 0;
	PutDispEnv(&db.disp[db.current_buffer]);
	DrawOTagEnv(&db.ot[db.nOTSize-1], &db.draw[db.current_buffer]);

#if DEBUG_VERSION
	ProfileStartCount();
#endif

	db.current_buffer ^= 1;

	return LnFlipFrame;
}

void do_gfx_debug_mode(unsigned long* otstart)//5E1B4(<) ? (F)
{
	unsigned long* data;
	unsigned char code;
	int ntri;
	int nquad;
	unsigned short x0;
	unsigned short y0;
	unsigned short x1;
	unsigned short y1;
	unsigned short x2;
	unsigned short y2;
	LINE_F2* line2;
	char txbuf[64];

	if (RawEdge & IN_UNK8)
	{
		gfx_debugging_mode++;
	}

	//loc_5E1E0
	nquad = 0;

	if (gfx_debugging_mode > 2)
	{
		gfx_debugging_mode = 0;
	}

	//loc_5E1F8
	data = (unsigned long*)(otstart[0] & 0xFFFFFF);
	ntri = 0;

	if ((unsigned long)data != 0xFFFFFF)
	{
		do
		{
			if ((data[0] & 0xFF000000) != 0)
			{
				code = ((char*)data)[7];//getcode

				if (gfx_debugging_mode < 2)
				{
					if ((code & 0xFC) == 0x7C)
					{
						if (gfx_debugging_mode != 0)
						{
							((short*)data)[13] &= 0xFF9F;
						}
						else
						{
							//loc_5E27C
							((char*)data)[7] = (code & 2) | 0x3C;//setcode
						}

						nquad = 1;
					}
					else if ((code & 0xFC) == 0x74)
					{
						//loc_5E290
						if (gfx_debugging_mode != 0)
						{
							((char*)data)[7] = 0x36;
							((short*)data)[13] &= 0xFF9F;
						}
						else
						{
							//loc_5E2B4
							((char*)data)[7] = (code & 2) | 0x34;
						}

						ntri = 1;
					}//loc_5E3C4
				}
				else if (gfx_debugging_mode == 2)
				{
					//loc_5E2C8

					if ((code & 0xFC) == 0x7C)
					{
						x0 = ((unsigned short*)data)[4];
						y0 = ((unsigned short*)data)[5];
						x1 = ((unsigned short*)data)[10];
						y1 = ((unsigned short*)data)[11];
						x2 = ((unsigned short*)data)[16];
						y2 = ((unsigned short*)data)[17];

						nquad++;

						((char*)data)[7] = 0x4C;
						((char*)data)[4] = 0x0;
						((char*)data)[5] = 0x50;
						((char*)data)[6] = 0x0;
						((long*)data)[6] = 0x55555555;

						((short*)data)[8] = ((unsigned short*)data)[22];

						line2 = (LINE_F2*)&data[6];

						((short*)data)[9] = ((unsigned short*)data)[23];

						((short*)data)[4] = x0;
						((short*)data)[5] = y0;
						((short*)data)[6] = x1;
						((short*)data)[7] = y1;
						((short*)data)[10] = x2;
						((short*)data)[11] = y2;

						line2->code = 0x40;
						line2->x0 = x0;
						line2->y0 = y0;
						line2->x1 = x2;
						line2->y1 = y2;
						line2->r0 = 0;
						line2->g0 = 80;
						line2->b0 = 0;

						((char*)data)[3] = 9;
					}
					else if ((code & 0xFC) == 0x74)
					{
						//loc_5E368
						ntri++;

						x0 = ((unsigned short*)data)[4];
						y0 = ((unsigned short*)data)[5];
						x1 = ((unsigned short*)data)[10];
						y1 = ((unsigned short*)data)[11];
						x2 = ((unsigned short*)data)[16];
						y2 = ((unsigned short*)data)[17];

						((char*)data)[7] = 76;
						((char*)data)[4] = 0;
						((char*)data)[5] = 80;
						((char*)data)[6] = 0;
						((long*)data)[6] = 0x55555555;
						((char*)data)[3] = 6;
						((short*)data)[4] = x0;
						((short*)data)[5] = y0;
						((short*)data)[6] = x1;
						((short*)data)[7] = y1;
						((short*)data)[8] = x2;
						((short*)data)[9] = y2;
						((short*)data)[10] = x0;
						((short*)data)[11] = y0;
					}
				}//loc_5E3C4
			}

			data = (unsigned long*)(data[0] & 0xFFFFFF);
		}while ((unsigned long)data != 0xFFFFFF);
		//loc_5E3C4
	}

	//loc_5E3D8
	if (gfx_debugging_mode == 0)
	{
		return;
	}

	sprintf(&txbuf[0], "TRI %d", ntri);
	PrintString(34, 220, 3, &txbuf[0], FF_NONE);

	sprintf(&txbuf[0], "QUAD %d", nquad);
	PrintString(34, 232, 3, &txbuf[0], FF_NONE);
}

void GPU_FlipStory(unsigned long* gfx)//5E448(<), * (F)
{
	RECT16 r;
	RECT16* fuckmyanalpassage;

	DrawSync(0);
	VSync(0);

	GnLastFrameCount = 0;
	PutDispEnv(&db.disp[db.current_buffer]);
	fuckmyanalpassage = (RECT16*) &db.disp[db.current_buffer ^ 1].disp;
	r.x = fuckmyanalpassage->x;
	r.y = fuckmyanalpassage->y;
	r.w = fuckmyanalpassage->w;
	r.h = fuckmyanalpassage->h;
	LoadImagePSX(&r, gfx);
	DrawOTagEnv(&db.ot[db.nOTSize - 1], &db.draw[db.current_buffer]);
	db.current_buffer ^= 1;
}<|endoftext|>


<commit_before>/*++

Module Name:

    snap.cpp

Abstract:

    Main entry point for the snap binary. Calls into the indexer, single-end aligner or
    paired-end aligner functions defined in other source files in this directory.

Authors:

    Matei Zaharia & Bill Bolosky, February, 2012

Environment:

    User mode service.

Revision History:

    Adapted from cSNAP, which was in turn adapted from the scala prototype

--*/

#include "stdafx.h"
#include "options.h"
#include "FASTA.h"
#include "GenomeIndex.h"
#include "SingleAligner.h"
#include "PairedAligner.h"
#include "exit.h"
#include "SeedSequencer.h"

using namespace std;

const char *SNAP_VERSION = "1.0beta.2";

static void usage()
{
    fprintf(stderr,
            "Usage: snap <command> [<options>]\n"
            "Commands:\n"
            "   index    build a genome index\n"
            "   single   align single-end reads\n"
            "   paired   align paired-end reads\n"
            "Type a command without arguments to see its help.\n");
    soft_exit(1);
}

int main(int argc, const char **argv)
{
    printf("Welcome to SNAP version %s.\n\n", SNAP_VERSION);

    InitializeSeedSequencers();

    if (argc < 2) {
        usage();
    } else if (strcmp(argv[1], "index") == 0) {
        GenomeIndex::runIndexer(argc - 2, argv + 2);
    } else if (strcmp(argv[1], "single") == 0 || strcmp(argv[1], "paired") == 0) {
        for (int i = 1; i < argc; /* i is increased below */) {
            unsigned nArgsConsumed;
            if (strcmp(argv[i], "single") == 0) {
                SingleAlignerContext single;
                single.runAlignment(argc - (i + 1), argv + i + 1, SNAP_VERSION, &nArgsConsumed);
            } else if (strcmp(argv[i], "paired") == 0) {
                PairedAlignerContext paired;
                paired.runAlignment(argc - (i + 1), argv + i + 1, SNAP_VERSION, &nArgsConsumed);
            } else {
                fprintf(stderr, "Invalid command: %s\n\n", argv[i]);
                usage();
            }
            _ASSERT(nArgsConsumed > 0);
            i += nArgsConsumed + 1;  // +1 for single or paired
        }
    } else {
        fprintf(stderr, "Invalid command: %s\n\n", argv[1]);
        usage();
    }
}
<commit_msg>1.0dev.1: merge 1.0beta.2<commit_after>/*++

Module Name:

    snap.cpp

Abstract:

    Main entry point for the snap binary. Calls into the indexer, single-end aligner or
    paired-end aligner functions defined in other source files in this directory.

Authors:

    Matei Zaharia & Bill Bolosky, February, 2012

Environment:

    User mode service.

Revision History:

    Adapted from cSNAP, which was in turn adapted from the scala prototype

--*/

#include "stdafx.h"
#include "options.h"
#include "FASTA.h"
#include "GenomeIndex.h"
#include "SingleAligner.h"
#include "PairedAligner.h"
#include "exit.h"
#include "SeedSequencer.h"

using namespace std;

const char *SNAP_VERSION = "1.0dev.1";

static void usage()
{
    fprintf(stderr,
            "Usage: snap <command> [<options>]\n"
            "Commands:\n"
            "   index    build a genome index\n"
            "   single   align single-end reads\n"
            "   paired   align paired-end reads\n"
            "Type a command without arguments to see its help.\n");
    soft_exit(1);
}

int main(int argc, const char **argv)
{
    printf("Welcome to SNAP version %s.\n\n", SNAP_VERSION);

    InitializeSeedSequencers();

    if (argc < 2) {
        usage();
    } else if (strcmp(argv[1], "index") == 0) {
        GenomeIndex::runIndexer(argc - 2, argv + 2);
    } else if (strcmp(argv[1], "single") == 0 || strcmp(argv[1], "paired") == 0) {
        for (int i = 1; i < argc; /* i is increased below */) {
            unsigned nArgsConsumed;
            if (strcmp(argv[i], "single") == 0) {
                SingleAlignerContext single;
                single.runAlignment(argc - (i + 1), argv + i + 1, SNAP_VERSION, &nArgsConsumed);
            } else if (strcmp(argv[i], "paired") == 0) {
                PairedAlignerContext paired;
                paired.runAlignment(argc - (i + 1), argv + i + 1, SNAP_VERSION, &nArgsConsumed);
            } else {
                fprintf(stderr, "Invalid command: %s\n\n", argv[i]);
                usage();
            }
            _ASSERT(nArgsConsumed > 0);
            i += nArgsConsumed + 1;  // +1 for single or paired
        }
    } else {
        fprintf(stderr, "Invalid command: %s\n\n", argv[1]);
        usage();
    }
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Gabriel Ebner
*/
#include "checker/text_import.h"
#include "kernel/environment.h"
#include "kernel/inductive/inductive.h"
#include "kernel/type_checker.h"
#include "util/sstream.h"
#include <string>
#include <iostream>
#include <unordered_map>
#include "kernel/quotient/quotient.h"

namespace lean {

struct text_importer {
    std::unordered_map<unsigned, expr> m_expr;
    std::unordered_map<unsigned, name> m_name;
    std::unordered_map<unsigned, level> m_level;

    lowlevel_notations m_notations;

    environment m_env;

    text_importer(environment const & env) : m_env(env) {
        m_level[0] = {};
        m_name[0] = {};
    }

    levels read_levels(std::istream & in) {
        unsigned idx;
        buffer<level> ls;
        while (in >> idx) {
            ls.push_back(m_level.at(idx));
        }
        return to_list(ls);
    }

    level_param_names read_level_params(std::istream & in) {
        unsigned idx;
        buffer<name> ls;
        while (in >> idx) {
            ls.push_back(m_name.at(idx));
        }
        return to_list(ls);
    }

    void handle_ind(std::istream & in) {
        unsigned num_params, name_idx, type_idx, num_intros;
        in >> num_params >> name_idx >> type_idx >> num_intros;

        buffer<inductive::intro_rule> intros;
        for (unsigned i = 0; i < num_intros; i++) {
            unsigned name_idx, type_idx; in >> name_idx >> type_idx;
            intros.push_back(inductive::mk_intro_rule(m_name.at(name_idx), m_expr.at(type_idx)));
        }

        auto ls = read_level_params(in);

        inductive::inductive_decl decl(m_name.at(name_idx), ls, num_params, m_expr.at(type_idx), to_list(intros));
        m_env = inductive::add_inductive(m_env, decl, true).first;
    }

    void handle_def(std::istream & in) {
        unsigned name_idx, type_idx, val_idx;
        in >> name_idx >> type_idx >> val_idx;
        auto ls = read_level_params(in);

        auto decl =
            type_checker(m_env).is_prop(m_expr.at(type_idx)) ?
                mk_theorem(m_name.at(name_idx), ls, m_expr.at(type_idx), m_expr.at(val_idx)) :
                mk_definition(m_env, m_name.at(name_idx), ls, m_expr.at(type_idx), m_expr.at(val_idx), true, true);

        m_env = m_env.add(check(m_env, decl, true));
    }

    void handle_ax(std::istream & in) {
        unsigned name_idx, type_idx;
        in >> name_idx >> type_idx;
        auto ls = read_level_params(in);
        m_env = m_env.add(check(m_env, mk_axiom(m_name.at(name_idx), ls, m_expr.at(type_idx))));
    }

    void handle_notation(std::istream & in, lowlevel_notation_kind kind) {
        unsigned name_idx, prec;
        in >> name_idx >> prec;

        std::string token;
        std::getline(in, token);
        if (!token.empty() && token.front())
            token.erase(token.begin());
        if (!token.empty() && token.back() == '\n')
            token.erase(token.end() - 1);

        m_notations[m_name.at(name_idx)] = { kind, token, prec };
    }

    binder_info read_binder_info(std::string const & tok) {
        if (tok == "#BI") {
            return mk_implicit_binder_info();
        } else if (tok == "#BS") {
            return mk_strict_implicit_binder_info();
        } else if (tok == "#BC") {
            return mk_inst_implicit_binder_info();
        } else if (tok == "#BD") {
            return {};
        } else {
            throw exception(sstream() << "unknown binder info: " << tok);
        }
    }

    void handle_line(std::string const & line) {
        std::istringstream in(line);

        unsigned idx;
        std::string cmd;
        in >> cmd;
        if (cmd == "#IND") {
            handle_ind(in);
        } else if (cmd == "#DEF") {
            handle_def(in);
        } else if (cmd == "#AX") {
            handle_ax(in);
        } else if (cmd == "#QUOT") {
            m_env = declare_quotient(m_env);
        } else if (cmd == "#PREFIX") {
            handle_notation(in, lowlevel_notation_kind::Prefix);
        } else if (cmd == "#POSTFIX") {
            handle_notation(in, lowlevel_notation_kind::Postfix);
        } else if (cmd == "#INFIX") {
            handle_notation(in, lowlevel_notation_kind::Infix);
        } else if (std::istringstream(cmd) >> idx) {
            std::string kind;
            in >> kind;

            if (kind == "#NS") {
                unsigned p; std::string limb; in >> p >> std::skipws >> limb;
                m_name[idx] = name(m_name.at(p), limb.c_str());
            } else if (kind == "#NI") {
                unsigned p, limb; in >> p >> limb;
                m_name[idx] = name(m_name.at(p), limb);
            } else if (kind == "#US") {
                unsigned l1; in >> l1;
                m_level[idx] = mk_succ(m_level.at(l1));
            } else if (kind == "#UM") {
                unsigned l1, l2; in >> l1 >> l2;
                m_level[idx] = mk_max(m_level.at(l1), m_level.at(l2));
            } else if (kind == "#UIM") {
                unsigned l1, l2; in >> l1 >> l2;
                m_level[idx] = mk_imax(m_level.at(l1), m_level.at(l2));
            } else if (kind == "#UP") {
                unsigned i1; in >> i1;
                m_level[idx] = mk_param_univ(m_name.at(i1));
            } else if (kind == "#EV") {
                unsigned v; in >> v;
                m_expr[idx] = mk_var(v);
            } else if (kind == "#ES") {
                unsigned l; in >> l;
                m_expr[idx] = mk_sort(m_level.at(l));
            } else if (kind == "#EC") {
                unsigned n; in >> n;
                auto ls = read_levels(in);
                m_expr[idx] = mk_constant(m_name.at(n), ls);
            } else if (kind == "#EA") {
                unsigned e1, e2; in >> e1 >> e2;
                m_expr[idx] = mk_app(m_expr.at(e1), m_expr.at(e2));
            } else if (kind == "#EZ") {
                unsigned n, t, v, b; in >> n >> t >> v >> b;
                m_expr[idx] = mk_let(m_name.at(n), m_expr.at(t), m_expr.at(v), m_expr.at(b));
            } else if (kind == "#EL") {
                unsigned n, t, e; std::string b; in >> b >> n >> t >> e;
                m_expr[idx] = mk_lambda(m_name.at(n), m_expr.at(t), m_expr.at(e), read_binder_info(b));
            } else if (kind == "#EP") {
                unsigned n, t, e; std::string b; in >> b >> n >> t >> e;
                m_expr[idx] = mk_pi(m_name.at(n), m_expr.at(t), m_expr.at(e), read_binder_info(b));
            } else {
                throw exception(sstream() << "unknown term definition kind: " << kind);
            }
        } else {
            throw exception(sstream() << "unknown command: " << cmd);
        }
    }
};

void import_from_text(std::istream & in, environment & env, lowlevel_notations & notations) {
    text_importer importer(env);

    std::string line;
    unsigned line_num = 0;
    while (std::getline(in, line)) {
        line_num++;
        try {
            importer.handle_line(line);
        } catch (throwable & t) {
            throw exception(sstream() << "line " << line_num << ": " << t.what());
        } catch (std::exception & e) {
            throw exception(sstream() << "line " << line_num << ": " << e.what());
        }
    }

    env = importer.m_env;
    notations = std::move(importer.m_notations);
}

}
<commit_msg>feat: leanchecker: print error messages (#548)<commit_after>/*
Copyright (c) 2017 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.

Author: Gabriel Ebner
*/
#include "checker/text_import.h"
#include "kernel/environment.h"
#include "kernel/inductive/inductive.h"
#include "kernel/type_checker.h"
#include "util/sstream.h"
#include <string>
#include <iostream>
#include <unordered_map>
#include "kernel/quotient/quotient.h"
#include "checker/simple_pp.h"
#include "kernel/ext_exception.h"

namespace lean {

template <typename Fn>
void wrap_exception(name const & decl_name, environment const & env, Fn const & fn) {
    try {
        fn();
    } catch (ext_exception & ex) {
        throw throwable(sstream() << decl_name << ": " <<
            ex.pp(formatter(options(), [&] (expr const & e, options const &) {
                return simple_pp(env, e, lowlevel_notations());
            })));
    }
}

struct text_importer {
    std::unordered_map<unsigned, expr> m_expr;
    std::unordered_map<unsigned, name> m_name;
    std::unordered_map<unsigned, level> m_level;

    lowlevel_notations m_notations;

    environment m_env;

    text_importer(environment const & env) : m_env(env) {
        m_level[0] = {};
        m_name[0] = {};
    }

    levels read_levels(std::istream & in) {
        unsigned idx;
        buffer<level> ls;
        while (in >> idx) {
            ls.push_back(m_level.at(idx));
        }
        return to_list(ls);
    }

    level_param_names read_level_params(std::istream & in) {
        unsigned idx;
        buffer<name> ls;
        while (in >> idx) {
            ls.push_back(m_name.at(idx));
        }
        return to_list(ls);
    }

    void handle_ind(std::istream & in) {
        unsigned num_params, name_idx, type_idx, num_intros;
        in >> num_params >> name_idx >> type_idx >> num_intros;

        buffer<inductive::intro_rule> intros;
        for (unsigned i = 0; i < num_intros; i++) {
            unsigned name_idx, type_idx; in >> name_idx >> type_idx;
            intros.push_back(inductive::mk_intro_rule(m_name.at(name_idx), m_expr.at(type_idx)));
        }

        auto ls = read_level_params(in);

        inductive::inductive_decl decl(m_name.at(name_idx), ls, num_params, m_expr.at(type_idx), to_list(intros));
        wrap_exception(decl.m_name, m_env, [&] {
            m_env = inductive::add_inductive(m_env, decl, true).first;
        });
    }

    void handle_def(std::istream & in) {
        unsigned name_idx, type_idx, val_idx;
        in >> name_idx >> type_idx >> val_idx;
        auto ls = read_level_params(in);
        name n = m_name.at(name_idx);

        wrap_exception(n, m_env, [&] {
            auto decl =
                type_checker(m_env).is_prop(m_expr.at(type_idx)) ?
                    mk_theorem(n, ls, m_expr.at(type_idx), m_expr.at(val_idx)) :
                    mk_definition(m_env, n, ls, m_expr.at(type_idx), m_expr.at(val_idx), true, true);

            m_env = m_env.add(check(m_env, decl, true));
        });
    }

    void handle_ax(std::istream & in) {
        unsigned name_idx, type_idx;
        in >> name_idx >> type_idx;
        auto ls = read_level_params(in);
        name n = m_name.at(name_idx);
        wrap_exception(n, m_env, [&] {
            m_env = m_env.add(check(m_env, mk_axiom(n, ls, m_expr.at(type_idx))));
        });
    }

    void handle_notation(std::istream & in, lowlevel_notation_kind kind) {
        unsigned name_idx, prec;
        in >> name_idx >> prec;

        std::string token;
        std::getline(in, token);
        if (!token.empty() && token.front())
            token.erase(token.begin());
        if (!token.empty() && token.back() == '\n')
            token.erase(token.end() - 1);

        m_notations[m_name.at(name_idx)] = { kind, token, prec };
    }

    binder_info read_binder_info(std::string const & tok) {
        if (tok == "#BI") {
            return mk_implicit_binder_info();
        } else if (tok == "#BS") {
            return mk_strict_implicit_binder_info();
        } else if (tok == "#BC") {
            return mk_inst_implicit_binder_info();
        } else if (tok == "#BD") {
            return {};
        } else {
            throw exception(sstream() << "unknown binder info: " << tok);
        }
    }

    void handle_line(std::string const & line) {
        std::istringstream in(line);

        unsigned idx;
        std::string cmd;
        in >> cmd;
        if (cmd == "#IND") {
            handle_ind(in);
        } else if (cmd == "#DEF") {
            handle_def(in);
        } else if (cmd == "#AX") {
            handle_ax(in);
        } else if (cmd == "#QUOT") {
            m_env = declare_quotient(m_env);
        } else if (cmd == "#PREFIX") {
            handle_notation(in, lowlevel_notation_kind::Prefix);
        } else if (cmd == "#POSTFIX") {
            handle_notation(in, lowlevel_notation_kind::Postfix);
        } else if (cmd == "#INFIX") {
            handle_notation(in, lowlevel_notation_kind::Infix);
        } else if (std::istringstream(cmd) >> idx) {
            std::string kind;
            in >> kind;

            if (kind == "#NS") {
                unsigned p; std::string limb; in >> p >> std::skipws >> limb;
                m_name[idx] = name(m_name.at(p), limb.c_str());
            } else if (kind == "#NI") {
                unsigned p, limb; in >> p >> limb;
                m_name[idx] = name(m_name.at(p), limb);
            } else if (kind == "#US") {
                unsigned l1; in >> l1;
                m_level[idx] = mk_succ(m_level.at(l1));
            } else if (kind == "#UM") {
                unsigned l1, l2; in >> l1 >> l2;
                m_level[idx] = mk_max(m_level.at(l1), m_level.at(l2));
            } else if (kind == "#UIM") {
                unsigned l1, l2; in >> l1 >> l2;
                m_level[idx] = mk_imax(m_level.at(l1), m_level.at(l2));
            } else if (kind == "#UP") {
                unsigned i1; in >> i1;
                m_level[idx] = mk_param_univ(m_name.at(i1));
            } else if (kind == "#EV") {
                unsigned v; in >> v;
                m_expr[idx] = mk_var(v);
            } else if (kind == "#ES") {
                unsigned l; in >> l;
                m_expr[idx] = mk_sort(m_level.at(l));
            } else if (kind == "#EC") {
                unsigned n; in >> n;
                auto ls = read_levels(in);
                m_expr[idx] = mk_constant(m_name.at(n), ls);
            } else if (kind == "#EA") {
                unsigned e1, e2; in >> e1 >> e2;
                m_expr[idx] = mk_app(m_expr.at(e1), m_expr.at(e2));
            } else if (kind == "#EZ") {
                unsigned n, t, v, b; in >> n >> t >> v >> b;
                m_expr[idx] = mk_let(m_name.at(n), m_expr.at(t), m_expr.at(v), m_expr.at(b));
            } else if (kind == "#EL") {
                unsigned n, t, e; std::string b; in >> b >> n >> t >> e;
                m_expr[idx] = mk_lambda(m_name.at(n), m_expr.at(t), m_expr.at(e), read_binder_info(b));
            } else if (kind == "#EP") {
                unsigned n, t, e; std::string b; in >> b >> n >> t >> e;
                m_expr[idx] = mk_pi(m_name.at(n), m_expr.at(t), m_expr.at(e), read_binder_info(b));
            } else {
                throw exception(sstream() << "unknown term definition kind: " << kind);
            }
        } else {
            throw exception(sstream() << "unknown command: " << cmd);
        }
    }
};

void import_from_text(std::istream & in, environment & env, lowlevel_notations & notations) {
    text_importer importer(env);

    std::string line;
    unsigned line_num = 0;
    while (std::getline(in, line)) {
        line_num++;
        try {
            importer.handle_line(line);
        } catch (throwable & t) {
            throw exception(sstream() << "line " << line_num << ": " << t.what());
        } catch (std::exception & e) {
            throw exception(sstream() << "line " << line_num << ": " << e.what());
        }
    }

    env = importer.m_env;
    notations = std::move(importer.m_notations);
}

}
<|endoftext|>


<commit_before>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "test_optimizers"

#include <boost/test/unit_test.hpp>
#include "math/abs.hpp"
#include "core/logger.h"
#include "core/minimize.h"
#include "math/random.hpp"
#include "math/numeric.hpp"
#include "math/epsilon.hpp"
#include "text/to_string.hpp"

#include "func/function_trid.h"
#include "func/function_beale.h"
#include "func/function_booth.h"
#include "func/function_cauchy.h"
#include "func/function_sphere.h"
#include "func/function_matyas.h"
#include "func/function_powell.h"
#include "func/function_mccormick.h"
#include "func/function_himmelblau.h"
#include "func/function_rosenbrock.h"
#include "func/function_3hump_camel.h"
#include "func/function_sum_squares.h"
#include "func/function_dixon_price.h"
#include "func/function_goldstein_price.h"
#include "func/function_rotated_ellipsoid.h"

namespace test
{
        using namespace ncv;

//        static void check_solution(const string_t& problem, const string_t& optimizer,
//                const vector_t& x0, const opt_state_t& state, const std::vector<std::pair<vector_t, scalar_t>>& solutions)
//        {
//                // find the closest solution
//                size_t best_index = std::string::npos;
//                scalar_t best_distance = std::numeric_limits<scalar_t>::max();

//                for (size_t index = 0; index < solutions.size(); index ++)
//                {
//                        const scalar_t distance = (state.x - solutions[index].first).lpNorm<Eigen::Infinity>();
//                        if (distance < best_distance)
//                        {
//                                best_distance = distance;
//                                best_index = index;
//                        }
//                }

//                // check accuracy
//                BOOST_REQUIRE_LT(best_index, solutions.size());

//                const scalar_t df = math::abs(state.f - solutions[best_index].second);
//                const scalar_t dx = (state.x - solutions[best_index].first).lpNorm<Eigen::Infinity>();

//                BOOST_CHECK_LE(df, math::epsilon3<scalar_t>());
//                BOOST_CHECK_LE(dx, math::epsilon3<scalar_t>());

//                // debugging
//                BOOST_CHECK_MESSAGE(
//                        dx < math::epsilon3<scalar_t>(),
//                        "failed (x) after " << state.n_iterations() <<
//                        " iterations for <" << problem << ">, <" << optimizer << "> and <" << x0.transpose() << ">!");
//                BOOST_CHECK_MESSAGE(
//                        df < math::epsilon3<scalar_t>(),
//                        "failed (f) after " << state.n_iterations() <<
//                        " iterations for <" << problem << ">, <" << optimizer << "> and <" << x0.transpose() << ">!");
//        }

        static void check_problem(const test::function_t& func)
        {
                const auto iterations = size_t(1024);
                const auto epsilon = scalar_t(1e-6);
                const auto trials = size_t(1024);

                const auto dims = func.problem().size();

                random_t<scalar_t> rgen(-1.0, +1.0);

                // generate fixed random trials
                vectors_t x0s(trials);
                for (auto& x0 : x0s)
                {
                        x0.resize(dims);
                        rgen(x0.data(), x0.data() + x0.size());
                }

                // optimizers to try
                const auto optimizers =
                {
                        min::batch_optimizer::GD,

                        min::batch_optimizer::CGD,
                        min::batch_optimizer::CGD_CD,
                        min::batch_optimizer::CGD_DY,
                        min::batch_optimizer::CGD_FR,
                        min::batch_optimizer::CGD_HS,
                        min::batch_optimizer::CGD_LS,
                        min::batch_optimizer::CGD_N,
                        min::batch_optimizer::CGD_PRP,
                        min::batch_optimizer::CGD_DYCD,
                        min::batch_optimizer::CGD_DYHS,

                        min::batch_optimizer::LBFGS
                };

                for (min::batch_optimizer optimizer : optimizers)
                {
                        const auto opt_name = text::to_string(optimizer);

                        for (size_t t = 0; t < trials; t ++)
                        {
                                const auto& x0 = x0s[t];
                                const auto x0t = x0.transpose();

                                const auto problem = func.problem();
                                const auto f0 = problem(x0);

                                // optimize
                                const auto state = ncv::minimize(
                                        problem, nullptr, nullptr, nullptr,
                                        x0, optimizer, iterations, epsilon);

                                const auto it = state.n_iterations();

                                // ignore out-of-domain solutions
                                if (!func.is_valid(state.x))
                                {
                                        continue;
                                }

                                #define NANOCV_TEST_OPTIMIZERS_DESCRIPTION \
                                        ") for (" << func.name() << ", " << opt_name << \
                                        ", x0 = [" << x0t << "], " << it << " iterations)"

                                // check function value decrease
                                const auto fx = state.f;
                                const auto fx_thres = f0 - epsilon * math::abs(f0);

                                BOOST_CHECK_MESSAGE(fx < f0,
                                        "decrease failed (" << fx << " < " << f0 <<
                                        NANOCV_TEST_OPTIMIZERS_DESCRIPTION);
                                BOOST_CHECK_MESSAGE(fx < fx_thres,
                                        "sufficient decrease failed (" << fx << " < " << fx_thres <<
                                        NANOCV_TEST_OPTIMIZERS_DESCRIPTION);

                                // check convergence
                                const auto gx = state.convergence_criteria();
                                const auto gx_thres = epsilon;

                                BOOST_CHECK_MESSAGE(gx < gx_thres,
                                        "convergence failed (" << gx << " < " << gx_thres << ", x = " << state.x.transpose() <<
                                        NANOCV_TEST_OPTIMIZERS_DESCRIPTION);

                                // todo: check local minimas (if any known)
                        }
                }
        }

        static void check_problems(const functions_t& funcs)
        {
                for (const auto& func : funcs)
                {
                        test::check_problem(*func);
                }
        }
}

BOOST_AUTO_TEST_CASE(test_optimizers)
{
        using namespace ncv;

        test::check_problems(ncv::make_beale_funcs());
//        test::check_problems(ncv::make_booth_funcs());
//        test::check_problems(ncv::make_matyas_funcs());
//        test::check_problems(ncv::make_trid_funcs(8));
//        test::check_problems(ncv::make_cauchy_funcs(8));
//        test::check_problems(ncv::make_sphere_funcs(8));
//        test::check_problems(ncv::make_powell_funcs(8));
//        test::check_problems(ncv::make_mccormick_funcs());
//        test::check_problems(ncv::make_himmelblau_funcs());
//        test::check_problems(ncv::make_rosenbrock_funcs(7));
//        test::check_problems(ncv::make_3hump_camel_funcs());
//        test::check_problems(ncv::make_dixon_price_funcs(8));
//        test::check_problems(ncv::make_sum_squares_funcs(8));
//        test::check_problems(ncv::make_goldstein_price_funcs());
//        test::check_problems(ncv::make_rotated_ellipsoid_funcs(8));
}

<commit_msg>cleanup unit test & print the number of out-of-domain solutions<commit_after>#define BOOST_TEST_DYN_LINK
#define BOOST_TEST_MODULE "test_optimizers"

#include <boost/test/unit_test.hpp>
#include "math/abs.hpp"
#include "core/logger.h"
#include "core/minimize.h"
#include "math/random.hpp"
#include "math/numeric.hpp"
#include "math/epsilon.hpp"
#include "text/to_string.hpp"

#include "func/function_trid.h"
#include "func/function_beale.h"
#include "func/function_booth.h"
#include "func/function_cauchy.h"
#include "func/function_sphere.h"
#include "func/function_matyas.h"
#include "func/function_powell.h"
#include "func/function_mccormick.h"
#include "func/function_himmelblau.h"
#include "func/function_rosenbrock.h"
#include "func/function_3hump_camel.h"
#include "func/function_sum_squares.h"
#include "func/function_dixon_price.h"
#include "func/function_goldstein_price.h"
#include "func/function_rotated_ellipsoid.h"

namespace test
{
        using namespace ncv;

//        static void check_solution(const string_t& problem, const string_t& optimizer,
//                const vector_t& x0, const opt_state_t& state, const std::vector<std::pair<vector_t, scalar_t>>& solutions)
//        {
//                // find the closest solution
//                size_t best_index = std::string::npos;
//                scalar_t best_distance = std::numeric_limits<scalar_t>::max();

//                for (size_t index = 0; index < solutions.size(); index ++)
//                {
//                        const scalar_t distance = (state.x - solutions[index].first).lpNorm<Eigen::Infinity>();
//                        if (distance < best_distance)
//                        {
//                                best_distance = distance;
//                                best_index = index;
//                        }
//                }

//                // check accuracy
//                BOOST_REQUIRE_LT(best_index, solutions.size());

//                const scalar_t df = math::abs(state.f - solutions[best_index].second);
//                const scalar_t dx = (state.x - solutions[best_index].first).lpNorm<Eigen::Infinity>();

//                BOOST_CHECK_LE(df, math::epsilon3<scalar_t>());
//                BOOST_CHECK_LE(dx, math::epsilon3<scalar_t>());

//                // debugging
//                BOOST_CHECK_MESSAGE(
//                        dx < math::epsilon3<scalar_t>(),
//                        "failed (x) after " << state.n_iterations() <<
//                        " iterations for <" << problem << ">, <" << optimizer << "> and <" << x0.transpose() << ">!");
//                BOOST_CHECK_MESSAGE(
//                        df < math::epsilon3<scalar_t>(),
//                        "failed (f) after " << state.n_iterations() <<
//                        " iterations for <" << problem << ">, <" << optimizer << "> and <" << x0.transpose() << ">!");
//        }

        static void check_problem(const test::function_t& func)
        {
                const auto iterations = size_t(64 * 1024);
                const auto epsilon = scalar_t(1e-6);
                const auto trials = size_t(1024);

                const auto dims = func.problem().size();

                random_t<scalar_t> rgen(-1.0, +1.0);

                // generate fixed random trials
                vectors_t x0s(trials);
                for (auto& x0 : x0s)
                {
                        x0.resize(dims);
                        rgen(x0.data(), x0.data() + x0.size());
                }

                // optimizers to try
                const auto optimizers =
                {
                        min::batch_optimizer::GD,

                        min::batch_optimizer::CGD,
                        min::batch_optimizer::CGD_CD,
                        min::batch_optimizer::CGD_DY,
                        min::batch_optimizer::CGD_FR,
                        min::batch_optimizer::CGD_HS,
                        min::batch_optimizer::CGD_LS,
                        min::batch_optimizer::CGD_N,
                        min::batch_optimizer::CGD_PRP,
                        min::batch_optimizer::CGD_DYCD,
                        min::batch_optimizer::CGD_DYHS,

                        min::batch_optimizer::LBFGS
                };

                for (min::batch_optimizer optimizer : optimizers)
                {
                        size_t out_of_domain = 0;

                        for (size_t t = 0; t < trials; t ++)
                        {
                                const auto problem = func.problem();

                                const auto& x0 = x0s[t];
                                const auto f0 = problem(x0);

                                // optimize
                                const auto state = ncv::minimize(
                                        problem, nullptr, nullptr, nullptr,
                                        x0, optimizer, iterations, epsilon);

                                const auto x = state.x;
                                const auto f = state.f;
                                const auto g = state.convergence_criteria();

                                const auto f_thres = f0 - epsilon * math::abs(f0);
                                const auto g_thres = epsilon;

                                // ignore out-of-domain solutions
                                if (!func.is_valid(x))
                                {
                                        out_of_domain ++;
                                        continue;
                                }

                                #define NANOCV_TEST_OPTIMIZERS_DESCRIPTION \
                                        "for (" << func.name() << ", " << text::to_string(optimizer) << \
                                        ", x = [" << x0.transpose() << "]/[" << x.transpose() << "]" << \
                                        ", f = " << f0 << "/" << f << \
                                        ", g = " << g << \
                                        ", "<< state.n_iterations() << " iterations)"

                                // check function value decrease
                                BOOST_CHECK_MESSAGE(f < f0,
                                        "decrease failed " << NANOCV_TEST_OPTIMIZERS_DESCRIPTION);
                                BOOST_CHECK_MESSAGE(f < f_thres,
                                        "sufficient decrease failed " << NANOCV_TEST_OPTIMIZERS_DESCRIPTION);

                                // check convergence
                                BOOST_CHECK_MESSAGE(g < g_thres,
                                        "convergence failed " << NANOCV_TEST_OPTIMIZERS_DESCRIPTION);

                                // todo: check local minimas (if any known)
                        }

                        log_info() << "out of domain for (" << func.name() << ", " << text::to_string(optimizer)
                                   << "): " << out_of_domain << "/" << trials << ".";
                }
        }

        static void check_problems(const functions_t& funcs)
        {
                for (const auto& func : funcs)
                {
                        test::check_problem(*func);
                }
        }
}

BOOST_AUTO_TEST_CASE(test_optimizers)
{
        using namespace ncv;

        test::check_problems(ncv::make_beale_funcs());
//        test::check_problems(ncv::make_booth_funcs());
//        test::check_problems(ncv::make_matyas_funcs());
//        test::check_problems(ncv::make_trid_funcs(8));
//        test::check_problems(ncv::make_cauchy_funcs(8));
//        test::check_problems(ncv::make_sphere_funcs(8));
//        test::check_problems(ncv::make_powell_funcs(8));
//        test::check_problems(ncv::make_mccormick_funcs());
//        test::check_problems(ncv::make_himmelblau_funcs());
//        test::check_problems(ncv::make_rosenbrock_funcs(7));
//        test::check_problems(ncv::make_3hump_camel_funcs());
//        test::check_problems(ncv::make_dixon_price_funcs(8));
//        test::check_problems(ncv::make_sum_squares_funcs(8));
//        test::check_problems(ncv::make_goldstein_price_funcs());
//        test::check_problems(ncv::make_rotated_ellipsoid_funcs(8));
}

<|endoftext|>


<commit_before>
//box

#include "box.hpp"

//default constructor unit box
Box::Box(std::string const& name) :
	Shape{name, Material{"box_material", Color{0.0f,0.0f,0.0f},
						Color{0.0f,0.0f,0.0f},
						Color{0.0f,0.0f,0.0f},
						0.0f}},
	m_min{glm::vec3{0.0f}},
	m_max{glm::vec3{1.0f}}
{}

//custom constructor
Box::Box(std::string const& name, Material const& material,
	glm::vec3 const& min, glm::vec3 const& max) :

	Shape{name, material},
	m_min{min},
	m_max{max}
{
	sortMinMax();
}

void Box::sortMinMax()
{
	if(m_min.x > m_max.x)
	{
		float buffer = m_min.x;
		m_min.x = m_max.x;
		m_max.x = buffer;
	}

	if(m_min.y > m_max.y)
	{
		float buffer = m_min.y;
		m_min.y = m_max.y;
		m_max.y = buffer;
	}

	if(m_min.z > m_max.z)
	{
		float buffer = m_min.z;
		m_min.z = m_max.z;
		m_max.z = buffer;
	}
}

//getter
glm::vec3 const& Box::get_min() const
{
	return m_min;
}

glm::vec3 const& Box::get_max() const
{
	return m_max;
}

//override area
float Box::area () const
{
	auto diff = m_max - m_min;
	return diff.x * diff.y * 2 + diff.x * diff.z * 2+ diff.y * diff.z * 2;
}

//override volume
float Box::volume () const
{
	auto diff = m_max - m_min;
	return diff.x * diff.y * diff.z;
}

//override print
std::ostream& Box::print (std::ostream& os) const
{
	os 	<< "\nshape type: box";
	//uses the default shape parent implementation of print on this instance
	//to print name and material
	Shape::print(os); //prints name and material
	os	<<   "min:        " << "(" << m_min.x << ", " << m_min.y << ", " << m_min.z << ")"
		<< "\nmax:        " << "(" << m_max.x << ", " << m_max.y << ", " << m_max.z << ")"
		<< "\n";
	return os;
}

//override intersect
bool Box::intersect(Ray const& ray, float& distance)
{
	//normalize ray
	Ray nray {ray.m_origin,ray.m_direction};
	nray.m_direction = glm::normalize(ray.m_direction);

	std::cout << ray << nray;;

	bool hit = false;

	//Parallelität zu Achsen

	//Alle Schnittpunkte mit Flächen durch Seiten der Box

/* NOTE: statt direction 1/direction verwenden, da sonst bei ray direction = 0
	ein Fehler auftritt?!
	http://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection */

	float t0x = (m_min.x - nray.m_origin.x) / nray.m_direction.x;
	float t1x = (m_max.x - nray.m_origin.x) / nray.m_direction.x;

	float t0y = (m_min.y - nray.m_origin.y) / nray.m_direction.y;
	float t1y = (m_max.y - nray.m_origin.y) / nray.m_direction.y;

	float t0z = (m_min.z - nray.m_origin.z) / nray.m_direction.z;
	float t1z = (m_max.z - nray.m_origin.z) / nray.m_direction.z;

	//far und near Schnittpunkte mit Flächen durch Seiten der Box
	float tx_far = std::max(t0x,t1x);
	float tx_near = std::min(t0x,t1x);

	float ty_far = std::max(t0y,t1y);
	float ty_near = std::min(t0y,t1y);

	float tz_far = std::max(t0z,t1z);
	float tz_near = std::min(t0z,t1z);

	//Schnittpunkte mit Ebenen, die auf der Box liegen
	float tfar = std::min(tx_far, ty_far);
	float tnear = std::max(tx_near, ty_near);

	//Wenn der Schnittpunkt mit der weiter entfernten Seite kleiner ist,
	//wird Box nicht von ray getroffen
	if(tfar < tnear)
	{
		return false;
	}

	//Betrachtung in 3D
	tfar = std::min(tfar, tz_far);
	tnear = std::max(tnear, tz_near);

	if(tfar < tnear)
	{
		return false;
	}

	distance = tnear;

	return true;
}<commit_msg>whatever<commit_after>
//box

#include "box.hpp"

//default constructor unit box
Box::Box(std::string const& name) :
	Shape{name, Material{"box_material", Color{0.0f,0.0f,0.0f},
						Color{0.0f,0.0f,0.0f},
						Color{0.0f,0.0f,0.0f},
						0.0f}},
	m_min{glm::vec3{0.0f}},
	m_max{glm::vec3{1.0f}}
{}

//custom constructor
Box::Box(std::string const& name, Material const& material,
	glm::vec3 const& min, glm::vec3 const& max) :

	Shape{name, material},
	m_min{min},
	m_max{max}
{
	sortMinMax();
}

void Box::sortMinMax()
{
	if(m_min.x > m_max.x)
	{
		float buffer = m_min.x;
		m_min.x = m_max.x;
		m_max.x = buffer;
	}

	if(m_min.y > m_max.y)
	{
		float buffer = m_min.y;
		m_min.y = m_max.y;
		m_max.y = buffer;
	}

	if(m_min.z > m_max.z)
	{
		float buffer = m_min.z;
		m_min.z = m_max.z;
		m_max.z = buffer;
	}
}

//getter
glm::vec3 const& Box::get_min() const
{
	return m_min;
}

glm::vec3 const& Box::get_max() const
{
	return m_max;
}

//override area
float Box::area () const
{
	auto diff = m_max - m_min;
	return diff.x * diff.y * 2 + diff.x * diff.z * 2+ diff.y * diff.z * 2;
}

//override volume
float Box::volume () const
{
	auto diff = m_max - m_min;
	return diff.x * diff.y * diff.z;
}

//override print
std::ostream& Box::print (std::ostream& os) const
{
	os 	<< "\nshape type: box";
	//uses the default shape parent implementation of print on this instance
	//to print name and material
	Shape::print(os); //prints name and material
	os	<<   "min:        " << "(" << m_min.x << ", " << m_min.y << ", " << m_min.z << ")"
		<< "\nmax:        " << "(" << m_max.x << ", " << m_max.y << ", " << m_max.z << ")"
		<< "\n";
	return os;
}

//override intersect
bool Box::intersect(Ray const& ray, float& distance)
{
	//normalize ray
	Ray nray {ray.m_origin,ray.m_direction};
	nray.m_direction = glm::normalize(ray.m_direction);

	std::cout << ray << nray;;

	bool hit = false;

	//Parallelität zu Achsen

	//Alle Schnittpunkte mit Flächen durch Seiten der Box

/* NOTE: statt direction 1/direction verwenden, da sonst bei ray direction = 0
	ein Fehler auftritt?!
	http://www.scratchapixel.com/lessons/3d-basic-rendering/minimal-ray-tracer-rendering-simple-shapes/ray-box-intersection */

	float t0x = (m_min.x - nray.m_origin.x) / nray.m_direction.x;
	float t1x = (m_max.x - nray.m_origin.x) / nray.m_direction.x;

	float t0y = (m_min.y - nray.m_origin.y) / nray.m_direction.y;
	float t1y = (m_max.y - nray.m_origin.y) / nray.m_direction.y;

	float t0z = (m_min.z - nray.m_origin.z) / nray.m_direction.z;
	float t1z = (m_max.z - nray.m_origin.z) / nray.m_direction.z;

	//far und near Schnittpunkte mit Flächen durch Seiten der Box
	float tx_far = std::max(t0x,t1x);
	float tx_near = std::min(t0x,t1x);

	float ty_far = std::max(t0y,t1y);
	float ty_near = std::min(t0y,t1y);

	float tz_far = std::max(t0z,t1z);
	float tz_near = std::min(t0z,t1z);

	//Schnittpunkte mit Ebenen, die auf der Box liegen
	float tfar = std::min(tx_far, ty_far);
	float tnear = std::max(tx_near, ty_near);

	//Wenn der Schnittpunkt mit der weiter entfernten Seite kleiner ist,
	//wird Box nicht von ray getroffen
	if(tfar < tnear)
	{
		return false;
	}

	//Betrachtung in 3D
	tfar = std::min(tfar, tz_far);
	tnear = std::max(tnear, tz_near);

	if(tfar < tnear)
	{
		return false;
	}

	distance = tnear;

	return true;
}
<|endoftext|>


<commit_before>/*
This file is part of BGSLibrary.

BGSLibrary 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.

BGSLibrary 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 BGSLibrary.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "TextureBGS.h"

TextureBGS::TextureBGS(){}
TextureBGS::~TextureBGS(){}

void TextureBGS::LBP(RgbImage& image, RgbImage& texture)
{
  for(int y = TEXTURE_R; y < image.Ptr()->height-TEXTURE_R; ++y)
  {
    for(int x = TEXTURE_R; x < image.Ptr()->width-TEXTURE_R; ++x)
    {
      for(int ch = 0; ch < NUM_CHANNELS; ++ch)
      {
        unsigned char textureCode = 0;
        int centerValue = (int)image(y, x, ch);

        // this only works for a texture radius of 2
        if(centerValue - (int)image(y-2, x, ch) + HYSTERSIS >= 0)
          textureCode += 1;

        if(centerValue - (int)image(y-1, x-2, ch) + HYSTERSIS >= 0)
          textureCode += 2;

        if(centerValue - (int)image(y-1, x+2, ch) + HYSTERSIS >= 0)
          textureCode += 4;

        if(centerValue - (int)image(y+1, x-2, ch) + HYSTERSIS >= 0)
          textureCode += 8;

        if(centerValue - (int)image(y+1, x+2, ch) + HYSTERSIS >= 0)
          textureCode += 16;

        if(centerValue - (int)image(y+2, x, ch) + HYSTERSIS >= 0)
          textureCode += 32;

        texture(y,x,ch) = textureCode;
      }
    }
  }
}

void TextureBGS::Histogram(RgbImage& texture, TextureHistogram* curTextureHist)
{
  // calculate histogram within a 2*REGION_R square
  for(int y = REGION_R+TEXTURE_R; y < texture.Ptr()->height-REGION_R-TEXTURE_R; ++y)
  {
    for(int x = REGION_R+TEXTURE_R; x < texture.Ptr()->width-REGION_R-TEXTURE_R; ++x)
    {
      int index = x+y*(texture.Ptr()->width);

      // clear histogram
      for(int i = 0; i < NUM_BINS; ++i)
      {
        curTextureHist[index].r[i] = 0;
        curTextureHist[index].g[i] = 0;
        curTextureHist[index].b[i] = 0;
      }

      // calculate histogram
      for(int j = -REGION_R; j <= REGION_R; ++j)
      {
        for(int i = -REGION_R; i <= REGION_R; ++i)
        {
          curTextureHist[index].r[texture(y+j,x+i,2)]++;
          curTextureHist[index].g[texture(y+j,x+i,1)]++;
          curTextureHist[index].b[texture(y+j,x+i,0)]++;
        }
      }
    }
  }
}

int TextureBGS::ProximityMeasure(TextureHistogram& bgTexture, TextureHistogram& curTextureHist)
{
  int proximity = 0;
  for(int i = 0; i < NUM_BINS; ++i)
  {
    proximity += std::min(bgTexture.r[i], curTextureHist.r[i]);
    proximity += std::min(bgTexture.g[i], curTextureHist.g[i]);
    proximity += std::min(bgTexture.b[i], curTextureHist.b[i]);
  }

  return proximity;
}

void TextureBGS::BgsCompare(TextureArray* bgModel, TextureHistogram* curTextureHist,
                unsigned char* modeArray, float threshold, BwImage& fgMask)
{
  cvZero(fgMask.Ptr());

  for(int y = REGION_R+TEXTURE_R; y < fgMask.Ptr()->height-REGION_R-TEXTURE_R; ++y)
  {
    for(int x = REGION_R+TEXTURE_R; x < fgMask.Ptr()->width-REGION_R-TEXTURE_R; ++x)
    {
      int index = x+y*(fgMask.Ptr()->width);

      // find closest matching texture in background model
      int maxProximity = -1;

      for(int m = 0; m < NUM_MODES; ++m)
      {
        int proximity = ProximityMeasure(bgModel[index].mode[m], curTextureHist[index]);

        if(proximity > maxProximity)
        {
          maxProximity = proximity;
          modeArray[index] = m;
        }
      }

      if(maxProximity < threshold)
        fgMask(y,x) = 255;
    }
  }
}

void TextureBGS::UpdateModel(BwImage& fgMask, TextureArray* bgModel,
                 TextureHistogram* curTextureHist, unsigned char* modeArray)
{
  for(int y = REGION_R+TEXTURE_R; y < fgMask.Ptr()->height-REGION_R-TEXTURE_R; ++y)
  {
    for(int x = REGION_R+TEXTURE_R; x < fgMask.Ptr()->width-REGION_R-TEXTURE_R; ++x)
    {
      int index = x+y*(fgMask.Ptr()->width);

      if(fgMask(x,y) == 0)
      {
        for(int i = 0; i < NUM_BINS; ++i)
        {
          bgModel[index].mode[modeArray[index]].r[i]
          = (unsigned char)(ALPHA*curTextureHist[index].r[i]
          + (1-ALPHA)*bgModel[index].mode[modeArray[index]].r[i] + 0.5);
        }
      }
    }
  }
}
<commit_msg>Update TextureBGS.cpp<commit_after>/*
This file is part of BGSLibrary.

BGSLibrary 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.

BGSLibrary 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 BGSLibrary.  If not, see <http://www.gnu.org/licenses/>.
*/
#include "TextureBGS.h"

TextureBGS::TextureBGS(){}
TextureBGS::~TextureBGS(){}

void TextureBGS::LBP(RgbImage& image, RgbImage& texture)
{
  for(int y = TEXTURE_R; y < image.Ptr()->height-TEXTURE_R; ++y)
  {
    for(int x = TEXTURE_R; x < image.Ptr()->width-TEXTURE_R; ++x)
    {
      for(int ch = 0; ch < NUM_CHANNELS; ++ch)
      {
        unsigned char textureCode = 0;
        int centerValue = (int)image(y, x, ch);

        // this only works for a texture radius of 2
        if(centerValue - (int)image(y-2, x, ch) + HYSTERSIS >= 0)
          textureCode += 1;

        if(centerValue - (int)image(y-1, x-2, ch) + HYSTERSIS >= 0)
          textureCode += 2;

        if(centerValue - (int)image(y-1, x+2, ch) + HYSTERSIS >= 0)
          textureCode += 4;

        if(centerValue - (int)image(y+1, x-2, ch) + HYSTERSIS >= 0)
          textureCode += 8;

        if(centerValue - (int)image(y+1, x+2, ch) + HYSTERSIS >= 0)
          textureCode += 16;

        if(centerValue - (int)image(y+2, x, ch) + HYSTERSIS >= 0)
          textureCode += 32;

        texture(y,x,ch) = textureCode;
      }
    }
  }
}

void TextureBGS::Histogram(RgbImage& texture, TextureHistogram* curTextureHist)
{
  // calculate histogram within a 2*REGION_R square
  for(int y = REGION_R+TEXTURE_R; y < texture.Ptr()->height-REGION_R-TEXTURE_R; ++y)
  {
    for(int x = REGION_R+TEXTURE_R; x < texture.Ptr()->width-REGION_R-TEXTURE_R; ++x)
    {
      int index = x+y*(texture.Ptr()->width);

      // clear histogram
      for(int i = 0; i < NUM_BINS; ++i)
      {
        curTextureHist[index].r[i] = 0;
        curTextureHist[index].g[i] = 0;
        curTextureHist[index].b[i] = 0;
      }

      // calculate histogram
      for(int j = -REGION_R; j <= REGION_R; ++j)
      {
        for(int i = -REGION_R; i <= REGION_R; ++i)
        {
          curTextureHist[index].r[texture(y+j,x+i,2)]++;
          curTextureHist[index].g[texture(y+j,x+i,1)]++;
          curTextureHist[index].b[texture(y+j,x+i,0)]++;
        }
      }
    }
  }
}

int TextureBGS::ProximityMeasure(TextureHistogram& bgTexture, TextureHistogram& curTextureHist)
{
  int proximity = 0;
  for(int i = 0; i < NUM_BINS; ++i)
  {
    proximity += std::min(bgTexture.r[i], curTextureHist.r[i]);
    proximity += std::min(bgTexture.g[i], curTextureHist.g[i]);
    proximity += std::min(bgTexture.b[i], curTextureHist.b[i]);
  }

  return proximity;
}

void TextureBGS::BgsCompare(TextureArray* bgModel, TextureHistogram* curTextureHist,
                unsigned char* modeArray, float threshold, BwImage& fgMask)
{
  cvZero(fgMask.Ptr());

  for(int y = REGION_R+TEXTURE_R; y < fgMask.Ptr()->height-REGION_R-TEXTURE_R; ++y)
  {
    for(int x = REGION_R+TEXTURE_R; x < fgMask.Ptr()->width-REGION_R-TEXTURE_R; ++x)
    {
      int index = x+y*(fgMask.Ptr()->width);

      // find closest matching texture in background model
      int maxProximity = -1;

      for(int m = 0; m < NUM_MODES; ++m)
      {
        int proximity = ProximityMeasure(bgModel[index].mode[m], curTextureHist[index]);

        if(proximity > maxProximity)
        {
          maxProximity = proximity;
          modeArray[index] = m;
        }
      }

      if(maxProximity < threshold)
        fgMask(y,x) = 255;
    }
  }
}

void TextureBGS::UpdateModel(BwImage& fgMask, TextureArray* bgModel,
                 TextureHistogram* curTextureHist, unsigned char* modeArray)
{
  for(int y = REGION_R+TEXTURE_R; y < fgMask.Ptr()->height-REGION_R-TEXTURE_R; ++y)
  {
    for(int x = REGION_R+TEXTURE_R; x < fgMask.Ptr()->width-REGION_R-TEXTURE_R; ++x)
    {
      int index = x+y*(fgMask.Ptr()->width);

      if(fgMask(y,x) == 0)
      {
        for(int i = 0; i < NUM_BINS; ++i)
        {
          bgModel[index].mode[modeArray[index]].r[i]
          = (unsigned char)(ALPHA*curTextureHist[index].r[i]
          + (1-ALPHA)*bgModel[index].mode[modeArray[index]].r[i] + 0.5);
        }
      }
    }
  }
}
<|endoftext|>


<commit_before><commit_msg>Add a couple of SAL_INFOs to trace the vector refs<commit_after><|endoftext|>


<commit_before>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2008, Red Hat, Inc., and others contributors as indicated
 * by the @authors tag. All rights reserved.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU Lesser General Public License, v. 2.1.
 * This program is distributed in the hope that it will be useful, but WITHOUT A
 * 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,
 * v.2.1 along with this distribution; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */
#include "ThreadLocalStorage.h"

#include <iostream>
#include <map>

#include "apr_portable.h"
#include "apr_thread_proc.h"

std::map<apr_os_thread_t, apr_pool_t*> tls_pools;

apr_pool_t* mutex_pool = NULL;
apr_thread_mutex_t* mutex = NULL;

extern int getKey() {
	return -1;
}

extern bool setSpecific(int key, void* threadData) {
        apr_os_thread_t os_th = apr_os_thread_current();

        std::map<apr_os_thread_t, apr_pool_t*>::iterator it = tls_pools.find(os_th);

        apr_pool_t * tls_pool = NULL;

        if(it == tls_pools.end())
        {
          apr_pool_create(&tls_pool,NULL);

	  if(mutex == NULL)
	  {
	    apr_pool_create(&mutex_pool,NULL);
	    apr_thread_mutex_create(&mutex, 0, mutex_pool);
	  }
          apr_thread_mutex_lock(mutex);
          tls_pools.insert(std::make_pair<apr_os_thread_t, apr_pool_t*>(os_th,tls_pool));
	  apr_thread_mutex_unlock(mutex);

        }
        else
           tls_pool = it->second;

        apr_thread_t* thread = NULL;
	apr_os_thread_put(&thread, &os_th, tls_pool);
	apr_status_t ret = apr_thread_data_set(threadData, (const char*)&key, NULL, thread);
	return (ret == APR_SUCCESS);
}

extern void* getSpecific(int key) {
        apr_os_thread_t os_th = apr_os_thread_current();

        std::map<apr_os_thread_t, apr_pool_t*>::iterator it = tls_pools.find(os_th);

        apr_pool_t * tls_pool = NULL;
        if(it == tls_pools.end())
        {
          return NULL;
        }
        else
        {
           tls_pool = it->second;
        }

        apr_thread_t* thread = NULL;
        apr_os_thread_put(&thread, &os_th, tls_pool);
        void* threadData = NULL;
        apr_thread_data_get(&threadData, (const char*)&key, thread);
	return threadData;
}

extern bool destroySpecific(int key) {
	return setSpecific(key, 0);
}

char* TSS_TPERESET = (char*) "0";
char* TSS_TPEBADDESC = (char*) "2";
char* TSS_TPEBLOCK = (char*) "3";
char* TSS_TPEINVAL = (char*) "4";
char* TSS_TPELIMIT = (char*) "5";
char* TSS_TPENOENT = (char*) "6";
char* TSS_TPEOS = (char*) "7";
char* TSS_TPEPROTO = (char*) "9";
char* TSS_TPESVCERR = (char*) "10";
char* TSS_TPESVCFAIL = (char*) "11";
char* TSS_TPESYSTEM = (char*) "12";
char* TSS_TPETIME = (char*) "13";
char* TSS_TPETRAN = (char*) "14";
char* TSS_TPGOTSIG = (char*) "15";
char* TSS_TPEITYPE = (char*) "17";
char* TSS_TPEOTYPE = (char*) "18";
char* TSS_TPEEVENT = (char*) "22";
char* TSS_TPEMATCH = (char*) "23";
<commit_msg>JBTM-2871 Fix STL compilation error on Fedora 25<commit_after>/*
 * JBoss, Home of Professional Open Source
 * Copyright 2008, Red Hat, Inc., and others contributors as indicated
 * by the @authors tag. All rights reserved.
 * See the copyright.txt in the distribution for a
 * full listing of individual contributors.
 * This copyrighted material is made available to anyone wishing to use,
 * modify, copy, or redistribute it subject to the terms and conditions
 * of the GNU Lesser General Public License, v. 2.1.
 * This program is distributed in the hope that it will be useful, but WITHOUT A
 * 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,
 * v.2.1 along with this distribution; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA  02110-1301, USA.
 */
#include "ThreadLocalStorage.h"

#include <iostream>
#include <map>

#include "apr_portable.h"
#include "apr_thread_proc.h"

std::map<apr_os_thread_t, apr_pool_t*> tls_pools;

apr_pool_t* mutex_pool = NULL;
apr_thread_mutex_t* mutex = NULL;

extern int getKey() {
	return -1;
}

extern bool setSpecific(int key, void* threadData) {
        apr_os_thread_t os_th = apr_os_thread_current();

        std::map<apr_os_thread_t, apr_pool_t*>::iterator it = tls_pools.find(os_th);

        apr_pool_t * tls_pool = NULL;

        if(it == tls_pools.end())
        {
          apr_pool_create(&tls_pool,NULL);

	  if(mutex == NULL)
	  {
	    apr_pool_create(&mutex_pool,NULL);
	    apr_thread_mutex_create(&mutex, 0, mutex_pool);
	  }
          apr_thread_mutex_lock(mutex);
          tls_pools.insert(std::make_pair(os_th,tls_pool));
	  apr_thread_mutex_unlock(mutex);

        }
        else
           tls_pool = it->second;

        apr_thread_t* thread = NULL;
	apr_os_thread_put(&thread, &os_th, tls_pool);
	apr_status_t ret = apr_thread_data_set(threadData, (const char*)&key, NULL, thread);
	return (ret == APR_SUCCESS);
}

extern void* getSpecific(int key) {
        apr_os_thread_t os_th = apr_os_thread_current();

        std::map<apr_os_thread_t, apr_pool_t*>::iterator it = tls_pools.find(os_th);

        apr_pool_t * tls_pool = NULL;
        if(it == tls_pools.end())
        {
          return NULL;
        }
        else
        {
           tls_pool = it->second;
        }

        apr_thread_t* thread = NULL;
        apr_os_thread_put(&thread, &os_th, tls_pool);
        void* threadData = NULL;
        apr_thread_data_get(&threadData, (const char*)&key, thread);
	return threadData;
}

extern bool destroySpecific(int key) {
	return setSpecific(key, 0);
}

char* TSS_TPERESET = (char*) "0";
char* TSS_TPEBADDESC = (char*) "2";
char* TSS_TPEBLOCK = (char*) "3";
char* TSS_TPEINVAL = (char*) "4";
char* TSS_TPELIMIT = (char*) "5";
char* TSS_TPENOENT = (char*) "6";
char* TSS_TPEOS = (char*) "7";
char* TSS_TPEPROTO = (char*) "9";
char* TSS_TPESVCERR = (char*) "10";
char* TSS_TPESVCFAIL = (char*) "11";
char* TSS_TPESYSTEM = (char*) "12";
char* TSS_TPETIME = (char*) "13";
char* TSS_TPETRAN = (char*) "14";
char* TSS_TPGOTSIG = (char*) "15";
char* TSS_TPEITYPE = (char*) "17";
char* TSS_TPEOTYPE = (char*) "18";
char* TSS_TPEEVENT = (char*) "22";
char* TSS_TPEMATCH = (char*) "23";
<|endoftext|>


<commit_before>/*
 Copyright (c) 2012, The Cinder Project, All rights reserved.

 This code is intended for use with the Cinder C++ library: http://libcinder.org

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
*/

#include "cinder/app/Renderer.h"

#if !defined( CINDER_WINRT)
	#include "cinder/gl/platform.h"
#endif

#include "cinder/app/AppBase.h"

#if defined( CINDER_COCOA )
	#include "cinder/cocoa/CinderCocoa.h"
	#if defined( CINDER_MAC )
		#include <ApplicationServices/ApplicationServices.h>
		#import <Cocoa/Cocoa.h>
		#import "cinder/app/cocoa/RendererImpl2dMacQuartz.h"
	#elif defined( CINDER_COCOA_TOUCH )
		#include "cinder/cocoa/CinderCocoaTouch.h"
		#import "cinder/app/cocoa/RendererImpl2dCocoaTouchQuartz.h"
	#endif

#elif defined( CINDER_MSW )
	#include "cinder/app/msw/AppImplMsw.h"
	#include "cinder/app/msw/RendererImpl2dGdi.h"
#endif

namespace cinder { namespace app {

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Renderer
Renderer::Renderer( const Renderer &renderer )
{
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Renderer2d
#if defined( CINDER_COCOA )

Renderer2d::Renderer2d( const Renderer2d &renderer )
	: Renderer( renderer )
{
	mImpl = 0;
}

Renderer2d::Renderer2d()
	: Renderer(), mImpl( 0 )
{
}

#if defined( CINDER_MAC )
Renderer2d::~Renderer2d()
{
	::CFRelease( mImpl );
}

void Renderer2d::setup( CGRect frame, NSView *cinderView, RendererRef /*sharedRenderer*/, bool retinaEnabled )
{
	mImpl = [[RendererImpl2dMacQuartz alloc] initWithFrame:NSRectFromCGRect(frame) cinderView:cinderView];
	// This is necessary for Objective-C garbage collection to do the right thing
	::CFRetain( mImpl );
}

#else

void Renderer2d::setup( const Area &frame, UIView *cinderView, RendererRef /*sharedRenderer*/ )
{
	mImpl = [[RendererImpl2dCocoaTouchQuartz alloc] initWithFrame:cinder::cocoa::createCgRect(frame) cinderView:cinderView];
}

#endif

CGContextRef Renderer2d::getCgContext()
{
	return [mImpl getCGContextRef];
}

void Renderer2d::startDraw()
{
	[mImpl makeCurrentContext];
}

void Renderer2d::finishDraw()
{
	[mImpl flushBuffer];
}

void Renderer2d::setFrameSize( int width, int height )
{
#if defined( CINDER_MAC )
	[mImpl setFrameSize:NSSizeToCGSize(NSMakeSize( width, height ))];
#endif
}

void Renderer2d::defaultResize()
{
	[mImpl defaultResize];
}

void Renderer2d::makeCurrentContext( bool /*force*/ )
{
	[mImpl makeCurrentContext];
}

Surface Renderer2d::copyWindowSurface( const Area &area, int32_t windowHeightPixels )
{
#if defined( CINDER_MAC )
	NSBitmapImageRep *rep = [mImpl getContents:area];
	if( rep )
		return *cocoa::convertNsBitmapDataRep( rep, true );
	else
		return Surface( 0, 0, false );
#elif defined( CINDER_COCOA_TOUCH )
	UIImage *image = [mImpl getContents:area];
	if( image )
		return *cocoa::convertUiImage( image, true );
	else
		return Surface( 0, 0, false );
#endif
}
#endif

#if defined( CINDER_MSW )

Renderer2d::Renderer2d( const Renderer2d &renderer )
	: Renderer( renderer )
{
	mImpl = 0;
	mDoubleBuffer = renderer.mDoubleBuffer;
}

Renderer2d::Renderer2d( bool doubleBuffer, bool paintEvents )
	: Renderer(), mDoubleBuffer(doubleBuffer), mPaintEvents( paintEvents )
{
}

void Renderer2d::setup( HWND wnd, HDC dc, RendererRef /*sharedRenderer*/ )
{
	mWnd = wnd;
	mImpl = new RendererImpl2dGdi( mDoubleBuffer, mPaintEvents );
	mImpl->initialize( wnd, dc, RendererRef() /* we don't use shared renderers on GDI */ );
}

void Renderer2d::kill()
{
	mImpl->kill();
}

HDC Renderer2d::getDc()
{
	return mImpl->getDc();
}

void Renderer2d::prepareToggleFullScreen()
{
	mImpl->prepareToggleFullScreen();
}

void Renderer2d::finishToggleFullScreen()
{
	mImpl->finishToggleFullScreen();
}

void Renderer2d::startDraw()
{
	mImpl->makeCurrentContext();
}

void Renderer2d::finishDraw()
{
	mImpl->swapBuffers();
}

void Renderer2d::defaultResize()
{
	mImpl->defaultResize();
}

Surface	Renderer2d::copyWindowSurface( const Area &area, int32_t windowHeightPixels )
{
	return mImpl->copyWindowContents( area );
}

#endif // defined( CINDER_MSW )

} } // namespace cinder::app
<commit_msg>Fixing issue freeing nullptr on default constructed Renderer2d on Mac<commit_after>/*
 Copyright (c) 2012, The Cinder Project, All rights reserved.

 This code is intended for use with the Cinder C++ library: http://libcinder.org

 Redistribution and use in source and binary forms, with or without modification, are permitted provided that
 the following conditions are met:

    * Redistributions of source code must retain the above copyright notice, this list of conditions and
	the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and
	the following disclaimer in the documentation and/or other materials provided with the distribution.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED
 WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
 PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
 ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
 TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
*/

#include "cinder/app/Renderer.h"

#if !defined( CINDER_WINRT)
	#include "cinder/gl/platform.h"
#endif

#include "cinder/app/AppBase.h"

#if defined( CINDER_COCOA )
	#include "cinder/cocoa/CinderCocoa.h"
	#if defined( CINDER_MAC )
		#include <ApplicationServices/ApplicationServices.h>
		#import <Cocoa/Cocoa.h>
		#import "cinder/app/cocoa/RendererImpl2dMacQuartz.h"
	#elif defined( CINDER_COCOA_TOUCH )
		#include "cinder/cocoa/CinderCocoaTouch.h"
		#import "cinder/app/cocoa/RendererImpl2dCocoaTouchQuartz.h"
	#endif

#elif defined( CINDER_MSW )
	#include "cinder/app/msw/AppImplMsw.h"
	#include "cinder/app/msw/RendererImpl2dGdi.h"
#endif

namespace cinder { namespace app {

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Renderer
Renderer::Renderer( const Renderer &renderer )
{
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Renderer2d
#if defined( CINDER_COCOA )

Renderer2d::Renderer2d( const Renderer2d &renderer )
	: Renderer( renderer ), mImpl( nullptr )
{
}

Renderer2d::Renderer2d()
	: Renderer(), mImpl( nullptr )
{
}

#if defined( CINDER_MAC )
Renderer2d::~Renderer2d()
{
	if( mImpl )
		::CFRelease( mImpl );
}

void Renderer2d::setup( CGRect frame, NSView *cinderView, RendererRef /*sharedRenderer*/, bool retinaEnabled )
{
	mImpl = [[RendererImpl2dMacQuartz alloc] initWithFrame:NSRectFromCGRect(frame) cinderView:cinderView];
	// This is necessary for Objective-C garbage collection to do the right thing
	::CFRetain( mImpl );
}

#else

void Renderer2d::setup( const Area &frame, UIView *cinderView, RendererRef /*sharedRenderer*/ )
{
	mImpl = [[RendererImpl2dCocoaTouchQuartz alloc] initWithFrame:cinder::cocoa::createCgRect(frame) cinderView:cinderView];
}

#endif

CGContextRef Renderer2d::getCgContext()
{
	return [mImpl getCGContextRef];
}

void Renderer2d::startDraw()
{
	[mImpl makeCurrentContext];
}

void Renderer2d::finishDraw()
{
	[mImpl flushBuffer];
}

void Renderer2d::setFrameSize( int width, int height )
{
#if defined( CINDER_MAC )
	[mImpl setFrameSize:NSSizeToCGSize(NSMakeSize( width, height ))];
#endif
}

void Renderer2d::defaultResize()
{
	[mImpl defaultResize];
}

void Renderer2d::makeCurrentContext( bool /*force*/ )
{
	[mImpl makeCurrentContext];
}

Surface Renderer2d::copyWindowSurface( const Area &area, int32_t windowHeightPixels )
{
#if defined( CINDER_MAC )
	NSBitmapImageRep *rep = [mImpl getContents:area];
	if( rep )
		return *cocoa::convertNsBitmapDataRep( rep, true );
	else
		return Surface( 0, 0, false );
#elif defined( CINDER_COCOA_TOUCH )
	UIImage *image = [mImpl getContents:area];
	if( image )
		return *cocoa::convertUiImage( image, true );
	else
		return Surface( 0, 0, false );
#endif
}
#endif

#if defined( CINDER_MSW )

Renderer2d::Renderer2d( const Renderer2d &renderer )
	: Renderer( renderer )
{
	mImpl = 0;
	mDoubleBuffer = renderer.mDoubleBuffer;
}

Renderer2d::Renderer2d( bool doubleBuffer, bool paintEvents )
	: Renderer(), mDoubleBuffer(doubleBuffer), mPaintEvents( paintEvents )
{
}

void Renderer2d::setup( HWND wnd, HDC dc, RendererRef /*sharedRenderer*/ )
{
	mWnd = wnd;
	mImpl = new RendererImpl2dGdi( mDoubleBuffer, mPaintEvents );
	mImpl->initialize( wnd, dc, RendererRef() /* we don't use shared renderers on GDI */ );
}

void Renderer2d::kill()
{
	mImpl->kill();
}

HDC Renderer2d::getDc()
{
	return mImpl->getDc();
}

void Renderer2d::prepareToggleFullScreen()
{
	mImpl->prepareToggleFullScreen();
}

void Renderer2d::finishToggleFullScreen()
{
	mImpl->finishToggleFullScreen();
}

void Renderer2d::startDraw()
{
	mImpl->makeCurrentContext();
}

void Renderer2d::finishDraw()
{
	mImpl->swapBuffers();
}

void Renderer2d::defaultResize()
{
	mImpl->defaultResize();
}

Surface	Renderer2d::copyWindowSurface( const Area &area, int32_t windowHeightPixels )
{
	return mImpl->copyWindowContents( area );
}

#endif // defined( CINDER_MSW )

} } // namespace cinder::app
<|endoftext|>