<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

#include <jni.h>
#include <android/sensor.h>
#include <android_native_app_glue.h>
#include "Allocator.h"
#include "Device.h"
#include "Log.h"
#include "OsEventQueue.h"
#include "Renderer.h"
#include "Touch.h"
#include "OsWindow.h"

namespace crown
{

ANativeWindow* g_android_window;
AAssetManager* g_android_asset_manager;

class AndroidDevice : public Device
{
public:

	//-----------------------------------------------------------------------------
	AndroidDevice()
		: m_game_thread("game_thread")
	{
		#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
			m_fileserver = 1;
		#endif
	}

	//-----------------------------------------------------------------------------
	void display_modes(Array<DisplayMode>& /*modes*/)
	{
		// Do nothing
	}

	//-----------------------------------------------------------------------------
	void set_display_mode(uint32_t /*id*/)
	{
		// Do nothing
	}

	//-----------------------------------------------------------------------------
	void set_fullscreen(bool /*full*/)
	{
		// Do nothing
	}

	void run(struct android_app* app)
	{
		app->userData = this;
		app->onAppCmd = crown::AndroidDevice::on_app_cmd;
		app->onInputEvent = crown::AndroidDevice::on_input_event;
		g_android_asset_manager = app->activity->assetManager;

		while (app->destroyRequested == 0)
		{
			int32_t num;
			android_poll_source* source;
			/*int32_t id =*/ ALooper_pollAll(-1, NULL, &num, (void**)&source);

			if (NULL != source)
			{
				source->process(app, source);
			}
		}

		m_game_thread.stop();
	}

	//-----------------------------------------------------------------------------
	int32_t run(int, char**)
	{
		return 0;
	}

	//-----------------------------------------------------------------------------
	void loop()
	{
		#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
			m_console = CE_NEW(default_allocator(), ConsoleServer)();
			m_console->init(m_console_port, false);
		#endif

		Device::init();

		// Push metrics here since Android does not trigger APP_CMD_WINDOW_RESIZED
		const int32_t width = ANativeWindow_getWidth(g_android_window);
		const int32_t height = ANativeWindow_getHeight(g_android_window);
		m_queue.push_metrics_event(0, 0, width, height);

		while (is_running() && !process_events())
		{
			#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
				m_console->update();
			#endif

			Device::frame();
			m_touch->update();
			m_keyboard->update();
		}

		Device::shutdown();

		#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
			m_console->shutdown();
			CE_DELETE(default_allocator(), m_console);
		#endif
	}

	//-----------------------------------------------------------------------------
	static int32_t main_loop(void* thiz)
	{
		return ((AndroidDevice*) thiz)->loop();
	}

	//-----------------------------------------------------------------------------
	bool process_events()
	{
		OsEvent event;

		while (m_queue.pop_event(event))
		{
			if (event.type == OsEvent::NONE) continue;

			switch (event.type)
			{
				case OsEvent::TOUCH:
				{
					const OsTouchEvent& ev = event.touch;
					switch (ev.type)
					{
						case OsTouchEvent::POINTER: m_touch->set_pointer_state(ev.x, ev.y, ev.pointer_id, ev.pressed); break;
						case OsTouchEvent::MOVE: m_touch->set_position(ev.pointer_id, ev.x, ev.y); break;
						default: CE_FATAL("Oops, unknown touch event type"); break;
					}

					break;
				}
				case OsEvent::KEYBOARD:
				{
					const OsKeyboardEvent& ev = event.keyboard;
					m_keyboard->set_button_state(ev.button, ev.pressed);
					break;
				}
				case OsEvent::METRICS:
				{
					const OsMetricsEvent& ev = event.metrics;
					m_window->m_x = ev.x;
					m_window->m_y = ev.y;
					m_window->m_width = ev.width;
					m_window->m_height = ev.height;
					break;
				}
				case OsEvent::EXIT:
				{
					return true;
				}
				case OsEvent::PAUSE:
				{
					pause();
					break;
				}
				case OsEvent::RESUME:
				{
					unpause();
					break;
				}
				default:
				{
					CE_FATAL("Unknown Os Event");
					break;
				}
			}
		}

		return false;
	}

	//-----------------------------------------------------------------------------
	static void on_app_cmd(struct android_app* app, int32_t cmd)
	{
		((AndroidDevice*) app->userData)->process_command(app, cmd);
	}

	//-----------------------------------------------------------------------------
	void process_command(struct android_app* app, int32_t cmd)
	{
		switch (cmd)
		{
			case APP_CMD_SAVE_STATE:
			{
				// // The system has asked us to save our current state.  Do so.
				// engine->app->savedState = malloc(sizeof(struct saved_state));
				// *((struct saved_state*)engine->app->savedState) = engine->state;
				// engine->app->savedStateSize = sizeof(struct saved_state);
				break;
			}
			case APP_CMD_INIT_WINDOW:
			{
				CE_ASSERT(app->window != NULL, "Android window is NULL");
				g_android_window = app->window;
				m_game_thread.start(main_loop, (void*)this);
				break;
			}
			case APP_CMD_TERM_WINDOW:
			{
				// The window is being hidden or closed, clean it up.
				break;
			}
			case APP_CMD_WINDOW_RESIZED:
			{
				// Not triggered by Android
				break;
			}
			case APP_CMD_GAINED_FOCUS:
			{
				break;
			}
			case APP_CMD_LOST_FOCUS:
			{
				break;
			}
			case APP_CMD_DESTROY:
			{
				m_queue.push_exit_event(0);
				break;
			}
		}
	}

	//-----------------------------------------------------------------------------
	static int32_t on_input_event(struct android_app* app, AInputEvent* event)
	{
		return ((AndroidDevice*) app->userData)->process_input(app, event);
	}

	//-----------------------------------------------------------------------------
	int32_t process_input(struct android_app* app, AInputEvent* event)
	{
		if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION)
		{
			const int32_t action = AMotionEvent_getAction(event);
			const int32_t pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
			const int32_t pointerCount = AMotionEvent_getPointerCount(event);

			const int32_t pointerId = AMotionEvent_getPointerId(event, pointerIndex);
			const float x = AMotionEvent_getX(event, pointerIndex);
			const float y = AMotionEvent_getY(event, pointerIndex);

			const int32_t actionMasked = (action & AMOTION_EVENT_ACTION_MASK);

			switch (actionMasked)
			{
				case AMOTION_EVENT_ACTION_DOWN:
				case AMOTION_EVENT_ACTION_POINTER_DOWN:
				{
					m_queue.push_touch_event((uint16_t) x, (uint16_t) y, (uint8_t) pointerId, true);
					break;
				}
				case AMOTION_EVENT_ACTION_UP:
				case AMOTION_EVENT_ACTION_POINTER_UP:
				{
					m_queue.push_touch_event((uint16_t) x, (uint16_t) y, (uint8_t) pointerId, false);
					break;
				}
				case AMOTION_EVENT_ACTION_OUTSIDE:
				case AMOTION_EVENT_ACTION_CANCEL:
				{
					m_queue.push_touch_event((uint16_t) x, (uint16_t) y, (uint8_t) pointerId, false);
					break;
				}
				case AMOTION_EVENT_ACTION_MOVE:
				{
					for (int index = 0; index < pointerCount; index++)
					{
						const float xx = AMotionEvent_getX(event, index);
						const float yy = AMotionEvent_getY(event, index);
						const int32_t id = AMotionEvent_getPointerId(event, index);
						m_queue.push_touch_event((uint16_t) xx, (uint16_t) yy, (uint8_t) id);
					}
					break;
				}
			}

			return 1;
		}
		else if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY)
		{
			const int32_t keycode = AKeyEvent_getKeyCode(event);
			const int32_t keyaction = AKeyEvent_getAction(event);

			if (keycode == AKEYCODE_BACK)
			{
				m_queue.push_keyboard_event(0, KeyboardButton::ESCAPE, keyaction == AKEY_EVENT_ACTION_DOWN ? true : false);
			}

			return 1;
		}

		return 0;
	}

private:

	OsEventQueue m_queue;
	OsThread m_game_thread;
};

} // namespace crown

void android_main(struct android_app* app)
{
	// Make sure glue isn't stripped.
	app_dummy();

	crown::memory::init();
	crown::os::init_os();
	crown::AndroidDevice* engine = CE_NEW(crown::default_allocator(), crown::AndroidDevice)();
	crown::set_device(engine);

	engine->run(app);

	CE_DELETE(crown::default_allocator(), engine);
	crown::memory::shutdown();
}
<commit_msg>Force exit fron android activity<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/

#include <jni.h>
#include <android/sensor.h>
#include <android_native_app_glue.h>
#include "Allocator.h"
#include "Device.h"
#include "Log.h"
#include "OsEventQueue.h"
#include "Renderer.h"
#include "Touch.h"
#include "OsWindow.h"

namespace crown
{

ANativeWindow* g_android_window;
AAssetManager* g_android_asset_manager;

class AndroidDevice : public Device
{
public:

	//-----------------------------------------------------------------------------
	AndroidDevice()
		: m_game_thread("game_thread")
	{
		#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
			m_fileserver = 1;
		#endif
	}

	//-----------------------------------------------------------------------------
	void display_modes(Array<DisplayMode>& /*modes*/)
	{
		// Do nothing
	}

	//-----------------------------------------------------------------------------
	void set_display_mode(uint32_t /*id*/)
	{
		// Do nothing
	}

	//-----------------------------------------------------------------------------
	void set_fullscreen(bool /*full*/)
	{
		// Do nothing
	}

	void run(struct android_app* app)
	{
		app->userData = this;
		app->onAppCmd = crown::AndroidDevice::on_app_cmd;
		app->onInputEvent = crown::AndroidDevice::on_input_event;
		g_android_asset_manager = app->activity->assetManager;

		while (app->destroyRequested == 0)
		{
			int32_t num;
			android_poll_source* source;
			/*int32_t id =*/ ALooper_pollAll(-1, NULL, &num, (void**)&source);

			if (NULL != source)
			{
				source->process(app, source);
			}
		}

		m_game_thread.stop();
	}

	//-----------------------------------------------------------------------------
	int32_t run(int, char**)
	{
		return 0;
	}

	//-----------------------------------------------------------------------------
	int32_t loop()
	{
		#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
			m_console = CE_NEW(default_allocator(), ConsoleServer)();
			m_console->init(m_console_port, false);
		#endif

		Device::init();

		// Push metrics here since Android does not trigger APP_CMD_WINDOW_RESIZED
		const int32_t width = ANativeWindow_getWidth(g_android_window);
		const int32_t height = ANativeWindow_getHeight(g_android_window);
		m_queue.push_metrics_event(0, 0, width, height);

		while (is_running() && !process_events())
		{
			#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
				m_console->update();
			#endif

			Device::frame();
			m_touch->update();
			m_keyboard->update();
		}

		Device::shutdown();

		#if defined(CROWN_DEBUG) || defined(CROWN_DEVELOPMENT)
			m_console->shutdown();
			CE_DELETE(default_allocator(), m_console);
		#endif

		exit(EXIT_SUCCESS);
		return 0;
	}

	//-----------------------------------------------------------------------------
	static int32_t main_loop(void* thiz)
	{
		return ((AndroidDevice*) thiz)->loop();
	}

	//-----------------------------------------------------------------------------
	bool process_events()
	{
		OsEvent event;

		while (m_queue.pop_event(event))
		{
			if (event.type == OsEvent::NONE) continue;

			switch (event.type)
			{
				case OsEvent::TOUCH:
				{
					const OsTouchEvent& ev = event.touch;
					switch (ev.type)
					{
						case OsTouchEvent::POINTER: m_touch->set_pointer_state(ev.x, ev.y, ev.pointer_id, ev.pressed); break;
						case OsTouchEvent::MOVE: m_touch->set_position(ev.pointer_id, ev.x, ev.y); break;
						default: CE_FATAL("Oops, unknown touch event type"); break;
					}

					break;
				}
				case OsEvent::KEYBOARD:
				{
					const OsKeyboardEvent& ev = event.keyboard;
					m_keyboard->set_button_state(ev.button, ev.pressed);
					break;
				}
				case OsEvent::METRICS:
				{
					const OsMetricsEvent& ev = event.metrics;
					m_window->m_x = ev.x;
					m_window->m_y = ev.y;
					m_window->m_width = ev.width;
					m_window->m_height = ev.height;
					break;
				}
				case OsEvent::EXIT:
				{
					return true;
				}
				case OsEvent::PAUSE:
				{
					pause();
					break;
				}
				case OsEvent::RESUME:
				{
					unpause();
					break;
				}
				default:
				{
					CE_FATAL("Unknown Os Event");
					break;
				}
			}
		}

		return false;
	}

	//-----------------------------------------------------------------------------
	static void on_app_cmd(struct android_app* app, int32_t cmd)
	{
		((AndroidDevice*) app->userData)->process_command(app, cmd);
	}

	//-----------------------------------------------------------------------------
	void process_command(struct android_app* app, int32_t cmd)
	{
		switch (cmd)
		{
			case APP_CMD_SAVE_STATE:
			{
				// // The system has asked us to save our current state.  Do so.
				// engine->app->savedState = malloc(sizeof(struct saved_state));
				// *((struct saved_state*)engine->app->savedState) = engine->state;
				// engine->app->savedStateSize = sizeof(struct saved_state);
				break;
			}
			case APP_CMD_INIT_WINDOW:
			{
				CE_ASSERT(app->window != NULL, "Android window is NULL");
				g_android_window = app->window;
				m_game_thread.start(main_loop, (void*)this);
				break;
			}
			case APP_CMD_TERM_WINDOW:
			{
				// The window is being hidden or closed, clean it up.
				break;
			}
			case APP_CMD_WINDOW_RESIZED:
			{
				// Not triggered by Android
				break;
			}
			case APP_CMD_GAINED_FOCUS:
			{
				break;
			}
			case APP_CMD_LOST_FOCUS:
			{
				break;
			}
			case APP_CMD_DESTROY:
			{
				m_queue.push_exit_event(0);
				break;
			}
		}
	}

	//-----------------------------------------------------------------------------
	static int32_t on_input_event(struct android_app* app, AInputEvent* event)
	{
		return ((AndroidDevice*) app->userData)->process_input(app, event);
	}

	//-----------------------------------------------------------------------------
	int32_t process_input(struct android_app* app, AInputEvent* event)
	{
		if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_MOTION)
		{
			const int32_t action = AMotionEvent_getAction(event);
			const int32_t pointerIndex = (action & AMOTION_EVENT_ACTION_POINTER_INDEX_MASK) >> AMOTION_EVENT_ACTION_POINTER_INDEX_SHIFT;
			const int32_t pointerCount = AMotionEvent_getPointerCount(event);

			const int32_t pointerId = AMotionEvent_getPointerId(event, pointerIndex);
			const float x = AMotionEvent_getX(event, pointerIndex);
			const float y = AMotionEvent_getY(event, pointerIndex);

			const int32_t actionMasked = (action & AMOTION_EVENT_ACTION_MASK);

			switch (actionMasked)
			{
				case AMOTION_EVENT_ACTION_DOWN:
				case AMOTION_EVENT_ACTION_POINTER_DOWN:
				{
					m_queue.push_touch_event((uint16_t) x, (uint16_t) y, (uint8_t) pointerId, true);
					break;
				}
				case AMOTION_EVENT_ACTION_UP:
				case AMOTION_EVENT_ACTION_POINTER_UP:
				{
					m_queue.push_touch_event((uint16_t) x, (uint16_t) y, (uint8_t) pointerId, false);
					break;
				}
				case AMOTION_EVENT_ACTION_OUTSIDE:
				case AMOTION_EVENT_ACTION_CANCEL:
				{
					m_queue.push_touch_event((uint16_t) x, (uint16_t) y, (uint8_t) pointerId, false);
					break;
				}
				case AMOTION_EVENT_ACTION_MOVE:
				{
					for (int index = 0; index < pointerCount; index++)
					{
						const float xx = AMotionEvent_getX(event, index);
						const float yy = AMotionEvent_getY(event, index);
						const int32_t id = AMotionEvent_getPointerId(event, index);
						m_queue.push_touch_event((uint16_t) xx, (uint16_t) yy, (uint8_t) id);
					}
					break;
				}
			}

			return 1;
		}
		else if (AInputEvent_getType(event) == AINPUT_EVENT_TYPE_KEY)
		{
			const int32_t keycode = AKeyEvent_getKeyCode(event);
			const int32_t keyaction = AKeyEvent_getAction(event);

			if (keycode == AKEYCODE_BACK)
			{
				m_queue.push_keyboard_event(0, KeyboardButton::ESCAPE, keyaction == AKEY_EVENT_ACTION_DOWN ? true : false);
			}

			return 1;
		}

		return 0;
	}

private:

	OsEventQueue m_queue;
	OsThread m_game_thread;
};

} // namespace crown

void android_main(struct android_app* app)
{
	// Make sure glue isn't stripped.
	app_dummy();

	crown::memory::init();
	crown::os::init_os();
	crown::AndroidDevice* engine = CE_NEW(crown::default_allocator(), crown::AndroidDevice)();
	crown::set_device(engine);

	engine->run(app);

	CE_DELETE(crown::default_allocator(), engine);
	crown::memory::shutdown();
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <list>
#include <functional>
#include <random>
#include <memory>
#include "GL/gl.h"
#include "GL/wglext.h"
#include "GL/glu.h"
#include "GLFW/glfw3.h"
#include "countof.h"

using std::cout;
using std::cerr;
using std::endl;
using std::vector;
using std::list;
using std::function;

void ding_r(float x, float y, float r);
void ding(float x, float y, float r=0) {
	if (r) {
		ding_r(x, y, r);
		return;
	}
	float a = 0.4;
	float b = 0.4;
	float p[] = {
		x+a, y,
		x, y+b,
		x-a, y,
		x, y-b
	};
	int p_c = COUNTOF(p);
	glEnableClientState(GL_VERTEX_ARRAY);
	glVertexPointer(2, GL_FLOAT, 0, p);
	glDrawArrays(GL_LINE_LOOP, 0, p_c/2);
}

void ding_r(float x, float y, float r) {
	float a = 0.4;
	float b = 0.4;
	float p[] = {
		a, 0,
		0, b,
		-a, 0,
		0, -b
	};
	int p_c = COUNTOF(p);
	for (int i=0; i<p_c; i+=2) {
		float xx = cos(r) * p[i] - sin(r) * p[i+1];
		float yy = sin(r) * p[i] + cos(r) * p[i+1];
		p[i] = xx + x;;
		p[i+1] = yy + y;
	}
	glEnableClientState(GL_VERTEX_ARRAY);
	glVertexPointer(2, GL_FLOAT, 0, p);
	glDrawArrays(GL_LINE_LOOP, 0, p_c/2);
}

struct vec2 {
	float x;
	float y;

	float dist2(vec2 b) {
		float dx = b.x-x, dy = b.y-y, len2=dx*dx+dy*dy;
		return len2;
	}
};

std::mt19937 rng;

typedef unsigned long long guid;
guid random_guid() {
	return std::uniform_int_distribution<guid>()(rng);
}

struct Object {
	Object() {}
	Object(vec2 pos, vec2 speed) : pos(pos), speed(speed) {}
	long guid = random_guid();
	vec2 pos;
	vec2 speed;

	bool operator==(const Object& other) {
		return guid == other.guid;
	}
};

template<typename T, typename... Args>
struct OwnedCallback {
	Object& o;
	function<T(Args...)> cb;

	T operator()(Args... args) {
		return cb(args...);
	}
};

struct Collision {
	// For now, simple quadratic collision
	struct Entry {
		Object& o;
	};
	list<Entry> chaff;
	list<Entry> bullets;

	void check(function<void(Object&, Object&)> fn) {
		float size = 0.1;
		for (auto x : chaff) {
			for (auto y : bullets) {
				if (x.o.pos.dist2(y.o.pos) < size*size) fn(x.o, y.o);
			}
		}
		for (auto x : chaff) {
			for (auto y : chaff) {
				if (x.o == y.o) continue;
				if (x.o.pos.dist2(y.o.pos) < size*size) fn(x.o, y.o);
			}
		}
	}
};

struct World {
	list<Object> objects; // could be a vector, but reallocs will kill references in callbacks
	list<OwnedCallback<void>> tick_events;
	list<OwnedCallback<void>> queue;
	list<OwnedCallback<void, int, int, int, int>> key_events;
	list<Object*> killQueue;

	Collision collisions;

	void tick(float dt) {
		for (auto& o : objects) {
			o.pos.x += o.speed.x * dt;
			o.pos.y += o.speed.y * dt;
		}
		for (auto t : tick_events) {
			t();
		}
		collisions.check([](Object& a, Object& b) {
			cout << "collision: " << a.guid << " x " << b.guid << endl;
		});
		for (auto o : killQueue) {
			real_kill(*o);
		}
		killQueue.erase(killQueue.begin(), killQueue.end());
	}

	Object* find_by_guid(guid g) {
		for (auto& o : objects) {
			if (o.guid == g) {
				return &o;
			}
		}
		return 0;

	}

	Object& add_object() {
		objects.push_back(Object());
		return objects.back();
	}

	void keyfun(int key, int scancode, int action, int mods) {
		/*
		 * [in]	window	The window that received the event.
		 * [in]	key	The keyboard key that was pressed or released.
		 * [in]	scancode	The system-specific scancode of the key.
		 * [in]	action	GLFW_PRESS, GLFW_RELEASE or GLFW_REPEAT.
		 * [in]	mods	Bit field describing which modifier keys were held down
		 */
		for (auto x : key_events) {
			x(key, scancode, action, mods);
		}
	}

	void bind_key(int key, Object& o, std::function<void()> callback) {
		key_events.push_back(OwnedCallback<void, int, int, int, int>{o, [=](int key2, int scancode, int action, int mods){
			if (key2 == key and action == GLFW_PRESS) {
				callback();
			}
		}});
	}

	void on_tick(Object& o, std::function<void()> callback) {
		tick_events.push_back(OwnedCallback<void>{o, callback});
	}

	void kill(Object& o) {
		killQueue.push_back(&o);
	}

	void real_kill(Object& o) {
		cout << "Killing: " << o.guid << endl;
		key_events.remove_if([&](OwnedCallback<void, int, int, int, int>& oc) { return oc.o == o; });
		tick_events.remove_if([&](OwnedCallback<void>& oc) { return oc.o == o; });
		queue.remove_if([&](OwnedCallback<void>& oc) { return oc.o == o; });
		collisions.chaff.remove_if([&](Collision::Entry& e) { return e.o == o; });
		collisions.bullets.remove_if([&](Collision::Entry& e) { return e.o == o; });
		objects.remove(o);

	}
};

GLFWwindow* window;
World* cb_world;
void cb_key(GLFWwindow*, int key, int scancode, int action, int mods) {
	cb_world->keyfun(key, scancode, action, mods);
}

void WrapScreen(World& w, Object& o) {
	w.tick_events.push_back(OwnedCallback<void>{o, [&o](){
		float m = 0.1;
		float xa = -16-m, xb = 16+m, ya=-9-m, yb=9+m;
		float xw=xb-xa, yw=yb-ya;
		if (o.pos.x < xa) {
			o.pos.x += xw;
		}
		if (o.pos.x > xb) {
			o.pos.x -= xw;
		}
		if (o.pos.y < ya) {
			o.pos.y += yw;
		}
		if (o.pos.y > yb) {
			o.pos.y -= yw;
		}
	}});
}

void KillWhenExitingScreen(World& w, Object& o) {
	w.tick_events.push_back(OwnedCallback<void>{o, [&w, &o]() { // This can run less often
		float xa=-16, xb=16, ya=-9, yb=9;
		if (o.pos.x < xa or o.pos.x > xb or o.pos.y < ya or o.pos.y > yb) {
			w.kill(o);
		}
	}});
}

void Asteroid(World& w, Object& o) {
	o.pos.x = std::uniform_real_distribution<float>(-1, 1)(rng);
	o.pos.y = std::uniform_real_distribution<float>(-1, 1)(rng);
	float speed = 0.3;
	float angle = std::uniform_real_distribution<float>(0, 44./7)(rng);
	o.speed.x = cos(angle)*speed;
	o.speed.y = sin(angle)*speed;
	WrapScreen(w, o);
	w.collisions.chaff.push_back(Collision::Entry{o});
}

void Bullet(World& w, Object& o) {
	KillWhenExitingScreen(w, o);
	w.collisions.bullets.push_back(Collision::Entry{o});
}

void Player(World& w, Object& o) {
	Asteroid(w, o);
	std::shared_ptr<float> angle(new float);

	w.on_tick(o, [&o, angle](){
		if (glfwGetKey(window, GLFW_KEY_RIGHT)) {
			*angle -= 0.1;
		}
		if (glfwGetKey(window, GLFW_KEY_LEFT)) {
			*angle += 0.1;
		}
		if (glfwGetKey(window, GLFW_KEY_UP)) {
			float acc = 0.1;
			o.speed.x += cos(*angle)*acc;
			o.speed.y += sin(*angle)*acc;
		}
		ding_r(o.pos.x, o.pos.y, *angle);
	});
	w.bind_key(GLFW_KEY_SPACE, o, [&w, &o, angle](){
		auto& as = w.add_object();
		Bullet(w, as);
		as.pos = o.pos;
		float v = 4;
		as.speed.x = cos(*angle)*v;
		as.speed.y = sin(*angle)*v;
	});
}

int main(void)
{
	if (!glfwInit())
		return -1;
	glfwWindowHint(GLFW_SAMPLES, 4);

	// window = glfwCreateWindow(1366, 768, "Hello World", glfwGetPrimaryMonitor(), 0);
	window = glfwCreateWindow(800, 480, "Hello World", 0, 0);

	if (!window)
	{
		cerr << "Could not create window" << endl;
		glfwTerminate();
		exit(-1);
	}

	World world;
	cb_world = &world;
	glfwSetKeyCallback(window, cb_key);

	for (int i=0; i<5; ++i) {
		Asteroid(world, world.add_object());
	}
	Player(world, world.add_object());

	/* Make the window's context current */
	glfwMakeContextCurrent(window);
	double t0 = glfwGetTime();
	cout << glGetString(GL_VENDOR) << endl;
	cout << glGetString(GL_VERSION) << endl;
	cout << glGetString(GL_RENDERER) << endl;

	PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)glfwGetProcAddress("wglSwapIntervalEXT");
	if (wglSwapIntervalEXT) {
		wglSwapIntervalEXT(1);
	} else {
		cerr << "VSync not available" << endl;
	}

	glMatrixMode(GL_PROJECTION);
	glOrtho(-16, 16, -9, 9, 1, -1);
	glMatrixMode(GL_MODELVIEW);

	/* Loop until the user closes the window */
	while (!glfwWindowShouldClose(window))
	{
		double t1 = glfwGetTime();
		float dt = (t1 - t0);
		t0 = t1;
		/* Render here */
		glClearColor(1,.98, 1 ,0);
		glClear(GL_COLOR_BUFFER_BIT);

		glColor3f(.5,.2,0);
		world.tick(dt);
		for (auto o : world.objects) {
			ding(o.pos.x, o.pos.y);
		}

		glfwSwapBuffers(window);
		glfwPollEvents();
	}

	glfwTerminate();
	return 0;
}
<commit_msg>Err, renderer.. with... objects..?<commit_after>#include <iostream>
#include <array>
#include <vector>
#include <list>
#include <functional>
#include <random>
#include <memory>
#include "GL/gl.h"
#include "GL/wglext.h"
#include "GL/glu.h"
#include "GLFW/glfw3.h"
#include "countof.h"

using std::cout;
using std::cerr;
using std::endl;
using std::vector;
using std::array;
using std::list;
using std::function;

struct vec2 {
	float x;
	float y;

	float dist2(vec2 b) {
		float dx = b.x-x, dy = b.y-y, len2=dx*dx+dy*dy;
		return len2;
	}
};

std::mt19937 rng;

typedef unsigned long long guid;
guid random_guid() {
	return std::uniform_int_distribution<guid>()(rng);
}

struct Object {
	Object() {}
	Object(vec2 pos, vec2 speed) : pos(pos), speed(speed) {}
	long guid = random_guid();
	vec2 pos;
	vec2 speed;

	bool operator==(const Object& other) {
		return guid == other.guid;
	}
};

template<typename T, typename... Args>
struct OwnedCallback {
	Object& o;
	function<T(Args...)> cb;

	T operator()(Args... args) {
		return cb(args...);
	}
};

struct Collision {
	// For now, simple quadratic collision
	struct Entry {
		Object& o;
	};
	list<Entry> chaff;
	list<Entry> bullets;

	void check(function<void(Object&, Object&)> fn) {
		float size = 0.1;
		for (auto x : chaff) {
			for (auto y : bullets) {
				if (x.o.pos.dist2(y.o.pos) < size*size) fn(x.o, y.o);
			}
		}
		for (auto x : chaff) {
			for (auto y : chaff) {
				if (x.o == y.o) continue;
				if (x.o.pos.dist2(y.o.pos) < size*size) fn(x.o, y.o);
			}
		}
	}
};

const float AST[] {
	0.4, 0,
	0, 0.4,
	-0.4, 0,
	0, -0.4,
};
const float SDX =.4, SYG=.8, SYD=.2, SYDD=.4;
const float SHIP[] {
	-SDX, -SYDD,
	0, SYG,
	SDX, -SYDD,
	0, -SYD,
};
const float BULLET[] {
	-1, 0,
	1, 0
};

const float* const MODELS[] { AST, SHIP, BULLET };
static constexpr int SIZES[] { 4, 4, 2 };

struct Renderer {

	struct Entry {
		Object& o;
		unsigned model;
	};
	list<Entry> entries;

	void add(Object& o, unsigned model) {
		entries.push_back(Entry { o, model });
	}

	void render() {
		glEnableClientState(GL_VERTEX_ARRAY);
		for (auto& e: entries) {
			render(e);
		}
	}

	void render(Entry& e) {
		float x = e.o.pos.x;
		float y = e.o.pos.y;
		float r = 0;
		const float* p = MODELS[e.model];
		int c = SIZES[e.model];
		glPushMatrix();
		glTranslatef(x, y, 0);
		glVertexPointer(2, GL_FLOAT, 0, p);
		glDrawArrays(GL_LINE_LOOP, 0, c);
		glPopMatrix();
	}
};

struct World {
	list<Object> objects; // could be a vector, but reallocs will kill references in callbacks
	list<OwnedCallback<void>> tick_events;
	list<OwnedCallback<void>> queue;
	list<OwnedCallback<void, int, int, int, int>> key_events;
	list<Object*> killQueue;

	Collision collisions;
	Renderer renderer;

	void tick(float dt) {
		for (auto& o : objects) {
			o.pos.x += o.speed.x * dt;
			o.pos.y += o.speed.y * dt;
		}
		for (auto t : tick_events) {
			t();
		}
		collisions.check([](Object& a, Object& b) {
			cout << "collision: " << a.guid << " x " << b.guid << endl;
		});
		for (auto o : killQueue) {
			real_kill(*o);
		}
		killQueue.erase(killQueue.begin(), killQueue.end());
	}

	Object* find_by_guid(guid g) {
		for (auto& o : objects) {
			if (o.guid == g) {
				return &o;
			}
		}
		return 0;

	}

	Object& add_object() {
		objects.push_back(Object());
		return objects.back();
	}

	void keyfun(int key, int scancode, int action, int mods) {
		/*
		 * [in]	window	The window that received the event.
		 * [in]	key	The keyboard key that was pressed or released.
		 * [in]	scancode	The system-specific scancode of the key.
		 * [in]	action	GLFW_PRESS, GLFW_RELEASE or GLFW_REPEAT.
		 * [in]	mods	Bit field describing which modifier keys were held down
		 */
		for (auto x : key_events) {
			x(key, scancode, action, mods);
		}
	}

	void bind_key(int key, Object& o, std::function<void()> callback) {
		key_events.push_back(OwnedCallback<void, int, int, int, int>{o, [=](int key2, int scancode, int action, int mods){
			if (key2 == key and action == GLFW_PRESS) {
				callback();
			}
		}});
	}

	void on_tick(Object& o, std::function<void()> callback) {
		tick_events.push_back(OwnedCallback<void>{o, callback});
	}

	void kill(Object& o) {
		killQueue.push_back(&o);
	}

	void real_kill(Object& o) {
		cout << "Killing: " << o.guid << endl;
		key_events.remove_if([&](OwnedCallback<void, int, int, int, int>& oc) { return oc.o == o; });
		tick_events.remove_if([&](OwnedCallback<void>& oc) { return oc.o == o; });
		queue.remove_if([&](OwnedCallback<void>& oc) { return oc.o == o; });
		collisions.chaff.remove_if([&](Collision::Entry& e) { return e.o == o; });
		collisions.bullets.remove_if([&](Collision::Entry& e) { return e.o == o; });
		renderer.entries.remove_if([&](Renderer::Entry& e) { return e.o == o; });
		objects.remove(o);

	}
};

GLFWwindow* window;
World* cb_world;
void cb_key(GLFWwindow*, int key, int scancode, int action, int mods) {
	cb_world->keyfun(key, scancode, action, mods);
}

void WrapScreen(World& w, Object& o) {
	w.tick_events.push_back(OwnedCallback<void>{o, [&o](){
		float m = 0.1;
		float xa = -16-m, xb = 16+m, ya=-9-m, yb=9+m;
		float xw=xb-xa, yw=yb-ya;
		if (o.pos.x < xa) {
			o.pos.x += xw;
		}
		if (o.pos.x > xb) {
			o.pos.x -= xw;
		}
		if (o.pos.y < ya) {
			o.pos.y += yw;
		}
		if (o.pos.y > yb) {
			o.pos.y -= yw;
		}
	}});
}

void KillWhenExitingScreen(World& w, Object& o) {
	w.tick_events.push_back(OwnedCallback<void>{o, [&w, &o]() { // This can run less often
		float xa=-16, xb=16, ya=-9, yb=9;
		if (o.pos.x < xa or o.pos.x > xb or o.pos.y < ya or o.pos.y > yb) {
			w.kill(o);
		}
	}});
}

void Asteroid(World& w, Object& o) {
	w.renderer.add(o, 0);
	o.pos.x = std::uniform_real_distribution<float>(-16, 16)(rng);
	o.pos.y = std::uniform_real_distribution<float>(-9, 9)(rng);
	float speed = 0.3;
	float angle = std::uniform_real_distribution<float>(0, 44./7)(rng);
	o.speed.x = cos(angle)*speed;
	o.speed.y = sin(angle)*speed;
	WrapScreen(w, o);
	w.collisions.chaff.push_back(Collision::Entry{o});
}

void Bullet(World& w, Object& o) {
	KillWhenExitingScreen(w, o);
	w.renderer.add(o, 2);
	w.collisions.bullets.push_back(Collision::Entry{o});
}

void Player(World& w, Object& o) {
	o.pos.x = o.pos.y = 0;
	o.speed.x = o.speed.y = 0;
	WrapScreen(w, o);
	w.collisions.chaff.push_back(Collision::Entry{o});
	w.renderer.add(o, 1);
	std::shared_ptr<float> angle(new float);

	w.on_tick(o, [&o, angle](){
		if (glfwGetKey(window, GLFW_KEY_RIGHT)) {
			*angle -= 0.1;
		}
		if (glfwGetKey(window, GLFW_KEY_LEFT)) {
			*angle += 0.1;
		}
		if (glfwGetKey(window, GLFW_KEY_UP)) {
			float acc = 0.1;
			o.speed.x += cos(*angle)*acc;
			o.speed.y += sin(*angle)*acc;
		}
		//ding_r(o.pos.x, o.pos.y, *angle);
	});
	w.bind_key(GLFW_KEY_SPACE, o, [&w, &o, angle](){
		auto& as = w.add_object();
		Bullet(w, as);
		as.pos = o.pos;
		float v = 16;
		as.speed.x = cos(*angle)*v;
		as.speed.y = sin(*angle)*v;
	});
}

int main(void)
{
	if (!glfwInit())
		return -1;
	glfwWindowHint(GLFW_SAMPLES, 4);

	// window = glfwCreateWindow(1366, 768, "Hello World", glfwGetPrimaryMonitor(), 0);
	window = glfwCreateWindow(800, 480, "Hello World", 0, 0);

	if (!window)
	{
		cerr << "Could not create window" << endl;
		glfwTerminate();
		exit(-1);
	}

	World world;
	cb_world = &world;
	glfwSetKeyCallback(window, cb_key);

	for (int i=0; i<5; ++i) {
		Asteroid(world, world.add_object());
	}
	Player(world, world.add_object());

	/* Make the window's context current */
	glfwMakeContextCurrent(window);
	double t0 = glfwGetTime();
	cout << glGetString(GL_VENDOR) << endl;
	cout << glGetString(GL_VERSION) << endl;
	cout << glGetString(GL_RENDERER) << endl;

	PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)glfwGetProcAddress("wglSwapIntervalEXT");
	if (wglSwapIntervalEXT) {
		wglSwapIntervalEXT(1);
	} else {
		cerr << "VSync not available" << endl;
	}

	glMatrixMode(GL_PROJECTION);
	glOrtho(-16, 16, -9, 9, 1, -1);
	glMatrixMode(GL_MODELVIEW);

	/* Loop until the user closes the window */
	while (!glfwWindowShouldClose(window))
	{
		double t1 = glfwGetTime();
		float dt = (t1 - t0);
		t0 = t1;
		/* Render here */
		glClearColor(1,.98, 1 ,0);
		glClear(GL_COLOR_BUFFER_BIT);

		glColor3f(.5,.2,0);
		world.tick(dt);
		world.renderer.render();

		glfwSwapBuffers(window);
		glfwPollEvents();
	}

	glfwTerminate();
	return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: tabarea.cxx,v $
 * $Revision: 1.12 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

// include ---------------------------------------------------------------

#include <tools/ref.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#include <svtools/pathoptions.hxx>
#include <svx/svdmark.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdview.hxx>

#define _SVX_TABAREA_CXX

#include <svx/dialogs.hrc>

#include <svx/xtable.hxx>
#include "globl3d.hxx"
#include <svx/svdmodel.hxx>
#include "drawitem.hxx"
#include "cuitabarea.hxx"
#include "tabarea.hrc"
#include "dlgname.hxx"
#include "dlgname.hrc"
#include <svx/dialmgr.hxx>

#define DLGWIN this->GetParent()->GetParent()

/*************************************************************************
|*
|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu
|*
|************************************************************************/

SvxAreaTabDialog::SvxAreaTabDialog
(
    Window* pParent,
    const SfxItemSet* pAttr,
    SdrModel* pModel,
    const SdrView* /* pSdrView */
) :

    SfxTabDialog( pParent, SVX_RES( RID_SVXDLG_AREA ), pAttr ),

    mpDrawModel          ( pModel ),
//    mpView               ( pSdrView ),
    mpColorTab           ( pModel->GetColorTable() ),
    mpNewColorTab        ( pModel->GetColorTable() ),
    mpGradientList       ( pModel->GetGradientList() ),
    mpNewGradientList    ( pModel->GetGradientList() ),
    mpHatchingList       ( pModel->GetHatchList() ),
    mpNewHatchingList    ( pModel->GetHatchList() ),
    mpBitmapList         ( pModel->GetBitmapList() ),
    mpNewBitmapList      ( pModel->GetBitmapList() ),
    mrOutAttrs           ( *pAttr ),
    mnColorTableState ( CT_NONE ),
    mnBitmapListState ( CT_NONE ),
    mnGradientListState ( CT_NONE ),
    mnHatchingListState ( CT_NONE ),
    mnPageType( PT_AREA ),
    mnDlgType( 0 ),
    mnPos( 0 ),
    mbAreaTP( sal_False ),
    mbDeleteColorTable( TRUE )
{
    FreeResource();

    AddTabPage( RID_SVXPAGE_AREA, SvxAreaTabPage::Create, 0 );
    AddTabPage( RID_SVXPAGE_SHADOW, SvxShadowTabPage::Create, 0 );
    AddTabPage( RID_SVXPAGE_TRANSPARENCE, SvxTransparenceTabPage::Create,  0);
    AddTabPage( RID_SVXPAGE_COLOR, SvxColorTabPage::Create, 0 );
    AddTabPage( RID_SVXPAGE_GRADIENT, SvxGradientTabPage::Create, 0 );
    AddTabPage( RID_SVXPAGE_HATCH, SvxHatchTabPage::Create, 0 );
    AddTabPage( RID_SVXPAGE_BITMAP, SvxBitmapTabPage::Create,  0);

    SetCurPageId( RID_SVXPAGE_AREA );

    CancelButton& rBtnCancel = GetCancelButton();
    rBtnCancel.SetClickHdl( LINK( this, SvxAreaTabDialog, CancelHdlImpl ) );
//! rBtnCancel.SetText( SVX_RESSTR( RID_SVXSTR_CLOSE ) );
}

// -----------------------------------------------------------------------

SvxAreaTabDialog::~SvxAreaTabDialog()
{
}

// -----------------------------------------------------------------------

void SvxAreaTabDialog::SavePalettes()
{
    if( mpNewColorTab != mpDrawModel->GetColorTable() )
    {
        if(mbDeleteColorTable)
            delete mpDrawModel->GetColorTable();
        mpDrawModel->SetColorTable( mpNewColorTab );
        SfxObjectShell::Current()->PutItem( SvxColorTableItem( mpNewColorTab, SID_COLOR_TABLE ) );
        mpColorTab = mpDrawModel->GetColorTable();
    }
    if( mpNewGradientList != mpDrawModel->GetGradientList() )
    {
        delete mpDrawModel->GetGradientList();
        mpDrawModel->SetGradientList( mpNewGradientList );
        SfxObjectShell::Current()->PutItem( SvxGradientListItem( mpNewGradientList, SID_GRADIENT_LIST ) );
        mpGradientList = mpDrawModel->GetGradientList();
    }
    if( mpNewHatchingList != mpDrawModel->GetHatchList() )
    {
        delete mpDrawModel->GetHatchList();
        mpDrawModel->SetHatchList( mpNewHatchingList );
        SfxObjectShell::Current()->PutItem( SvxHatchListItem( mpNewHatchingList, SID_HATCH_LIST ) );
        mpHatchingList = mpDrawModel->GetHatchList();
    }
    if( mpNewBitmapList != mpDrawModel->GetBitmapList() )
    {
        delete mpDrawModel->GetBitmapList();
        mpDrawModel->SetBitmapList( mpNewBitmapList );
        SfxObjectShell::Current()->PutItem( SvxBitmapListItem( mpNewBitmapList, SID_BITMAP_LIST ) );
        mpBitmapList = mpDrawModel->GetBitmapList();
    }

    // Speichern der Tabellen, wenn sie geaendert wurden.

    const String aPath( SvtPathOptions().GetPalettePath() );

    if( mnHatchingListState & CT_MODIFIED )
    {
        mpHatchingList->SetPath( aPath );
        mpHatchingList->Save();

        // ToolBoxControls werden benachrichtigt:
        SfxObjectShell::Current()->PutItem( SvxHatchListItem( mpHatchingList, SID_HATCH_LIST ) );
    }

    if( mnBitmapListState & CT_MODIFIED )
    {
        mpBitmapList->SetPath( aPath );
        mpBitmapList->Save();

        // ToolBoxControls werden benachrichtigt:
        SfxObjectShell::Current()->PutItem( SvxBitmapListItem( mpBitmapList, SID_BITMAP_LIST ) );
    }

    if( mnGradientListState & CT_MODIFIED )
    {
        mpGradientList->SetPath( aPath );
        mpGradientList->Save();
        // ToolBoxControls werden benachrichtigt:
        SfxObjectShell::Current()->PutItem( SvxGradientListItem( mpGradientList, SID_GRADIENT_LIST ) );
    }

    if( mnColorTableState & CT_MODIFIED )
    {
        mpColorTab->SetPath( aPath );
        mpColorTab->Save();

        // ToolBoxControls werden benachrichtigt:
        SfxObjectShell::Current()->PutItem( SvxColorTableItem( mpColorTab, SID_COLOR_TABLE ) );
    }
}
// -----------------------------------------------------------------------

short SvxAreaTabDialog::Ok()
{
    SavePalettes();

    // Es wird RET_OK zurueckgeliefert, wenn wenigstens eine
    // TabPage in FillItemSet() TRUE zurueckliefert. Dieses
    // geschieht z.Z. standardmaessig.
    return( SfxTabDialog::Ok() );
}

// -----------------------------------------------------------------------

IMPL_LINK_INLINE_START( SvxAreaTabDialog, CancelHdlImpl, void *, EMPTYARG)
{
    SavePalettes();

    EndDialog( RET_CANCEL );
    return 0;
}
IMPL_LINK_INLINE_END( SvxAreaTabDialog, CancelHdlImpl, void *, p )

// -----------------------------------------------------------------------

void SvxAreaTabDialog::PageCreated( USHORT nId, SfxTabPage &rPage )
{
    switch( nId )
    {
        case RID_SVXPAGE_AREA:
            ( (SvxAreaTabPage&) rPage ).SetColorTable( mpColorTab );
            ( (SvxAreaTabPage&) rPage ).SetGradientList( mpGradientList );
            ( (SvxAreaTabPage&) rPage ).SetHatchingList( mpHatchingList );
            ( (SvxAreaTabPage&) rPage ).SetBitmapList( mpBitmapList );
            //CHINA001 ( (SvxAreaTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxAreaTabPage&) rPage ).SetPageType( mnPageType ); //add CHINA001
            //CHINA001 ( (SvxAreaTabPage&) rPage ).SetDlgType( &mnDlgType );
            ( (SvxAreaTabPage&) rPage ).SetDlgType( mnDlgType );//add CHINA001
            //CHINA001 ( (SvxAreaTabPage&) rPage ).SetPos( &nPos );
            ( (SvxAreaTabPage&) rPage ).SetPos( mnPos );//add CHINA001
            ( (SvxAreaTabPage&) rPage ).SetAreaTP( &mbAreaTP );
            ( (SvxAreaTabPage&) rPage ).SetGrdChgd( &mnGradientListState );
            ( (SvxAreaTabPage&) rPage ).SetHtchChgd( &mnHatchingListState );
            ( (SvxAreaTabPage&) rPage ).SetBmpChgd( &mnBitmapListState );
            ( (SvxAreaTabPage&) rPage ).SetColorChgd( &mnColorTableState );
            ( (SvxAreaTabPage&) rPage ).Construct();
            // ActivatePage() wird das erste mal nicht gerufen
            ( (SvxAreaTabPage&) rPage ).ActivatePage( mrOutAttrs );

        break;

        case RID_SVXPAGE_SHADOW:
        {
            ( (SvxShadowTabPage&) rPage ).SetColorTable( mpColorTab );
            ( (SvxShadowTabPage&) rPage ).SetPageType( mnPageType );//CHINA001 ( (SvxShadowTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxShadowTabPage&) rPage ).SetDlgType( mnDlgType );//CHINA001 ( (SvxShadowTabPage&) rPage ).SetDlgType( &mnDlgType );
            //( (SvxShadowTabPage&) rPage ).SetPos( &nPos );
            ( (SvxShadowTabPage&) rPage ).SetAreaTP( &mbAreaTP );
            ( (SvxShadowTabPage&) rPage ).SetColorChgd( &mnColorTableState );
            ( (SvxShadowTabPage&) rPage ).Construct();
        }
        break;

        case RID_SVXPAGE_GRADIENT:
            ( (SvxGradientTabPage&) rPage ).SetColorTable( mpColorTab );
            ( (SvxGradientTabPage&) rPage ).SetGradientList( mpGradientList );
            ( (SvxGradientTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxGradientTabPage&) rPage ).SetDlgType( &mnDlgType );
            ( (SvxGradientTabPage&) rPage ).SetPos( &mnPos );
            ( (SvxGradientTabPage&) rPage ).SetAreaTP( &mbAreaTP );
            ( (SvxGradientTabPage&) rPage ).SetGrdChgd( &mnGradientListState );
            ( (SvxGradientTabPage&) rPage ).SetColorChgd( &mnColorTableState );
            ( (SvxGradientTabPage&) rPage ).Construct();
        break;

        case RID_SVXPAGE_HATCH:
            ( (SvxHatchTabPage&) rPage ).SetColorTable( mpColorTab );
            ( (SvxHatchTabPage&) rPage ).SetHatchingList( mpHatchingList );
            ( (SvxHatchTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxHatchTabPage&) rPage ).SetDlgType( &mnDlgType );
            ( (SvxHatchTabPage&) rPage ).SetPos( &mnPos );
            ( (SvxHatchTabPage&) rPage ).SetAreaTP( &mbAreaTP );
            ( (SvxHatchTabPage&) rPage ).SetHtchChgd( &mnHatchingListState );
            ( (SvxHatchTabPage&) rPage ).SetColorChgd( &mnColorTableState );
            ( (SvxHatchTabPage&) rPage ).Construct();
        break;

        case RID_SVXPAGE_BITMAP:
            ( (SvxBitmapTabPage&) rPage ).SetColorTable( mpColorTab );
            ( (SvxBitmapTabPage&) rPage ).SetBitmapList( mpBitmapList );
            ( (SvxBitmapTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxBitmapTabPage&) rPage ).SetDlgType( &mnDlgType );
            ( (SvxBitmapTabPage&) rPage ).SetPos( &mnPos );
            ( (SvxBitmapTabPage&) rPage ).SetAreaTP( &mbAreaTP );
            ( (SvxBitmapTabPage&) rPage ).SetBmpChgd( &mnBitmapListState );
            ( (SvxBitmapTabPage&) rPage ).SetColorChgd( &mnColorTableState );
            ( (SvxBitmapTabPage&) rPage ).Construct();
        break;

        case RID_SVXPAGE_COLOR:
            ( (SvxColorTabPage&) rPage ).SetColorTable( mpColorTab );
            ( (SvxColorTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxColorTabPage&) rPage ).SetDlgType( &mnDlgType );
            ( (SvxColorTabPage&) rPage ).SetPos( &mnPos );
            ( (SvxColorTabPage&) rPage ).SetAreaTP( &mbAreaTP );
            ( (SvxColorTabPage&) rPage ).SetColorChgd( &mnColorTableState );
            ( (SvxColorTabPage&) rPage ).SetDeleteColorTable( mbDeleteColorTable );
            ( (SvxColorTabPage&) rPage ).Construct();
        break;

        case RID_SVXPAGE_TRANSPARENCE:
            ( (SvxTransparenceTabPage&) rPage ).SetPageType( mnPageType );//CHINA001 ( (SvxTransparenceTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxTransparenceTabPage&) rPage ).SetDlgType( mnDlgType );//CHINA001 ( (SvxTransparenceTabPage&) rPage ).SetDlgType( &mnDlgType );
            ( (SvxTransparenceTabPage&) rPage ).Construct();
        break;

    }
}

<commit_msg>INTEGRATION: CWS dba31a (1.12.100); FILE MERGED 2008/07/10 07:06:33 oj 1.12.100.1: #i88727# changes need to support none sfx apps<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: tabarea.cxx,v $
 * $Revision: 1.13 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_svx.hxx"

#ifdef SVX_DLLIMPLEMENTATION
#undef SVX_DLLIMPLEMENTATION
#endif

// include ---------------------------------------------------------------

#include <tools/ref.hxx>
#include <sfx2/app.hxx>
#include <sfx2/objsh.hxx>
#ifndef _MSGBOX_HXX //autogen
#include <vcl/msgbox.hxx>
#endif
#include <svtools/pathoptions.hxx>
#include <svx/svdmark.hxx>
#include <svx/svdobj.hxx>
#include <svx/svdview.hxx>

#define _SVX_TABAREA_CXX

#include <svx/dialogs.hrc>

#include <svx/xtable.hxx>
#include "globl3d.hxx"
#include <svx/svdmodel.hxx>
#include "drawitem.hxx"
#include "cuitabarea.hxx"
#include "tabarea.hrc"
#include "dlgname.hxx"
#include "dlgname.hrc"
#include <svx/dialmgr.hxx>

#define DLGWIN this->GetParent()->GetParent()

/*************************************************************************
|*
|* Konstruktor des Tab-Dialogs: Fuegt die Seiten zum Dialog hinzu
|*
|************************************************************************/

SvxAreaTabDialog::SvxAreaTabDialog
(
    Window* pParent,
    const SfxItemSet* pAttr,
    SdrModel* pModel,
    const SdrView* /* pSdrView */
) :

    SfxTabDialog( pParent, SVX_RES( RID_SVXDLG_AREA ), pAttr ),

    mpDrawModel          ( pModel ),
//    mpView               ( pSdrView ),
    mpColorTab           ( pModel->GetColorTable() ),
    mpNewColorTab        ( pModel->GetColorTable() ),
    mpGradientList       ( pModel->GetGradientList() ),
    mpNewGradientList    ( pModel->GetGradientList() ),
    mpHatchingList       ( pModel->GetHatchList() ),
    mpNewHatchingList    ( pModel->GetHatchList() ),
    mpBitmapList         ( pModel->GetBitmapList() ),
    mpNewBitmapList      ( pModel->GetBitmapList() ),
    mrOutAttrs           ( *pAttr ),
    mnColorTableState ( CT_NONE ),
    mnBitmapListState ( CT_NONE ),
    mnGradientListState ( CT_NONE ),
    mnHatchingListState ( CT_NONE ),
    mnPageType( PT_AREA ),
    mnDlgType( 0 ),
    mnPos( 0 ),
    mbAreaTP( sal_False ),
    mbDeleteColorTable( TRUE )
{
    FreeResource();

    AddTabPage( RID_SVXPAGE_AREA, SvxAreaTabPage::Create, 0 );
    AddTabPage( RID_SVXPAGE_SHADOW, SvxShadowTabPage::Create, 0 );
    AddTabPage( RID_SVXPAGE_TRANSPARENCE, SvxTransparenceTabPage::Create,  0);
    AddTabPage( RID_SVXPAGE_COLOR, SvxColorTabPage::Create, 0 );
    AddTabPage( RID_SVXPAGE_GRADIENT, SvxGradientTabPage::Create, 0 );
    AddTabPage( RID_SVXPAGE_HATCH, SvxHatchTabPage::Create, 0 );
    AddTabPage( RID_SVXPAGE_BITMAP, SvxBitmapTabPage::Create,  0);

    SetCurPageId( RID_SVXPAGE_AREA );

    CancelButton& rBtnCancel = GetCancelButton();
    rBtnCancel.SetClickHdl( LINK( this, SvxAreaTabDialog, CancelHdlImpl ) );
//! rBtnCancel.SetText( SVX_RESSTR( RID_SVXSTR_CLOSE ) );
}

// -----------------------------------------------------------------------

SvxAreaTabDialog::~SvxAreaTabDialog()
{
}

// -----------------------------------------------------------------------

void SvxAreaTabDialog::SavePalettes()
{
    SfxObjectShell* pShell = SfxObjectShell::Current();
    /*uno::Reference< frame::XDispatchProvider > xDispatchProvider;
    if ( !pShell )
    {
        uno::Reference< frame::XModel> xModel = mpDrawModel->getUnoModel();
        if ( xModel.is() )
            xDispatchProvider.set(xModel->getCurrentController(),uno::UNO_QUERY);
    }*/
    if( mpNewColorTab != mpDrawModel->GetColorTable() )
    {
        if(mbDeleteColorTable)
            delete mpDrawModel->GetColorTable();
        mpDrawModel->SetColorTable( mpNewColorTab );
        SvxColorTableItem aColorTableItem( mpNewColorTab, SID_COLOR_TABLE );
        if ( pShell )
            pShell->PutItem( aColorTableItem );
        else
        {
            mpDrawModel->GetItemPool().Put(aColorTableItem,SID_COLOR_TABLE);
        }
        mpColorTab = mpDrawModel->GetColorTable();
    }
    if( mpNewGradientList != mpDrawModel->GetGradientList() )
    {
        delete mpDrawModel->GetGradientList();
        mpDrawModel->SetGradientList( mpNewGradientList );
        SvxGradientListItem aItem( mpNewGradientList, SID_GRADIENT_LIST );
        if ( pShell )
            pShell->PutItem( aItem );
        else
        {
            mpDrawModel->GetItemPool().Put(aItem,SID_GRADIENT_LIST);
        }
        mpGradientList = mpDrawModel->GetGradientList();
    }
    if( mpNewHatchingList != mpDrawModel->GetHatchList() )
    {
        delete mpDrawModel->GetHatchList();
        mpDrawModel->SetHatchList( mpNewHatchingList );
        SvxHatchListItem aItem( mpNewHatchingList, SID_HATCH_LIST );
        if ( pShell )
            pShell->PutItem( aItem );
        else
        {
            mpDrawModel->GetItemPool().Put(aItem,SID_HATCH_LIST);
        }
        mpHatchingList = mpDrawModel->GetHatchList();
    }
    if( mpNewBitmapList != mpDrawModel->GetBitmapList() )
    {
        delete mpDrawModel->GetBitmapList();
        mpDrawModel->SetBitmapList( mpNewBitmapList );
        SvxBitmapListItem aItem( mpNewBitmapList, SID_BITMAP_LIST );
        if ( pShell )
            pShell->PutItem( aItem );
        else
        {
            mpDrawModel->GetItemPool().Put(aItem,SID_BITMAP_LIST);
        }
        mpBitmapList = mpDrawModel->GetBitmapList();
    }

    // Speichern der Tabellen, wenn sie geaendert wurden.

    const String aPath( SvtPathOptions().GetPalettePath() );

    if( mnHatchingListState & CT_MODIFIED )
    {
        mpHatchingList->SetPath( aPath );
        mpHatchingList->Save();

        SvxHatchListItem aItem( mpHatchingList, SID_HATCH_LIST );
        // ToolBoxControls werden benachrichtigt:
        if ( pShell )
            pShell->PutItem( aItem );
        else
        {
            mpDrawModel->GetItemPool().Put(aItem);
        }
    }

    if( mnBitmapListState & CT_MODIFIED )
    {
        mpBitmapList->SetPath( aPath );
        mpBitmapList->Save();

        SvxBitmapListItem aItem( mpBitmapList, SID_BITMAP_LIST );
        // ToolBoxControls werden benachrichtigt:
        if ( pShell )
            pShell->PutItem( aItem );
        else
        {
            mpDrawModel->GetItemPool().Put(aItem);
        }
    }

    if( mnGradientListState & CT_MODIFIED )
    {
        mpGradientList->SetPath( aPath );
        mpGradientList->Save();

        SvxGradientListItem aItem( mpGradientList, SID_GRADIENT_LIST );
        // ToolBoxControls werden benachrichtigt:
        if ( pShell )
            pShell->PutItem( aItem );
        else
        {
            mpDrawModel->GetItemPool().Put(aItem);
        }
    }

    if( mnColorTableState & CT_MODIFIED )
    {
        mpColorTab->SetPath( aPath );
        mpColorTab->Save();

        SvxColorTableItem aItem( mpColorTab, SID_COLOR_TABLE );
        // ToolBoxControls werden benachrichtigt:
        if ( pShell )
            pShell->PutItem( aItem );
        else
        {
            mpDrawModel->GetItemPool().Put(aItem);
        }
    }
}
// -----------------------------------------------------------------------

short SvxAreaTabDialog::Ok()
{
    SavePalettes();

    // Es wird RET_OK zurueckgeliefert, wenn wenigstens eine
    // TabPage in FillItemSet() TRUE zurueckliefert. Dieses
    // geschieht z.Z. standardmaessig.
    return( SfxTabDialog::Ok() );
}

// -----------------------------------------------------------------------

IMPL_LINK_INLINE_START( SvxAreaTabDialog, CancelHdlImpl, void *, EMPTYARG)
{
    SavePalettes();

    EndDialog( RET_CANCEL );
    return 0;
}
IMPL_LINK_INLINE_END( SvxAreaTabDialog, CancelHdlImpl, void *, p )

// -----------------------------------------------------------------------

void SvxAreaTabDialog::PageCreated( USHORT nId, SfxTabPage &rPage )
{
    switch( nId )
    {
        case RID_SVXPAGE_AREA:
            ( (SvxAreaTabPage&) rPage ).SetColorTable( mpColorTab );
            ( (SvxAreaTabPage&) rPage ).SetGradientList( mpGradientList );
            ( (SvxAreaTabPage&) rPage ).SetHatchingList( mpHatchingList );
            ( (SvxAreaTabPage&) rPage ).SetBitmapList( mpBitmapList );
            //CHINA001 ( (SvxAreaTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxAreaTabPage&) rPage ).SetPageType( mnPageType ); //add CHINA001
            //CHINA001 ( (SvxAreaTabPage&) rPage ).SetDlgType( &mnDlgType );
            ( (SvxAreaTabPage&) rPage ).SetDlgType( mnDlgType );//add CHINA001
            //CHINA001 ( (SvxAreaTabPage&) rPage ).SetPos( &nPos );
            ( (SvxAreaTabPage&) rPage ).SetPos( mnPos );//add CHINA001
            ( (SvxAreaTabPage&) rPage ).SetAreaTP( &mbAreaTP );
            ( (SvxAreaTabPage&) rPage ).SetGrdChgd( &mnGradientListState );
            ( (SvxAreaTabPage&) rPage ).SetHtchChgd( &mnHatchingListState );
            ( (SvxAreaTabPage&) rPage ).SetBmpChgd( &mnBitmapListState );
            ( (SvxAreaTabPage&) rPage ).SetColorChgd( &mnColorTableState );
            ( (SvxAreaTabPage&) rPage ).Construct();
            // ActivatePage() wird das erste mal nicht gerufen
            ( (SvxAreaTabPage&) rPage ).ActivatePage( mrOutAttrs );

        break;

        case RID_SVXPAGE_SHADOW:
        {
            ( (SvxShadowTabPage&) rPage ).SetColorTable( mpColorTab );
            ( (SvxShadowTabPage&) rPage ).SetPageType( mnPageType );//CHINA001 ( (SvxShadowTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxShadowTabPage&) rPage ).SetDlgType( mnDlgType );//CHINA001 ( (SvxShadowTabPage&) rPage ).SetDlgType( &mnDlgType );
            //( (SvxShadowTabPage&) rPage ).SetPos( &nPos );
            ( (SvxShadowTabPage&) rPage ).SetAreaTP( &mbAreaTP );
            ( (SvxShadowTabPage&) rPage ).SetColorChgd( &mnColorTableState );
            ( (SvxShadowTabPage&) rPage ).Construct();
        }
        break;

        case RID_SVXPAGE_GRADIENT:
            ( (SvxGradientTabPage&) rPage ).SetColorTable( mpColorTab );
            ( (SvxGradientTabPage&) rPage ).SetGradientList( mpGradientList );
            ( (SvxGradientTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxGradientTabPage&) rPage ).SetDlgType( &mnDlgType );
            ( (SvxGradientTabPage&) rPage ).SetPos( &mnPos );
            ( (SvxGradientTabPage&) rPage ).SetAreaTP( &mbAreaTP );
            ( (SvxGradientTabPage&) rPage ).SetGrdChgd( &mnGradientListState );
            ( (SvxGradientTabPage&) rPage ).SetColorChgd( &mnColorTableState );
            ( (SvxGradientTabPage&) rPage ).Construct();
        break;

        case RID_SVXPAGE_HATCH:
            ( (SvxHatchTabPage&) rPage ).SetColorTable( mpColorTab );
            ( (SvxHatchTabPage&) rPage ).SetHatchingList( mpHatchingList );
            ( (SvxHatchTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxHatchTabPage&) rPage ).SetDlgType( &mnDlgType );
            ( (SvxHatchTabPage&) rPage ).SetPos( &mnPos );
            ( (SvxHatchTabPage&) rPage ).SetAreaTP( &mbAreaTP );
            ( (SvxHatchTabPage&) rPage ).SetHtchChgd( &mnHatchingListState );
            ( (SvxHatchTabPage&) rPage ).SetColorChgd( &mnColorTableState );
            ( (SvxHatchTabPage&) rPage ).Construct();
        break;

        case RID_SVXPAGE_BITMAP:
            ( (SvxBitmapTabPage&) rPage ).SetColorTable( mpColorTab );
            ( (SvxBitmapTabPage&) rPage ).SetBitmapList( mpBitmapList );
            ( (SvxBitmapTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxBitmapTabPage&) rPage ).SetDlgType( &mnDlgType );
            ( (SvxBitmapTabPage&) rPage ).SetPos( &mnPos );
            ( (SvxBitmapTabPage&) rPage ).SetAreaTP( &mbAreaTP );
            ( (SvxBitmapTabPage&) rPage ).SetBmpChgd( &mnBitmapListState );
            ( (SvxBitmapTabPage&) rPage ).SetColorChgd( &mnColorTableState );
            ( (SvxBitmapTabPage&) rPage ).Construct();
        break;

        case RID_SVXPAGE_COLOR:
            ( (SvxColorTabPage&) rPage ).SetColorTable( mpColorTab );
            ( (SvxColorTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxColorTabPage&) rPage ).SetDlgType( &mnDlgType );
            ( (SvxColorTabPage&) rPage ).SetPos( &mnPos );
            ( (SvxColorTabPage&) rPage ).SetAreaTP( &mbAreaTP );
            ( (SvxColorTabPage&) rPage ).SetColorChgd( &mnColorTableState );
            ( (SvxColorTabPage&) rPage ).SetDeleteColorTable( mbDeleteColorTable );
            ( (SvxColorTabPage&) rPage ).Construct();
        break;

        case RID_SVXPAGE_TRANSPARENCE:
            ( (SvxTransparenceTabPage&) rPage ).SetPageType( mnPageType );//CHINA001 ( (SvxTransparenceTabPage&) rPage ).SetPageType( &mnPageType );
            ( (SvxTransparenceTabPage&) rPage ).SetDlgType( mnDlgType );//CHINA001 ( (SvxTransparenceTabPage&) rPage ).SetDlgType( &mnDlgType );
            ( (SvxTransparenceTabPage&) rPage ).Construct();
        break;

    }
}

<|endoftext|>


<commit_before>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include "filedb.h"

#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

namespace {

void copyDirectory(fs::path original, fs::path destination)
{
    fs::create_directory(destination);
    for (fs::directory_iterator curr(original), end;
         curr != end;
         ++curr) {

        fs::path destPath = destination / curr->path().filename();
        if ( fs::is_directory(curr->status()) ) {
            copyDirectory(*curr, destPath);
        } else {
            fs::copy_file(*curr, destPath);
        }
    }
}

} //anonymous namespace

namespace filedistribution {

FileDB::FileDB(fs::path dbPath)
    : _dbPath(dbPath) {}

void
FileDB::add(fs::path original, const std::string &name) {
    fs::path targetPathTemp = _dbPath / (name + ".tmp");
    fs::path targetPath = _dbPath / (name + ".new");
    if (fs::exists(targetPath)) {
        return;
    }

    if (fs::exists(targetPathTemp)) {
        fs::remove_all(targetPathTemp);
    }

    fs::create_directory(targetPathTemp);
    if (!fs::is_directory(original)) {
        fs::copy_file(original, targetPathTemp / original.filename());
    } else {
        copyDirectory(original, targetPathTemp / original.filename());
    }

    assert(!fs::exists(targetPath));
    fs::rename(targetPathTemp, targetPath);
}

}
<commit_msg>And then it should be safe to only do conditional copy.<commit_after>// Copyright 2016 Yahoo Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
#include <vespa/fastos/fastos.h>
#include "filedb.h"

#include <boost/filesystem.hpp>

namespace fs = boost::filesystem;

namespace {

void copyDirectory(fs::path original, fs::path destination)
{
    fs::create_directory(destination);
    for (fs::directory_iterator curr(original), end;
         curr != end;
         ++curr) {

        fs::path destPath = destination / curr->path().filename();
        if ( fs::is_directory(curr->status()) ) {
            copyDirectory(*curr, destPath);
        } else {
            fs::copy_file(*curr, destPath);
        }
    }
}

} //anonymous namespace

namespace filedistribution {

FileDB::FileDB(fs::path dbPath)
    : _dbPath(dbPath) {}

void
FileDB::add(fs::path original, const std::string &name) {
    fs::path finalPath = _dbPath / name;
    if (fs::exists(finalPath)) {
        return;
    }
    fs::path targetPathTemp = _dbPath / (name + ".tmp");
    fs::path targetPath = _dbPath / (name + ".new");
    if (fs::exists(targetPath)) {
        return;
    }

    if (fs::exists(targetPathTemp)) {
        fs::remove_all(targetPathTemp);
    }

    fs::create_directory(targetPathTemp);
    if (!fs::is_directory(original)) {
        fs::copy_file(original, targetPathTemp / original.filename());
    } else {
        copyDirectory(original, targetPathTemp / original.filename());
    }

    assert(!fs::exists(targetPath));
    fs::rename(targetPathTemp, targetPath);
}

}
<|endoftext|>


<commit_before>// Elementary DMRG for Heisenberg S=1/2 chain,
// infinite system algorithm to build chain
// ED with Lanczos
// finite system sweep
//
//Roger Melko May 9 2006

#include <blitz/array.h>
#include <fstream>

BZ_USING_NAMESPACE(blitz)

//template function prototypes
template<typename T> Array<T,2> reduceM2M2(const Array<T,4>&, const int);
void EigenValuesLAN(Array<double,4>&, Array<double,2>&, const int, double *);
void DMlargeEigen(Array<double,2>&, Array<double,2>&, const int, const int);

//block object
struct BLOCK {
  int size;    //# of sites
  Array<double,2> HAp;  //A' block hamiltonian
  Array<double,2> SzL;   //Sz(left) operator
  Array<double,2> SmL;   //Sm(left) operator
  Array<double,2> SpL;   //Sp(left) operator
};

int main()
{
  int iter, NumI;
  int i1, i1p, i2, i2p, i3, i4;
  int b1;
  int m, st;     //# states
  int sites;     //# sites
  double Eval;   //Eigenvalue
  BLOCK blk;
  ofstream fout;
  char fname[7];

  fname[0] = '0'; fname[1] = '0'; fname[2] = '0';
  fname[3] = '.';
  fname[4] = 'E'; fname[5] = 'n'; fname[6] = 'v';

  cout<<"# states to keep: ";
  cin>>m;

  //Matrices
  Array<double,4> TSR(2,2,2,2);  //tensor product for Hab hamiltonian

  Array<double,4> Habcd(4,4,4,4); //superblock hamiltonian
  Array<double,2> HAB(4,4);        //new SYSTEM Hamiltonian
  Array<double,2> Psi(4,4); // ground state wavefunction
  Array<double,2> rhoTSR(4,4); // reduced density matrix
  Array<double,2> OO(m,4);   //the TRUNCATION matrix
  Array<double,2> OT(4,m);   // trasposed truncation matrix
  Array<double,2> Hl(4,m);   // the left half of new system H

  //create identity matrices
  Array<double,2> I2(2,2), I4(4,4), I2m(2*m,2*m);
  I2=0.0; I4=0.0; I2m=0.0;
  for (b1=0; b1<2; b1++) I2(b1,b1)=1.0;
  for (b1=0; b1<4; b1++) I4(b1,b1)=1.0;
  for (b1=0; b1<(2*m); b1++) I2m(b1,b1)=1.0;
  Array<double,2> I2st(4,4);
  I2st = I4;

  // Create pauli matrices
  Array<double,2> Sz(2,2), Sp(2,2), Sm(2,2);
  Sz = 0.5, 0,
       0, -0.5;
  Sp = 0, 1.0,
       0, 0;
  Sm = 0, 0,
       1.0, 0;

  //tensor indices
  firstIndex i;    secondIndex j;
  thirdIndex k;    fourthIndex l;

  cout<<"Iterations : ";
  cin>>NumI;

  //create a tensor product: two-site Hamiltonian
  TSR = Sz(i,k)*Sz(j,l)+ 0.5*Sp(i,k)*Sm(j,l) + 0.5*Sm(i,k)*Sp(j,l) ;
  //write as 2D matrix in combined basis
  Array<double,2> H12 = reduceM2M2(TSR,2);
  //cout<<"H12 "<<H12<<endl;

  TSR = Sz(i,k)*I2(j,l);
  Array<double,2> SzAB = reduceM2M2(TSR,2);

  TSR = Sm(i,k)*I2(j,l);
  Array<double,2> SmAB = reduceM2M2(TSR,2);

  TSR = Sp(i,k)*I2(j,l);
  Array<double,2> SpAB = reduceM2M2(TSR,2);

  HAB = H12;
  st = 2;     //start with a 2^2=4 state system
  sites = 2;

  /******infinite system algorithm loop first iteration**********/
  /******build system until number of desired states m **********/

  while(st <= m) {

   Habcd = HAB(i,k)*I2st(j,l) + I2st(i,k)*HAB(j,l) +
      SzAB(i,k)*SzAB(j,l)+ 0.5*SpAB(i,k)*SmAB(j,l) + 0.5*SmAB(i,k)*SpAB(j,l);

    EigenValuesLAN(Habcd,Psi,(4*st*st),&Eval);

    cout<<"sites: "<<2.0*sites;
    cout<<" Energy: "<<Eval/(2.0*sites)<<endl;

    rhoTSR = 0;
    for (i1=0; i1< 2*st; i1++)
      for (i1p=0; i1p< 2*st; i1p++)
        for (i2=0; i2< 2*st; i2++)
 	  rhoTSR(i1,i1p) += Psi(i1,i2)*Psi(i1p,i2);

    OO.resize(2*st,2*st);
    OT.resize(2*st,2*st);
    DMlargeEigen(rhoTSR, OO, 2*st, 2*st);
    for (i1=0; i1<2*st; i1++)
      for (i2=0; i2< 2*st; i2++)
        OT(i1,i2) = OO(i2,i1);  //Transpose

    blk.HAp.resize(2*st,2*st);
    //transform Operator Matrices to new basis
    Hl.resize(2*st,2*st);
    Hl = sum(HAB(i,k)*OT(k,j),k);   //Ha'
    blk.HAp = sum(OO(i,k)*Hl(k,j),k);   //(inner product)

    blk.SzL.resize(2*st,2*st);
    Hl = sum(SzAB(i,k)*OT(k,j),k);
    blk.SzL = sum(OO(i,k)*Hl(k,j),k);

    blk.SpL.resize(2*st,2*st);
    Hl = sum(SpAB(i,k)*OT(k,j),k);
    blk.SpL = sum(OO(i,k)*Hl(k,j),k);

    blk.SmL.resize(2*st,2*st);
    Hl = sum(SmAB(i,k)*OT(k,j),k);
    blk.SmL = sum(OO(i,k)*Hl(k,j),k);

    // Add a single spin  (m*m*2*2 tensor)
    st *= 2;
    TSR.resize(st,2,st,2);

    TSR = blk.HAp(i,k)*I2(j,l) + blk.SzL(i,k)*Sz(j,l)+
      0.5*blk.SpL(i,k)*Sm(j,l) + 0.5*blk.SmL(i,k)*Sp(j,l) ;
    HAB.resize(2*st,2*st);            //Hamiltonian for next iteration
    HAB = reduceM2M2(TSR,st);
   //   cout<<HAB<<endl;

    SzAB.resize(2*st,2*st);  //Operators for next iteration
    TSR = I2st(i,k)*Sz(j,l);
    SzAB = reduceM2M2(TSR,st);

    SpAB.resize(2*st,2*st);
    TSR = I2st(i,k)*Sp(j,l);
    SpAB = reduceM2M2(TSR,st);

    SmAB.resize(2*st,2*st);
    TSR = I2st(i,k)*Sm(j,l);
    SmAB = reduceM2M2(TSR,st);

    Habcd.resize(2*st,2*st,2*st,2*st);   //re-prepare superblock matrix
    Psi.resize(2*st,2*st);             //GS wavefunction
    rhoTSR.resize(2*st,2*st);

//    st *= 2;
    sites += 1;

    I2st.resize(4*st,4*st);    //redifine identity matrix
    I2st = 0.0;
    for (b1=0; b1<(4*st); b1++) I2st(b1,b1)=1.0;

  }//end while

  blk.size = sites-1;
  fname[2] = 48 + (blk.size)%10;          //some ASCII crap
  fname[1] = 48 + (blk.size-blk.size%10)/100;
  fname[0] = 48;
  fout.open(fname,ios::out);
  fout << blk.size <<endl;
  fout << blk.HAp ;
  fout << blk.SzL ;
  fout << blk.SpL ;
  fout << blk.SmL ;
  fout.close();

  OO.resize(m,(2*st));
  OT.resize((2*st),m);
  Hl.resize((2*st),m);

  /*******************second+ iteration down here*************/

  for (iter = 1; iter<NumI; iter++){

    Habcd = HAB(i,k)*I2st(j,l) + I2st(i,k)*HAB(j,l) +
      SzAB(i,k)*SzAB(j,l)+ 0.5*SpAB(i,k)*SmAB(j,l) + 0.5*SmAB(i,k)*SpAB(j,l);

    EigenValuesLAN(Habcd,Psi,(4*st*st),&Eval);
    cout<<2*sites<<" "<<Eval/(2.0*sites)<<endl;

    rhoTSR = 0;
    for (i1=0; i1< 2*st; i1++)
      for (i1p=0; i1p< 2*st; i1p++)
        for (i2=0; i2< 2*st; i2++)
 	  rhoTSR(i1,i1p) += Psi(i1,i2)*Psi(i1p,i2);

    DMlargeEigen(rhoTSR, OO, 2*st, m);
    for (i1=0; i1<2*st; i1++)
      for (i2=0; i2< m; i2++)
        OT(i1,i2) = OO(i2,i1);  //Transpose

    st = m;

    if (iter == 1) blk.HAp.resize(m,m);
    //transform Operator Matrices to new basis
    Hl = sum(HAB(i,k)*OT(k,j),k);   //Ha'
    blk.HAp = sum(OO(i,k)*Hl(k,j),k);   //(inner product)

    if (iter == 1) blk.SzL.resize(m,m);
    Hl = sum(SzAB(i,k)*OT(k,j),k);
    blk.SzL = sum(OO(i,k)*Hl(k,j),k);

    if (iter == 1) blk.SpL.resize(m,m);
    Hl = sum(SpAB(i,k)*OT(k,j),k);
    blk.SpL = sum(OO(i,k)*Hl(k,j),k);

    if (iter == 1) blk.SmL.resize(m,m);
    Hl = sum(SmAB(i,k)*OT(k,j),k);
    blk.SmL = sum(OO(i,k)*Hl(k,j),k);

   if (iter == 1) TSR.resize(m,2,m,2);
    // Add a single spin  (m*m*2*2 tensor)
    TSR = blk.HAp(i,k)*I2(j,l) + blk.SzL(i,k)*Sz(j,l)+
      0.5*blk.SpL(i,k)*Sm(j,l) + 0.5*blk.SmL(i,k)*Sp(j,l) ;
    if (iter == 1) HAB.resize(2*m,2*m);
    HAB = reduceM2M2(TSR,m);

    if (iter == 1){
      SzAB.resize(2*m,2*m);  //Operators for next iteration
      TSR = I2m(i,k)*Sz(j,l);
      SzAB = reduceM2M2(TSR,m);

      SpAB.resize(2*m,2*m);
      TSR = I2m(i,k)*Sp(j,l);
      SpAB = reduceM2M2(TSR,m);

      SmAB.resize(2*m,2*m);
      TSR = I2m(i,k)*Sm(j,l);
      SmAB = reduceM2M2(TSR,m);
    }

   st = m;
   sites += 1;

   if (iter == 1){    //final resize
    I2st.resize(2*m,2*m);
    I2st = I2m;

    Habcd.resize(2*m,2*m,2*m,2*m);   //re-prepare superblock matrix
    Psi.resize(2*m,2*m);             //GS wavefunction
    rhoTSR.resize(2*m,2*m);
    OO.resize(m,(2*m));
    OT.resize((2*m),m);
    Hl.resize((2*m),m);

   }

  }//iter

  return 0;
}

/*****************************************************************/
template<typename T>
Array<T,2> reduceM2M2(const Array<T,4>& T2, const int m)
/****reduces a m,2,m,2 matrix to a 2m*2m matrix
     over the direct product basis of 2 spins*************/
{
  int r,c;
  Array<double,2> M4(2*m,2*m);

  r=0;
  for (int a1=0; a1<m; a1++)
    for (int a2=0; a2<2; a2++){
      c=0;
      for (int a3=0; a3<m; a3++)
	for (int a4=0; a4<2; a4++){
	  M4(r,c) = T2(a1,a2,a3,a4);
	  c++;
	}
      r++;
    }

  return M4;

}

<commit_msg> BlockRead and BlockWrite procedures added to write blocks to file<commit_after>// Elementary DMRG for Heisenberg S=1/2 chain,
// infinite system algorithm to build chain
// ED with Lanczos
// finite system sweep
//
//Roger Melko May 9 2006

#include <blitz/array.h>
#include <fstream>

BZ_USING_NAMESPACE(blitz)

//block object
struct BLOCK {
  int size;    //# of sites
  Array<double,2> HAp;  //A' block hamiltonian
  Array<double,2> SzL;   //Sz(left) operator
  Array<double,2> SmL;   //Sm(left) operator
  Array<double,2> SpL;   //Sp(left) operator
};

//template function prototypes
template<typename T> Array<T,2> reduceM2M2(const Array<T,4>&, const int);
void EigenValuesLAN(Array<double,4>&, Array<double,2>&, const int, double *);
void DMlargeEigen(Array<double,2>&, Array<double,2>&, const int, const int);
void BlockWrite(BLOCK *, const int, char []);
void BlockRead(BLOCK *, const int, char []);

int main()
{
  int iter, NumI;
  int i1, i1p, i2, i2p, i3, i4;
  int b1;
  int m, st;     //# states
  int sites;     //# sites
  double Eval;   //Eigenvalue
  BLOCK blk;
  char fname[7];

  //initialize filename
  fname[0] = '.'; fname[1] = '0'; fname[2] = '0';
  fname[3] = '.';
  fname[4] = 'e'; fname[5] = 'n'; fname[6] = 'v';

  cout<<"# states to keep: ";
  cin>>m;

  //Matrices
  Array<double,4> TSR(2,2,2,2);  //tensor product for Hab hamiltonian

  Array<double,4> Habcd(4,4,4,4); //superblock hamiltonian
  Array<double,2> HAB(4,4);        //new SYSTEM Hamiltonian
  Array<double,2> Psi(4,4); // ground state wavefunction
  Array<double,2> rhoTSR(4,4); // reduced density matrix
  Array<double,2> OO(m,4);   //the TRUNCATION matrix
  Array<double,2> OT(4,m);   // trasposed truncation matrix
  Array<double,2> Hl(4,m);   // the left half of new system H

  //create identity matrices
  Array<double,2> I2(2,2), I4(4,4), I2m(2*m,2*m);
  I2=0.0; I4=0.0; I2m=0.0;
  for (b1=0; b1<2; b1++) I2(b1,b1)=1.0;
  for (b1=0; b1<4; b1++) I4(b1,b1)=1.0;
  for (b1=0; b1<(2*m); b1++) I2m(b1,b1)=1.0;
  Array<double,2> I2st(4,4);
  I2st = I4;

  // Create pauli matrices
  Array<double,2> Sz(2,2), Sp(2,2), Sm(2,2);
  Sz = 0.5, 0,
       0, -0.5;
  Sp = 0, 1.0,
       0, 0;
  Sm = 0, 0,
       1.0, 0;

  //tensor indices
  firstIndex i;    secondIndex j;
  thirdIndex k;    fourthIndex l;

  cout<<"Iterations : ";
  cin>>NumI;

  //create a tensor product: two-site Hamiltonian
  TSR = Sz(i,k)*Sz(j,l)+ 0.5*Sp(i,k)*Sm(j,l) + 0.5*Sm(i,k)*Sp(j,l) ;
  //write as 2D matrix in combined basis
  Array<double,2> H12 = reduceM2M2(TSR,2);
  //cout<<"H12 "<<H12<<endl;

  TSR = Sz(i,k)*I2(j,l);
  Array<double,2> SzAB = reduceM2M2(TSR,2);

  TSR = Sm(i,k)*I2(j,l);
  Array<double,2> SmAB = reduceM2M2(TSR,2);

  TSR = Sp(i,k)*I2(j,l);
  Array<double,2> SpAB = reduceM2M2(TSR,2);

  HAB = H12;
  st = 2;     //start with a 2^2=4 state system
  sites = 2;

  /******infinite system algorithm loop first iteration**********/
  /******build system until number of desired states m **********/

  while(st <= m) {

   Habcd = HAB(i,k)*I2st(j,l) + I2st(i,k)*HAB(j,l) +
      SzAB(i,k)*SzAB(j,l)+ 0.5*SpAB(i,k)*SmAB(j,l) + 0.5*SmAB(i,k)*SpAB(j,l);

    EigenValuesLAN(Habcd,Psi,(4*st*st),&Eval);

    cout<<"sites: "<<2.0*sites;
    cout<<" Energy: "<<Eval/(2.0*sites)<<endl;

    rhoTSR = 0;
    for (i1=0; i1< 2*st; i1++)
      for (i1p=0; i1p< 2*st; i1p++)
        for (i2=0; i2< 2*st; i2++)
 	  rhoTSR(i1,i1p) += Psi(i1,i2)*Psi(i1p,i2);

    OO.resize(2*st,2*st);
    OT.resize(2*st,2*st);
    DMlargeEigen(rhoTSR, OO, 2*st, 2*st);
    for (i1=0; i1<2*st; i1++)
      for (i2=0; i2< 2*st; i2++)
        OT(i1,i2) = OO(i2,i1);  //Transpose

    blk.HAp.resize(2*st,2*st);
    //transform Operator Matrices to new basis
    Hl.resize(2*st,2*st);
    Hl = sum(HAB(i,k)*OT(k,j),k);   //Ha'
    blk.HAp = sum(OO(i,k)*Hl(k,j),k);   //(inner product)

    blk.SzL.resize(2*st,2*st);
    Hl = sum(SzAB(i,k)*OT(k,j),k);
    blk.SzL = sum(OO(i,k)*Hl(k,j),k);

    blk.SpL.resize(2*st,2*st);
    Hl = sum(SpAB(i,k)*OT(k,j),k);
    blk.SpL = sum(OO(i,k)*Hl(k,j),k);

    blk.SmL.resize(2*st,2*st);
    Hl = sum(SmAB(i,k)*OT(k,j),k);
    blk.SmL = sum(OO(i,k)*Hl(k,j),k);

    // Add a single spin  (m*m*2*2 tensor)
    st *= 2;
    TSR.resize(st,2,st,2);

    TSR = blk.HAp(i,k)*I2(j,l) + blk.SzL(i,k)*Sz(j,l)+
      0.5*blk.SpL(i,k)*Sm(j,l) + 0.5*blk.SmL(i,k)*Sp(j,l) ;
    HAB.resize(2*st,2*st);            //Hamiltonian for next iteration
    HAB = reduceM2M2(TSR,st);
   //   cout<<HAB<<endl;

    SzAB.resize(2*st,2*st);  //Operators for next iteration
    TSR = I2st(i,k)*Sz(j,l);
    SzAB = reduceM2M2(TSR,st);

    SpAB.resize(2*st,2*st);
    TSR = I2st(i,k)*Sp(j,l);
    SpAB = reduceM2M2(TSR,st);

    SmAB.resize(2*st,2*st);
    TSR = I2st(i,k)*Sm(j,l);
    SmAB = reduceM2M2(TSR,st);

    Habcd.resize(2*st,2*st,2*st,2*st);   //re-prepare superblock matrix
    Psi.resize(2*st,2*st);             //GS wavefunction
    rhoTSR.resize(2*st,2*st);

//    st *= 2;
    sites += 1;

    I2st.resize(4*st,4*st);    //redifine identity matrix
    I2st = 0.0;
    for (b1=0; b1<(4*st); b1++) I2st(b1,b1)=1.0;

  }//end while

  BlockWrite(&blk,sites-1,fname);

  OO.resize(m,(2*st));
  OT.resize((2*st),m);
  Hl.resize((2*st),m);

  /*******************second+ iteration down here*************/

  for (iter = 1; iter<NumI; iter++){

    Habcd = HAB(i,k)*I2st(j,l) + I2st(i,k)*HAB(j,l) +
      SzAB(i,k)*SzAB(j,l)+ 0.5*SpAB(i,k)*SmAB(j,l) + 0.5*SmAB(i,k)*SpAB(j,l);

    EigenValuesLAN(Habcd,Psi,(4*st*st),&Eval);
    cout<<2*sites<<" "<<Eval/(2.0*sites)<<endl;

    rhoTSR = 0;
    for (i1=0; i1< 2*st; i1++)
      for (i1p=0; i1p< 2*st; i1p++)
        for (i2=0; i2< 2*st; i2++)
 	  rhoTSR(i1,i1p) += Psi(i1,i2)*Psi(i1p,i2);

    DMlargeEigen(rhoTSR, OO, 2*st, m);
    for (i1=0; i1<2*st; i1++)
      for (i2=0; i2< m; i2++)
        OT(i1,i2) = OO(i2,i1);  //Transpose

    st = m;

    if (iter == 1) blk.HAp.resize(m,m);
    //transform Operator Matrices to new basis
    Hl = sum(HAB(i,k)*OT(k,j),k);   //Ha'
    blk.HAp = sum(OO(i,k)*Hl(k,j),k);   //(inner product)

    if (iter == 1) blk.SzL.resize(m,m);
    Hl = sum(SzAB(i,k)*OT(k,j),k);
    blk.SzL = sum(OO(i,k)*Hl(k,j),k);

    if (iter == 1) blk.SpL.resize(m,m);
    Hl = sum(SpAB(i,k)*OT(k,j),k);
    blk.SpL = sum(OO(i,k)*Hl(k,j),k);

    if (iter == 1) blk.SmL.resize(m,m);
    Hl = sum(SmAB(i,k)*OT(k,j),k);
    blk.SmL = sum(OO(i,k)*Hl(k,j),k);

   BlockWrite(&blk, sites, fname);

   if (iter == 1) TSR.resize(m,2,m,2);
    // Add a single spin  (m*m*2*2 tensor)
    TSR = blk.HAp(i,k)*I2(j,l) + blk.SzL(i,k)*Sz(j,l)+
      0.5*blk.SpL(i,k)*Sm(j,l) + 0.5*blk.SmL(i,k)*Sp(j,l) ;
    if (iter == 1) HAB.resize(2*m,2*m);
    HAB = reduceM2M2(TSR,m);

    if (iter == 1){
      SzAB.resize(2*m,2*m);  //Operators for next iteration
      TSR = I2m(i,k)*Sz(j,l);
      SzAB = reduceM2M2(TSR,m);

      SpAB.resize(2*m,2*m);
      TSR = I2m(i,k)*Sp(j,l);
      SpAB = reduceM2M2(TSR,m);

      SmAB.resize(2*m,2*m);
      TSR = I2m(i,k)*Sm(j,l);
      SmAB = reduceM2M2(TSR,m);
    }

   st = m;
   sites += 1;

   if (iter == 1){    //final resize
    I2st.resize(2*m,2*m);
    I2st = I2m;

    Habcd.resize(2*m,2*m,2*m,2*m);   //re-prepare superblock matrix
    Psi.resize(2*m,2*m);             //GS wavefunction
    rhoTSR.resize(2*m,2*m);
    OO.resize(m,(2*m));
    OT.resize((2*m),m);
    Hl.resize((2*m),m);

   }

  }//iter

  BlockRead(&blk,5,fname);

  cout<<blk.SzL;

  return 0;
}

/*****************************************************************/
template<typename T>
Array<T,2> reduceM2M2(const Array<T,4>& T2, const int m)
/****reduces a m,2,m,2 matrix to a 2m*2m matrix
     over the direct product basis of 2 spins*************/
{
  int r,c;
  Array<double,2> M4(2*m,2*m);

  r=0;
  for (int a1=0; a1<m; a1++)
    for (int a2=0; a2<2; a2++){
      c=0;
      for (int a3=0; a3<m; a3++)
	for (int a4=0; a4<2; a4++){
	  M4(r,c) = T2(a1,a2,a3,a4);
	  c++;
	}
      r++;
    }

  return M4;

}

/*****************************************************************/
void BlockWrite(BLOCK *blk, const int sites, char fname[])
{
  ofstream fout;

  blk->size = sites;
  fname[2] = 48 + (blk->size)%10;          //some ASCII crap
//  fname[1] = 48 + (blk->size-blk->size%10)/100;
//  fname[0] = 48;

  fout.open(fname,ios::out);
  fout << blk->size <<endl;
  fout << blk->HAp ;
  fout << blk->SzL ;
  fout << blk->SpL ;
  fout << blk->SmL ;
  fout.close();

} //BlockWrite

/*****************************************************************/
void BlockRead(BLOCK *blk, const int sites, char fname[])
{
  ifstream fin;

  blk->size = sites;
  fname[2] = 48 + (blk->size)%10;          //some ASCII crap
//  fname[1] = 48 + (blk->size-blk->size%10)/100;
//  fname[0] = 48;

  fin.open(fname,ios::in);
  fin >> blk->size;
  fin >> blk->HAp ;
  fin >> blk->SzL ;
  fin >> blk->SpL ;
  fin >> blk->SmL ;
  fin.close();

//  cout<<blk->HAp;

}
<|endoftext|>


<commit_before>// Copyright 2022 Michael Fisher <mfisher@lvtk.org>
// SPDX-License-Identifier: ISC

#pragma once

#include <lvtk/ui/widget.hpp>

namespace lvtk {

class Main;

class Embed final : public Widget {
public:
    Embed (Main& main);
    ~Embed();

    ViewRef host_view() const noexcept;

    void paint (Graphics& g) override;
    void resized() override;

protected:
    void children_changed() override;
    void parent_structure_changed() override;

private:
    class Window;
    std::unique_ptr<Window> window;
};

} // namespace lvtk
<commit_msg>embed: add LVTK_API tag<commit_after>// Copyright 2022 Michael Fisher <mfisher@lvtk.org>
// SPDX-License-Identifier: ISC

#pragma once

#include <lvtk/lvtk.h>
#include <lvtk/ui/widget.hpp>

namespace lvtk {

class Main;

class LVTK_API Embed final : public Widget {
public:
    Embed (Main& main);
    ~Embed();

    ViewRef host_view() const noexcept;

    void paint (Graphics& g) override;
    void resized() override;

protected:
    void children_changed() override;
    void parent_structure_changed() override;

private:
    class Window;
    std::unique_ptr<Window> window;
    LVTK_DISABLE_COPY (Embed);
};

} // namespace lvtk
<|endoftext|>


<commit_before>#include <iostream>

#include <boost/thread.hpp>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <include/HogCPU.h>

#include "utils.h"

class ResizeCallback: public ghog::lib::ImageCallback
{
public:
	ResizeCallback(int num_images)
	{
		_finished = 0;
		_total_images = num_images;
	}

	void image_processed(cv::Mat original,
		cv::Mat processed)
	{
		_finished++;
	}

	bool is_finished()
	{
		return (_finished == _total_images);
	}

private:
	int _finished;
	int _total_images;
};

int main(int argc,
	char** argv)
{
	std::vector<std::string> file_list = getImagesList("resources/inputs");
	ResizeCallback callback(file_list.size());
	ghog::lib::IHog* utils = new ghog::lib::HogCPU("hog.xml");
	cv::Size new_size(24, 24);

	for(int i = 0; i < file_list.size(); ++i)
	{
		cv::Mat input_img = cv::imread(file_list[i], CV_LOAD_IMAGE_GRAYSCALE);
		utils->resize(input_img, new_size, &callback);
	}
	std::cout << "Processing " << file_list.size() << " images..." << std::endl;
	while(!callback.is_finished())
	{
		std::cout << ".";
		std::cout.flush();
		boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
	}
	std::cout << std::endl;
	std::cout << "Images processed." << std::endl;
	return 0;
}

<commit_msg>Fix undefined references.<commit_after>#include <iostream>

#include <boost/thread.hpp>

#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>

#include <include/HogCPU.h>

#include "utils.h"

class ResizeCallback: public ghog::lib::ImageCallback
{
public:
	ResizeCallback(int num_images)
	{
		_finished = 0;
		_total_images = num_images;
	}

	void image_processed(cv::Mat original,
		cv::Mat processed)
	{
		_finished++;
	}

	bool is_finished()
	{
		return (_finished == _total_images);
	}

private:
	int _finished;
	int _total_images;
};

int main(int argc,
	char** argv)
{
	std::vector<std::string> file_list = getImagesList("resources/images");
	ResizeCallback callback(file_list.size());
	ghog::lib::IHog* utils = new ghog::lib::HogCPU("hog.xml");
	cv::Size new_size(24, 24);

	for(int i = 0; i < file_list.size(); ++i)
	{
		cv::Mat input_img = cv::imread(file_list[i], CV_LOAD_IMAGE_GRAYSCALE);
		utils->resize(input_img, new_size, &callback);
	}
	std::cout << "Processing " << file_list.size() << " images..." << std::endl;
	while(!callback.is_finished())
	{
		std::cout << ".";
		std::cout.flush();
		boost::this_thread::sleep(boost::posix_time::milliseconds(1000));
	}
	std::cout << std::endl;
	std::cout << "Images processed." << std::endl;
	return 0;
}

<|endoftext|>