<commit_before>/*
 * Copyright 2011-2013 Blender Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

#include <stdio.h>

#include "buffers.h"
#include "camera.h"
#include "device.h"
#include "scene.h"
#include "session.h"

#include "util_args.h"
#include "util_foreach.h"
#include "util_function.h"
#include "util_path.h"
#include "util_progress.h"
#include "util_string.h"
#include "util_time.h"
#include "util_transform.h"

#ifdef WITH_CYCLES_STANDALONE_GUI
#include "util_view.h"
#endif

#include "cycles_xml.h"

CCL_NAMESPACE_BEGIN

struct Options {
	Session *session;
	Scene *scene;
	string filepath;
	int width, height;
	SceneParams scene_params;
	SessionParams session_params;
	bool quiet;
	bool show_help, interactive, pause;
} options;

static void session_print(const string& str)
{
	/* print with carriage return to overwrite previous */
	printf("\r%s", str.c_str());

	/* add spaces to overwrite longer previous print */
	static int maxlen = 0;
	int len = str.size();
	maxlen = max(len, maxlen);

	for(int i = len; i < maxlen; i++)
		printf(" ");

	/* flush because we don't write an end of line */
	fflush(stdout);
}

static void session_print_status()
{
	int sample, tile;
	double total_time, sample_time;
	string status, substatus;

	/* get status */
	sample = options.session->progress.get_sample();
	options.session->progress.get_tile(tile, total_time, sample_time);
	options.session->progress.get_status(status, substatus);

	if(substatus != "")
		status += ": " + substatus;

	/* print status */
	status = string_printf("Sample %d   %s", sample, status.c_str());
	session_print(status);
}

static BufferParams& session_buffer_params()
{
	static BufferParams buffer_params;
	buffer_params.width = options.width;
	buffer_params.height = options.height;
	buffer_params.full_width = options.width;
	buffer_params.full_height = options.height;

	return buffer_params;
}

static void session_init()
{
	options.session = new Session(options.session_params);
	options.session->reset(session_buffer_params(), options.session_params.samples);
	options.session->scene = options.scene;

	if(options.session_params.background && !options.quiet)
		options.session->progress.set_update_callback(function_bind(&session_print_status));
#ifdef WITH_CYCLES_STANDALONE_GUI
	else
		options.session->progress.set_update_callback(function_bind(&view_redraw));
#endif

	options.session->start();

	options.scene = NULL;
}

static void scene_init()
{
	options.scene = new Scene(options.scene_params, options.session_params.device);

	/* Read XML */
	xml_read_file(options.scene, options.filepath.c_str());

	/* Camera width/height override? */
	if (!(options.width == 0 || options.height == 0)) {
		options.scene->camera->width = options.width;
		options.scene->camera->height = options.height;
	}
	else {
		options.width = options.scene->camera->width;
		options.height = options.scene->camera->height;
	}

	/* Calculate Viewplane */
	options.scene->camera->compute_auto_viewplane();
}

static void session_exit()
{
	if(options.session) {
		delete options.session;
		options.session = NULL;
	}
	if(options.scene) {
		delete options.scene;
		options.scene = NULL;
	}

	if(options.session_params.background && !options.quiet) {
		session_print("Finished Rendering.");
		printf("\n");
	}
}

#ifdef WITH_CYCLES_STANDALONE_GUI
static void display_info(Progress& progress)
{
	static double latency = 0.0;
	static double last = 0;
	double elapsed = time_dt();
	string str, interactive;

	latency = (elapsed - last);
	last = elapsed;

	int sample, tile;
	double total_time, sample_time;
	string status, substatus;

	sample = progress.get_sample();
	progress.get_tile(tile, total_time, sample_time);
	progress.get_status(status, substatus);

	if(substatus != "")
		status += ": " + substatus;

	interactive = options.interactive? "On":"Off";

	str = string_printf(
	        "%s"
	        "        Time: %.2f"
	        "        Latency: %.4f"
	        "        Sample: %d"
	        "        Average: %.4f"
	        "        Interactive: %s",
	        status.c_str(), total_time, latency, sample, sample_time, interactive.c_str());

	view_display_info(str.c_str());

	if(options.show_help)
		view_display_help();
}

static void display()
{
	static DeviceDrawParams draw_params = DeviceDrawParams();

	options.session->draw(session_buffer_params(), draw_params);

	display_info(options.session->progress);
}

static void motion(int x, int y, int button)
{
	if(options.interactive) {
		Transform matrix = options.session->scene->camera->matrix;

		/* Translate */
		if(button == 0) {
			float3 translate = make_float3(x * 0.01f, -(y * 0.01f), 0.0f);
			matrix = matrix * transform_translate(translate);
		}

		/* Rotate */
		else if(button == 2) {
			float4 r1 = make_float4((float)x * 0.1f, 0.0f, 1.0f, 0.0f);
			matrix = matrix * transform_rotate(DEG2RADF(r1.x), make_float3(r1.y, r1.z, r1.w));

			float4 r2 = make_float4(y * 0.1f, 1.0f, 0.0f, 0.0f);
			matrix = matrix * transform_rotate(DEG2RADF(r2.x), make_float3(r2.y, r2.z, r2.w));
		}

		/* Update and Reset */
		options.session->scene->camera->matrix = matrix;
		options.session->scene->camera->need_update = true;
		options.session->scene->camera->need_device_update = true;

		options.session->reset(session_buffer_params(), options.session_params.samples);
	}
}

static void resize(int width, int height)
{
	options.width = width;
	options.height = height;

	if(options.session) {
		/* Update camera */
		options.session->scene->camera->width = width;
		options.session->scene->camera->height = height;
		options.session->scene->camera->compute_auto_viewplane();
		options.session->scene->camera->need_update = true;
		options.session->scene->camera->need_device_update = true;

		options.session->reset(session_buffer_params(), options.session_params.samples);
	}
}

static void keyboard(unsigned char key)
{
	/* Toggle help */
	if(key == 'h')
		options.show_help = !(options.show_help);

	/* Reset */
	else if(key == 'r')
		options.session->reset(session_buffer_params(), options.session_params.samples);

	/* Cancel */
	else if(key == 27) // escape
		options.session->progress.set_cancel("Canceled");

	/* Pause */
	else if(key == 'p') {
		options.pause = !options.pause;
		options.session->set_pause(options.pause);
	}

	/* Interactive Mode */
	else if(key == 'i')
		options.interactive = !(options.interactive);

	else if(options.interactive && (key == 'w' || key == 'a' || key == 's' || key == 'd')) {
		Transform matrix = options.session->scene->camera->matrix;
		float3 translate;

		if(key == 'w')
			translate = make_float3(0.0f, 0.0f, 0.1f);
		else if(key == 's')
			translate = make_float3(0.0f, 0.0f, -0.1f);
		else if(key == 'a')
			translate = make_float3(-0.1f, 0.0f, 0.0f);
		else if(key == 'd')
			translate = make_float3(0.1f, 0.0f, 0.0f);

		matrix = matrix * transform_translate(translate);

		/* Update and Reset */
		options.session->scene->camera->matrix = matrix;
		options.session->scene->camera->need_update = true;
		options.session->scene->camera->need_device_update = true;

		options.session->reset(session_buffer_params(), options.session_params.samples);
	}
}
#endif

static int files_parse(int argc, const char *argv[])
{
	if(argc > 0)
		options.filepath = argv[0];

	return 0;
}

static void options_parse(int argc, const char **argv)
{
	options.width = 0;
	options.height = 0;
	options.filepath = "";
	options.session = NULL;
	options.quiet = false;

	/* device names */
	string device_names = "";
	string devicename = "cpu";
	bool list = false;

	vector<DeviceType>& types = Device::available_types();

	foreach(DeviceType type, types) {
		if(device_names != "")
			device_names += ", ";

		device_names += Device::string_from_type(type);
	}

	/* shading system */
	string ssname = "svm";

	/* parse options */
	ArgParse ap;
	bool help = false;

	ap.options ("Usage: cycles [options] file.xml",
		"%*", files_parse, "",
		"--device %s", &devicename, ("Devices to use: " + device_names).c_str(),
#ifdef WITH_OSL
		"--shadingsys %s", &ssname, "Shading system to use: svm, osl",
#endif
		"--background", &options.session_params.background, "Render in background, without user interface",
		"--quiet", &options.quiet, "In background mode, don't print progress messages",
		"--samples %d", &options.session_params.samples, "Number of samples to render",
		"--output %s", &options.session_params.output_path, "File path to write output image",
		"--threads %d", &options.session_params.threads, "CPU Rendering Threads",
		"--width  %d", &options.width, "Window width in pixel",
		"--height %d", &options.height, "Window height in pixel",
		"--list-devices", &list, "List information about all available devices",
		"--help", &help, "Print help message",
		NULL);

	if(ap.parse(argc, argv) < 0) {
		fprintf(stderr, "%s\n", ap.geterror().c_str());
		ap.usage();
		exit(EXIT_FAILURE);
	}
	else if(list) {
		vector<DeviceInfo>& devices = Device::available_devices();
		printf("Devices:\n");

		foreach(DeviceInfo& info, devices) {
			printf("    %s%s\n",
				info.description.c_str(),
				(info.display_device)? " (display)": "");
		}

		exit(EXIT_SUCCESS);
	}
	else if(help || options.filepath == "") {
		ap.usage();
		exit(EXIT_SUCCESS);
	}

	if(ssname == "osl")
		options.scene_params.shadingsystem = SceneParams::OSL;
	else if(ssname == "svm")
		options.scene_params.shadingsystem = SceneParams::SVM;

#ifndef WITH_CYCLES_STANDALONE_GUI
	options.session_params.background = true;
#endif

	/* Use progressive rendering */
	options.session_params.progressive = true;

	/* find matching device */
	DeviceType device_type = Device::type_from_string(devicename.c_str());
	vector<DeviceInfo>& devices = Device::available_devices();
	DeviceInfo device_info;
	bool device_available = false;

	foreach(DeviceInfo& device, devices) {
		if(device_type == device.type) {
			options.session_params.device = device;
			device_available = true;
			break;
		}
	}

	/* handle invalid configurations */
	if(options.session_params.device.type == DEVICE_NONE || !device_available) {
		fprintf(stderr, "Unknown device: %s\n", devicename.c_str());
		exit(EXIT_FAILURE);
	}
#ifdef WITH_OSL
	else if(!(ssname == "osl" || ssname == "svm")) {
		fprintf(stderr, "Unknown shading system: %s\n", ssname.c_str());
		exit(EXIT_FAILURE);
	}
	else if(options.scene_params.shadingsystem == SceneParams::OSL && options.session_params.device.type != DEVICE_CPU) {
		fprintf(stderr, "OSL shading system only works with CPU device\n");
		exit(EXIT_FAILURE);
	}
#endif
	else if(options.session_params.samples < 0) {
		fprintf(stderr, "Invalid number of samples: %d\n", options.session_params.samples);
		exit(EXIT_FAILURE);
	}
	else if(options.filepath == "") {
		fprintf(stderr, "No file path specified\n");
		exit(EXIT_FAILURE);
	}

	/* For smoother Viewport */
	options.session_params.start_resolution = 64;

	/* load scene */
	scene_init();
}

CCL_NAMESPACE_END

using namespace ccl;

int main(int argc, const char **argv)
{
	path_init();
	options_parse(argc, argv);

#ifdef WITH_CYCLES_STANDALONE_GUI
	if(options.session_params.background) {
#endif
		session_init();
		options.session->wait();
		session_exit();
#ifdef WITH_CYCLES_STANDALONE_GUI
	}
	else {
		string title = "Cycles: " + path_filename(options.filepath);

		/* init/exit are callback so they run while GL is initialized */
		view_main_loop(title.c_str(), options.width, options.height,
			session_init, session_exit, resize, display, keyboard, motion);
	}
#endif

	return 0;
}

<commit_msg>Fix cycles standalone compile error of shading system enum change.<commit_after>/*
 * Copyright 2011-2013 Blender Foundation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

#include <stdio.h>

#include "buffers.h"
#include "camera.h"
#include "device.h"
#include "scene.h"
#include "session.h"

#include "util_args.h"
#include "util_foreach.h"
#include "util_function.h"
#include "util_path.h"
#include "util_progress.h"
#include "util_string.h"
#include "util_time.h"
#include "util_transform.h"

#ifdef WITH_CYCLES_STANDALONE_GUI
#include "util_view.h"
#endif

#include "cycles_xml.h"

CCL_NAMESPACE_BEGIN

struct Options {
	Session *session;
	Scene *scene;
	string filepath;
	int width, height;
	SceneParams scene_params;
	SessionParams session_params;
	bool quiet;
	bool show_help, interactive, pause;
} options;

static void session_print(const string& str)
{
	/* print with carriage return to overwrite previous */
	printf("\r%s", str.c_str());

	/* add spaces to overwrite longer previous print */
	static int maxlen = 0;
	int len = str.size();
	maxlen = max(len, maxlen);

	for(int i = len; i < maxlen; i++)
		printf(" ");

	/* flush because we don't write an end of line */
	fflush(stdout);
}

static void session_print_status()
{
	int sample, tile;
	double total_time, sample_time;
	string status, substatus;

	/* get status */
	sample = options.session->progress.get_sample();
	options.session->progress.get_tile(tile, total_time, sample_time);
	options.session->progress.get_status(status, substatus);

	if(substatus != "")
		status += ": " + substatus;

	/* print status */
	status = string_printf("Sample %d   %s", sample, status.c_str());
	session_print(status);
}

static BufferParams& session_buffer_params()
{
	static BufferParams buffer_params;
	buffer_params.width = options.width;
	buffer_params.height = options.height;
	buffer_params.full_width = options.width;
	buffer_params.full_height = options.height;

	return buffer_params;
}

static void session_init()
{
	options.session = new Session(options.session_params);
	options.session->reset(session_buffer_params(), options.session_params.samples);
	options.session->scene = options.scene;

	if(options.session_params.background && !options.quiet)
		options.session->progress.set_update_callback(function_bind(&session_print_status));
#ifdef WITH_CYCLES_STANDALONE_GUI
	else
		options.session->progress.set_update_callback(function_bind(&view_redraw));
#endif

	options.session->start();

	options.scene = NULL;
}

static void scene_init()
{
	options.scene = new Scene(options.scene_params, options.session_params.device);

	/* Read XML */
	xml_read_file(options.scene, options.filepath.c_str());

	/* Camera width/height override? */
	if (!(options.width == 0 || options.height == 0)) {
		options.scene->camera->width = options.width;
		options.scene->camera->height = options.height;
	}
	else {
		options.width = options.scene->camera->width;
		options.height = options.scene->camera->height;
	}

	/* Calculate Viewplane */
	options.scene->camera->compute_auto_viewplane();
}

static void session_exit()
{
	if(options.session) {
		delete options.session;
		options.session = NULL;
	}
	if(options.scene) {
		delete options.scene;
		options.scene = NULL;
	}

	if(options.session_params.background && !options.quiet) {
		session_print("Finished Rendering.");
		printf("\n");
	}
}

#ifdef WITH_CYCLES_STANDALONE_GUI
static void display_info(Progress& progress)
{
	static double latency = 0.0;
	static double last = 0;
	double elapsed = time_dt();
	string str, interactive;

	latency = (elapsed - last);
	last = elapsed;

	int sample, tile;
	double total_time, sample_time;
	string status, substatus;

	sample = progress.get_sample();
	progress.get_tile(tile, total_time, sample_time);
	progress.get_status(status, substatus);

	if(substatus != "")
		status += ": " + substatus;

	interactive = options.interactive? "On":"Off";

	str = string_printf(
	        "%s"
	        "        Time: %.2f"
	        "        Latency: %.4f"
	        "        Sample: %d"
	        "        Average: %.4f"
	        "        Interactive: %s",
	        status.c_str(), total_time, latency, sample, sample_time, interactive.c_str());

	view_display_info(str.c_str());

	if(options.show_help)
		view_display_help();
}

static void display()
{
	static DeviceDrawParams draw_params = DeviceDrawParams();

	options.session->draw(session_buffer_params(), draw_params);

	display_info(options.session->progress);
}

static void motion(int x, int y, int button)
{
	if(options.interactive) {
		Transform matrix = options.session->scene->camera->matrix;

		/* Translate */
		if(button == 0) {
			float3 translate = make_float3(x * 0.01f, -(y * 0.01f), 0.0f);
			matrix = matrix * transform_translate(translate);
		}

		/* Rotate */
		else if(button == 2) {
			float4 r1 = make_float4((float)x * 0.1f, 0.0f, 1.0f, 0.0f);
			matrix = matrix * transform_rotate(DEG2RADF(r1.x), make_float3(r1.y, r1.z, r1.w));

			float4 r2 = make_float4(y * 0.1f, 1.0f, 0.0f, 0.0f);
			matrix = matrix * transform_rotate(DEG2RADF(r2.x), make_float3(r2.y, r2.z, r2.w));
		}

		/* Update and Reset */
		options.session->scene->camera->matrix = matrix;
		options.session->scene->camera->need_update = true;
		options.session->scene->camera->need_device_update = true;

		options.session->reset(session_buffer_params(), options.session_params.samples);
	}
}

static void resize(int width, int height)
{
	options.width = width;
	options.height = height;

	if(options.session) {
		/* Update camera */
		options.session->scene->camera->width = width;
		options.session->scene->camera->height = height;
		options.session->scene->camera->compute_auto_viewplane();
		options.session->scene->camera->need_update = true;
		options.session->scene->camera->need_device_update = true;

		options.session->reset(session_buffer_params(), options.session_params.samples);
	}
}

static void keyboard(unsigned char key)
{
	/* Toggle help */
	if(key == 'h')
		options.show_help = !(options.show_help);

	/* Reset */
	else if(key == 'r')
		options.session->reset(session_buffer_params(), options.session_params.samples);

	/* Cancel */
	else if(key == 27) // escape
		options.session->progress.set_cancel("Canceled");

	/* Pause */
	else if(key == 'p') {
		options.pause = !options.pause;
		options.session->set_pause(options.pause);
	}

	/* Interactive Mode */
	else if(key == 'i')
		options.interactive = !(options.interactive);

	else if(options.interactive && (key == 'w' || key == 'a' || key == 's' || key == 'd')) {
		Transform matrix = options.session->scene->camera->matrix;
		float3 translate;

		if(key == 'w')
			translate = make_float3(0.0f, 0.0f, 0.1f);
		else if(key == 's')
			translate = make_float3(0.0f, 0.0f, -0.1f);
		else if(key == 'a')
			translate = make_float3(-0.1f, 0.0f, 0.0f);
		else if(key == 'd')
			translate = make_float3(0.1f, 0.0f, 0.0f);

		matrix = matrix * transform_translate(translate);

		/* Update and Reset */
		options.session->scene->camera->matrix = matrix;
		options.session->scene->camera->need_update = true;
		options.session->scene->camera->need_device_update = true;

		options.session->reset(session_buffer_params(), options.session_params.samples);
	}
}
#endif

static int files_parse(int argc, const char *argv[])
{
	if(argc > 0)
		options.filepath = argv[0];

	return 0;
}

static void options_parse(int argc, const char **argv)
{
	options.width = 0;
	options.height = 0;
	options.filepath = "";
	options.session = NULL;
	options.quiet = false;

	/* device names */
	string device_names = "";
	string devicename = "cpu";
	bool list = false;

	vector<DeviceType>& types = Device::available_types();

	foreach(DeviceType type, types) {
		if(device_names != "")
			device_names += ", ";

		device_names += Device::string_from_type(type);
	}

	/* shading system */
	string ssname = "svm";

	/* parse options */
	ArgParse ap;
	bool help = false;

	ap.options ("Usage: cycles [options] file.xml",
		"%*", files_parse, "",
		"--device %s", &devicename, ("Devices to use: " + device_names).c_str(),
#ifdef WITH_OSL
		"--shadingsys %s", &ssname, "Shading system to use: svm, osl",
#endif
		"--background", &options.session_params.background, "Render in background, without user interface",
		"--quiet", &options.quiet, "In background mode, don't print progress messages",
		"--samples %d", &options.session_params.samples, "Number of samples to render",
		"--output %s", &options.session_params.output_path, "File path to write output image",
		"--threads %d", &options.session_params.threads, "CPU Rendering Threads",
		"--width  %d", &options.width, "Window width in pixel",
		"--height %d", &options.height, "Window height in pixel",
		"--list-devices", &list, "List information about all available devices",
		"--help", &help, "Print help message",
		NULL);

	if(ap.parse(argc, argv) < 0) {
		fprintf(stderr, "%s\n", ap.geterror().c_str());
		ap.usage();
		exit(EXIT_FAILURE);
	}
	else if(list) {
		vector<DeviceInfo>& devices = Device::available_devices();
		printf("Devices:\n");

		foreach(DeviceInfo& info, devices) {
			printf("    %s%s\n",
				info.description.c_str(),
				(info.display_device)? " (display)": "");
		}

		exit(EXIT_SUCCESS);
	}
	else if(help || options.filepath == "") {
		ap.usage();
		exit(EXIT_SUCCESS);
	}

	if(ssname == "osl")
		options.scene_params.shadingsystem = SHADINGSYSTEM_OSL;
	else if(ssname == "svm")
		options.scene_params.shadingsystem = SHADINGSYSTEM_SVM;

#ifndef WITH_CYCLES_STANDALONE_GUI
	options.session_params.background = true;
#endif

	/* Use progressive rendering */
	options.session_params.progressive = true;

	/* find matching device */
	DeviceType device_type = Device::type_from_string(devicename.c_str());
	vector<DeviceInfo>& devices = Device::available_devices();
	DeviceInfo device_info;
	bool device_available = false;

	foreach(DeviceInfo& device, devices) {
		if(device_type == device.type) {
			options.session_params.device = device;
			device_available = true;
			break;
		}
	}

	/* handle invalid configurations */
	if(options.session_params.device.type == DEVICE_NONE || !device_available) {
		fprintf(stderr, "Unknown device: %s\n", devicename.c_str());
		exit(EXIT_FAILURE);
	}
#ifdef WITH_OSL
	else if(!(ssname == "osl" || ssname == "svm")) {
		fprintf(stderr, "Unknown shading system: %s\n", ssname.c_str());
		exit(EXIT_FAILURE);
	}
	else if(options.scene_params.shadingsystem == SHADINGSYSTEM_OSL && options.session_params.device.type != DEVICE_CPU) {
		fprintf(stderr, "OSL shading system only works with CPU device\n");
		exit(EXIT_FAILURE);
	}
#endif
	else if(options.session_params.samples < 0) {
		fprintf(stderr, "Invalid number of samples: %d\n", options.session_params.samples);
		exit(EXIT_FAILURE);
	}
	else if(options.filepath == "") {
		fprintf(stderr, "No file path specified\n");
		exit(EXIT_FAILURE);
	}

	/* For smoother Viewport */
	options.session_params.start_resolution = 64;

	/* load scene */
	scene_init();
}

CCL_NAMESPACE_END

using namespace ccl;

int main(int argc, const char **argv)
{
	path_init();
	options_parse(argc, argv);

#ifdef WITH_CYCLES_STANDALONE_GUI
	if(options.session_params.background) {
#endif
		session_init();
		options.session->wait();
		session_exit();
#ifdef WITH_CYCLES_STANDALONE_GUI
	}
	else {
		string title = "Cycles: " + path_filename(options.filepath);

		/* init/exit are callback so they run while GL is initialized */
		view_main_loop(title.c_str(), options.width, options.height,
			session_init, session_exit, resize, display, keyboard, motion);
	}
#endif

	return 0;
}

<|endoftext|>


<commit_before>//
// Created by admin on 2016/12/9.
//
#include <cstdio>
#include <cmath>

#include "CrystalLib.h"
#include "../src/DBSCAN.h"

using namespace Crystal;

struct Vec3f {
    union
    {
        struct {
            float x;
            float y;
            float z;
        };
        float e[3];
    };
};

int main(int argc, char** argv) {

    auto EuclidDistanceFunc = [](const Vec3f& v1, const Vec3f& v2)->float { return std::sqrt((v1.x-v2.x)*(v1.x-v2.x) + (v1.y-v2.y)*(v1.y-v2.y) + (v1.z-v2.z)*(v1.z-v2.z)); };

    printf("%f\n", EuclidDistanceFunc(Vec3f{ 1.f,0.f,0.f }, Vec3f{ 2.0f,0.f,0.f }));

    auto dbscan = DBSCAN<Vec3f, float>();
    dbscan.Run(vimg, 10.f, 20, EuclidDistanceFunc);
    printf("Hello Crystal\n");
    getchar();
    return 0;
}
<commit_msg>add opencv image debug<commit_after>//
// Created by admin on 2016/12/9.
//
#include <cstdio>
#include <cmath>
#include <random>

#include "CrystalLib.h"
#include "../src/DBSCAN.h"
#include <opencv2/opencv.hpp>

using namespace Crystal;

struct Vec3f {
    union
    {
        struct {
            float x;
            float y;
            float z;
        };
        float e[3];
    };
};

std::vector<Vec3f> GenerateRandomDisturbCluster(const Vec3f& center, float rad, int num) {
    std::random_device rd;
    std::mt19937 gen(rd());
    std::uniform_real_distribution<> dis(-rad, rad);
    std::vector<Vec3f> rc;
    for (int i = 0; i < num; ++i) {
        rc.push_back(Vec3f{ center.x + (float)dis(gen), center.y + (float)dis(gen), center.z + (float)dis(gen)});
    }
    return rc;
}

int main(int argc, char** argv) {

    cv::Mat atom_image = cv::Mat( 1000, 1000, CV_8UC3, cv::Scalar(255,255,255) );

    std::vector<Vec3f> pts = GenerateRandomDisturbCluster(Vec3f{ 5.f,5.f,5.f }, 1.f, 200);

    std::vector<Vec3f> pts5 = GenerateRandomDisturbCluster(Vec3f{ 8.2f, 7.2f ,5.f }, 0.3f, 100);

    std::vector<Vec3f> pts4 = GenerateRandomDisturbCluster(Vec3f{ 5.9f,5.9f,5.9f }, 0.7f, 200);

    std::vector<Vec3f> pts3 = GenerateRandomDisturbCluster(Vec3f{ 2.f,1.f,1.f }, 0.3f, 200);

    std::vector<Vec3f> pts2 = GenerateRandomDisturbCluster(Vec3f{ 5.f,5.f,5.f }, 5.f, 200);

    pts.insert(pts.end(), pts2.begin(), pts2.end());
    pts.insert(pts.end(), pts3.begin(), pts3.end());
    pts.insert(pts.end(), pts4.begin(), pts4.end());
    pts.insert(pts.end(), pts5.begin(), pts5.end());

    auto EuclidDistanceFunc = [](const Vec3f& v1, const Vec3f& v2)->float { return std::sqrt((v1.x-v2.x)*(v1.x-v2.x) + (v1.y-v2.y)*(v1.y-v2.y) + (v1.z-v2.z)*(v1.z-v2.z)); };

    printf("%f\n", EuclidDistanceFunc(Vec3f{ 1.f,0.f,0.f }, Vec3f{ 2.0f,0.f,0.f }));

    auto dbscan = DBSCAN<Vec3f, float>();
    dbscan.Run(pts, 0.4f, 4, EuclidDistanceFunc);

    float scalar = 100.f;

    for (int ic = 0; ic < dbscan.Clusters.size(); ++ic) {
        std::random_device rd;
        std::mt19937 gen(rd());
        std::uniform_real_distribution<> dis(0, 255);
        Vec3f clustercolor = Vec3f{ (float)dis(gen), (float)dis(gen), (float)dis(gen) };
        for (int ip = 0; ip < dbscan.Clusters[ic].size(); ++ip) {
            int pid = dbscan.Clusters[ic][ip];
            cv::circle(
                atom_image
                , cv::Point(scalar * pts[pid].x, scalar * pts[pid].y)
                , 4
                , cv::Scalar(clustercolor.x, clustercolor.y, clustercolor.y)\
                , -1
            );
        }
    }

    for (int ic = 0; ic < dbscan.Noise.size(); ++ic) {
        int pid = dbscan.Noise[ic];
        cv::circle(
            atom_image
            , cv::Point(scalar * pts[pid].x, scalar * pts[pid].y)
            , 4
            , cv::Scalar(0, 0, 0)
            , -1
        );
    }
    printf("Hello Crystal\n");
    getchar();
    return 0;
}
<|endoftext|>


<commit_before>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <arrayfire.h>
#include <iostream>
#include <cstdio>

using namespace af;
using namespace std;

static const int width = 512, height = 512;
static const int pixels_per_unit = 20;

af::array p_x;
af::array p_y;
af::array vels_x;
af::array vels_y;
af::array forces_x;
af::array forces_y;

void simulate(float dt){
    p_x += vels_x * pixels_per_unit * dt;
    p_y += vels_y * pixels_per_unit * dt;

    //calculate distance to center
    af::array diff_x = p_x - width/2;
    af::array diff_y = p_y - height/2;
    af::array dist = sqrt( diff_x*diff_x + diff_y*diff_y );

    //calculate normalised force vectors
    forces_x = -1 * diff_x / dist;
    forces_y = -1 * diff_y / dist;
    //update force scaled to time and magnitude constant
    forces_x *= pixels_per_unit * dt;
    forces_y *= pixels_per_unit * dt;

    //dampening
    vels_x *= 1 - (0.005*dt);
    vels_y *= 1 - (0.005*dt);

    //update velocities from forces
    vels_x += forces_x;
    vels_y += forces_y;

}

void collisions(){
    //clamp particles inside screen border
    af::array projected_px = min(width, max(0, p_x));
    af::array projected_py = min(height - 1, max(0, p_y));

    //calculate distance to center
    af::array diff_x = projected_px - width/2;
    af::array diff_y = projected_py - height/2;
    af::array dist = sqrt( diff_x*diff_x + diff_y*diff_y );

    //collide with center sphere
    const int radius = 50;
    const float elastic_constant = 0.91f;
    if(sum<int>(dist<radius) > 0) {
        vels_x(dist<radius) = -elastic_constant * vels_x(dist<radius);
        vels_y(dist<radius) = -elastic_constant * vels_y(dist<radius);

        //normalize diff vector
        diff_x /= dist;
        diff_y /= dist;
        //place all particle colliding with sphere on surface
        p_x(dist<radius) = width/2 + diff_x(dist<radius) * radius;
        p_y(dist<radius) = height/2 +  diff_y(dist<radius) * radius;
    }
}

int main(int argc, char *argv[])
{
    try {
        const static int total_particles = 1000;
        static const int reset = 500;

        af::info();

        af::Window myWindow(width, height, "Gravity Simulation using ArrayFire");

        int frame_count = 0;

        // Initialize the kernel array just once
        const af::array draw_kernel = gaussianKernel(3, 3);

        // Generate a random starting state
        p_x = af::randu(total_particles) * width;
        p_y = af::randu(total_particles) * height;

        vels_x = af::randn(total_particles);
        vels_y = af::randn(total_particles);

        forces_x = af::randn(total_particles);
        forces_y = af::randn(total_particles);

        af::array image = af::constant(0, width, height);
        af::array ids(total_particles, u32);

        af::timer timer = af::timer::start();
        while(!myWindow.close()) {
            float dt = af::timer::stop(timer);
            timer = af::timer::start();

            ids = (p_x.as(u32) * height) + p_y.as(u32);
            image(ids) += 255;
            image = convolve2(image, draw_kernel);
            myWindow.image(image);
            image = af::constant(0, image.dims());
            frame_count++;

            // Generate a random starting state
            if(frame_count % reset == 0) {
                p_x = af::randu(total_particles) * width;
                p_y = af::randu(total_particles) * height;

                vels_x = af::randn(total_particles);
                vels_y = af::randn(total_particles);
            }

            //check for collisions and adjust velocities accordingly
            collisions();

            //run force simulation and update particles
            simulate(dt);

        }
    } catch (af::exception& e) {
        fprintf(stderr, "%s\n", e.what());
        throw;
    }

    #ifdef WIN32 // pause in Windows
    if (!(argc == 2 && argv[1][0] == '-')) {
        printf("hit [enter]...");
        fflush(stdout);
        getchar();
    }
    #endif
    return 0;
}

<commit_msg>remove state globals<commit_after>/*******************************************************
 * Copyright (c) 2014, ArrayFire
 * All rights reserved.
 *
 * This file is distributed under 3-clause BSD license.
 * The complete license agreement can be obtained at:
 * http://arrayfire.com/licenses/BSD-3-Clause
 ********************************************************/

#include <arrayfire.h>
#include <iostream>
#include <cstdio>

using namespace af;
using namespace std;

static const int width = 512, height = 512;
static const int pixels_per_unit = 20;

void simulate(af::array *pos, af::array *vels, af::array *forces, float dt){
    pos[0] += vels[0] * pixels_per_unit * dt;
    pos[1] += vels[1] * pixels_per_unit * dt;

    //calculate distance to center
    af::array diff_x = pos[0] - width/2;
    af::array diff_y = pos[1] - height/2;
    af::array dist = sqrt( diff_x*diff_x + diff_y*diff_y );

    //calculate normalised force vectors
    forces[0] = -1 * diff_x / dist;
    forces[1] = -1 * diff_y / dist;
    //update force scaled to time and magnitude constant
    forces[0] *= pixels_per_unit * dt;
    forces[1] *= pixels_per_unit * dt;

    //dampening
    vels[0] *= 1 - (0.005*dt);
    vels[1] *= 1 - (0.005*dt);

    //update velocities from forces
    vels[0] += forces[0];
    vels[1] += forces[1];

}

void collisions(af::array *pos, af::array *vels){
    //clamp particles inside screen border
    af::array projected_px = min(width, max(0, pos[0]));
    af::array projected_py = min(height - 1, max(0, pos[1]));

    //calculate distance to center
    af::array diff_x = projected_px - width/2;
    af::array diff_y = projected_py - height/2;
    af::array dist = sqrt( diff_x*diff_x + diff_y*diff_y );

    //collide with center sphere
    const int radius = 50;
    const float elastic_constant = 0.91f;
    if(sum<int>(dist<radius) > 0) {
        vels[0](dist<radius) = -elastic_constant * vels[0](dist<radius);
        vels[1](dist<radius) = -elastic_constant * vels[1](dist<radius);

        //normalize diff vector
        diff_x /= dist;
        diff_y /= dist;
        //place all particle colliding with sphere on surface
        pos[0](dist<radius) = width/2 + diff_x(dist<radius) * radius;
        pos[1](dist<radius) = height/2 +  diff_y(dist<radius) * radius;
    }
}

int main(int argc, char *argv[])
{
    try {
        const static int total_particles = 1000;
        static const int reset = 500;

        af::info();

        af::Window myWindow(width, height, "Gravity Simulation using ArrayFire");

        int frame_count = 0;

        // Initialize the kernel array just once
        const af::array draw_kernel = gaussianKernel(3, 3);

        af::array pos[2];
        af::array vels[2];
        af::array forces[2];

        // Generate a random starting state
        pos[0] = af::randu(total_particles) * width;
        pos[1] = af::randu(total_particles) * height;

        vels[0] = af::randn(total_particles);
        vels[1] = af::randn(total_particles);

        forces[0] = af::randn(total_particles);
        forces[1] = af::randn(total_particles);

        af::array image = af::constant(0, width, height);
        af::array ids(total_particles, u32);

        af::timer timer = af::timer::start();
        while(!myWindow.close()) {
            float dt = af::timer::stop(timer);
            timer = af::timer::start();

            ids = (pos[0].as(u32) * height) + pos[1].as(u32);
            image(ids) += 255;
            image = convolve2(image, draw_kernel);
            myWindow.image(image);
            image = af::constant(0, image.dims());
            frame_count++;

            // Generate a random starting state
            if(frame_count % reset == 0) {
                pos[0] = af::randu(total_particles) * width;
                pos[1] = af::randu(total_particles) * height;

                vels[0] = af::randn(total_particles);
                vels[1] = af::randn(total_particles);
            }

            //check for collisions and adjust positions/velocities accordingly
            collisions(pos, vels);

            //run force simulation and update particles
            simulate(pos, vels, forces, dt);

        }
    } catch (af::exception& e) {
        fprintf(stderr, "%s\n", e.what());
        throw;
    }

    #ifdef WIN32 // pause in Windows
    if (!(argc == 2 && argv[1][0] == '-')) {
        printf("hit [enter]...");
        fflush(stdout);
        getchar();
    }
    #endif
    return 0;
}

<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: timestamp.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 04:25:51 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef CONFIGMGR_TIMESTAMP_HXX
#define CONFIGMGR_TIMESTAMP_HXX

#include <vos/timer.hxx>

namespace configmgr
{
////////////////////////////////////////////////////////////////////////////////

    class TimeInterval
    {
        vos::TTimeValue m_aTime;
    public:
        TimeInterval() : m_aTime()
        {}

        explicit
        TimeInterval(sal_uInt32 nSeconds) : m_aTime(nSeconds,0)
        {}

        explicit
        TimeInterval(const TimeValue& rTimeValue) : m_aTime(rTimeValue)
        {}

        sal_Bool isEmpty() const { return m_aTime.isEmpty(); }

        vos::TTimeValue const& getTimeValue() const { return m_aTime; }
    };
////////////////////////////////////////////////////////////////////////////////

    class TimeStamp
    {
        vos::TTimeValue m_aTime;
    public:
        TimeStamp() : m_aTime()
        {}

        explicit
        TimeStamp(TimeValue const& rTimeValue) : m_aTime(rTimeValue)
        {}

        TimeStamp& operator += (TimeInterval const& aInterval)
        { m_aTime.addTime(aInterval.getTimeValue()); return *this; }

        vos::TTimeValue const& getTimeValue() const { return m_aTime; }

        sal_Bool isNever() const;

        static TimeStamp getCurrentTime();
        static TimeStamp never(); // is later than (>) any other TimeStamp
        static TimeStamp always(); // is before (<) any other TimeStamp
    };

    inline
    TimeStamp operator +(TimeStamp const& aTime, TimeInterval const& aInterval)
    {
        TimeStamp aResult(aTime);
        aResult += aInterval;
        return aResult;
    }
    inline
    TimeStamp operator +(TimeInterval const& aInterval, TimeStamp const& aTime)
    {
        TimeStamp aResult(aTime);
        aResult += aInterval;
        return aResult;
    }
////////////////////////////////////////////////////////////////////////////////
    inline sal_Bool operator ==(TimeStamp const& lhs, TimeStamp const& rhs)
    { return lhs.getTimeValue() == rhs.getTimeValue(); }
    inline sal_Bool operator < (TimeStamp const& lhs, TimeStamp const& rhs)
    { return lhs.getTimeValue() < rhs.getTimeValue(); }
    inline sal_Bool operator > (TimeStamp const& lhs, TimeStamp const& rhs)
    { return lhs.getTimeValue() > rhs.getTimeValue(); }

    inline sal_Bool operator !=(TimeStamp const& lhs, TimeStamp const& rhs)
    { return !(lhs == rhs); }
    inline sal_Bool operator <=(TimeStamp const& lhs, TimeStamp const& rhs)
    { return !(rhs < lhs); }
    inline sal_Bool operator >=(TimeStamp const& lhs, TimeStamp const& rhs)
    { return !(lhs < rhs); }

    inline sal_Bool TimeStamp::isNever() const
    {
        return never() <= *this;
    }
////////////////////////////////////////////////////////////////////////////////

    struct ltTimeStamp //: std::binary_function<TimeStamp,TimeStamp,bool>
    {
        bool operator()(TimeStamp const& lhs, TimeStamp const& rhs) const
        { return !!(lhs < rhs); }
    };

////////////////////////////////////////////////////////////////////////////////
} // namespace configmgr

#endif // CONFIGMGR_TIMESTAMP_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.4.130); FILE MERGED 2008/03/31 12:22:54 rt 1.4.130.1: #i87441# Change license header to LPGL v3.<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: timestamp.hxx,v $
 * $Revision: 1.5 $
 *
 * 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.
 *
 ************************************************************************/

#ifndef CONFIGMGR_TIMESTAMP_HXX
#define CONFIGMGR_TIMESTAMP_HXX

#include <vos/timer.hxx>

namespace configmgr
{
////////////////////////////////////////////////////////////////////////////////

    class TimeInterval
    {
        vos::TTimeValue m_aTime;
    public:
        TimeInterval() : m_aTime()
        {}

        explicit
        TimeInterval(sal_uInt32 nSeconds) : m_aTime(nSeconds,0)
        {}

        explicit
        TimeInterval(const TimeValue& rTimeValue) : m_aTime(rTimeValue)
        {}

        sal_Bool isEmpty() const { return m_aTime.isEmpty(); }

        vos::TTimeValue const& getTimeValue() const { return m_aTime; }
    };
////////////////////////////////////////////////////////////////////////////////

    class TimeStamp
    {
        vos::TTimeValue m_aTime;
    public:
        TimeStamp() : m_aTime()
        {}

        explicit
        TimeStamp(TimeValue const& rTimeValue) : m_aTime(rTimeValue)
        {}

        TimeStamp& operator += (TimeInterval const& aInterval)
        { m_aTime.addTime(aInterval.getTimeValue()); return *this; }

        vos::TTimeValue const& getTimeValue() const { return m_aTime; }

        sal_Bool isNever() const;

        static TimeStamp getCurrentTime();
        static TimeStamp never(); // is later than (>) any other TimeStamp
        static TimeStamp always(); // is before (<) any other TimeStamp
    };

    inline
    TimeStamp operator +(TimeStamp const& aTime, TimeInterval const& aInterval)
    {
        TimeStamp aResult(aTime);
        aResult += aInterval;
        return aResult;
    }
    inline
    TimeStamp operator +(TimeInterval const& aInterval, TimeStamp const& aTime)
    {
        TimeStamp aResult(aTime);
        aResult += aInterval;
        return aResult;
    }
////////////////////////////////////////////////////////////////////////////////
    inline sal_Bool operator ==(TimeStamp const& lhs, TimeStamp const& rhs)
    { return lhs.getTimeValue() == rhs.getTimeValue(); }
    inline sal_Bool operator < (TimeStamp const& lhs, TimeStamp const& rhs)
    { return lhs.getTimeValue() < rhs.getTimeValue(); }
    inline sal_Bool operator > (TimeStamp const& lhs, TimeStamp const& rhs)
    { return lhs.getTimeValue() > rhs.getTimeValue(); }

    inline sal_Bool operator !=(TimeStamp const& lhs, TimeStamp const& rhs)
    { return !(lhs == rhs); }
    inline sal_Bool operator <=(TimeStamp const& lhs, TimeStamp const& rhs)
    { return !(rhs < lhs); }
    inline sal_Bool operator >=(TimeStamp const& lhs, TimeStamp const& rhs)
    { return !(lhs < rhs); }

    inline sal_Bool TimeStamp::isNever() const
    {
        return never() <= *this;
    }
////////////////////////////////////////////////////////////////////////////////

    struct ltTimeStamp //: std::binary_function<TimeStamp,TimeStamp,bool>
    {
        bool operator()(TimeStamp const& lhs, TimeStamp const& rhs) const
        { return !!(lhs < rhs); }
    };

////////////////////////////////////////////////////////////////////////////////
} // namespace configmgr

#endif // CONFIGMGR_TIMESTAMP_HXX

<|endoftext|>


<commit_before>// Copyright (c) 2014-2018 Sebastien Rombauts (sebastien.rombauts@gmail.com)
//
// Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
// or copy at http://opensource.org/licenses/MIT)

#include "GitSourceControlState.h"

#define LOCTEXT_NAMESPACE "GitSourceControl.State"

int32 FGitSourceControlState::GetHistorySize() const
{
	return History.Num();
}

TSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::GetHistoryItem( int32 HistoryIndex ) const
{
	check(History.IsValidIndex(HistoryIndex));
	return History[HistoryIndex];
}

TSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::FindHistoryRevision( int32 RevisionNumber ) const
{
	for(const auto& Revision : History)
	{
		if(Revision->GetRevisionNumber() == RevisionNumber)
		{
			return Revision;
		}
	}

	return nullptr;
}

TSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::FindHistoryRevision(const FString& InRevision) const
{
	for(const auto& Revision : History)
	{
		if(Revision->GetRevision() == InRevision)
		{
			return Revision;
		}
	}

	return nullptr;
}

TSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::GetBaseRevForMerge() const
{
	for(const auto& Revision : History)
	{
		// look for the the SHA1 id of the file, not the commit id (revision)
		if(Revision->FileHash == PendingMergeBaseFileHash)
		{
			return Revision;
		}
	}

	return nullptr;
}

// @todo add Slate icons for git specific states (NotAtHead vs Conflicted...)
FName FGitSourceControlState::GetIconName() const
{
	if(LockState == ELockState::Locked)
	{
		return FName("Subversion.CheckedOut");
	}
	else if(LockState == ELockState::LockedOther)
	{
		return FName("Subversion.CheckedOutByOtherUser");
	}
	else if (!IsCurrent())
	{
		return FName("Subversion.NotAtHeadRevision");
	}

	switch(WorkingCopyState)
	{
	case EWorkingCopyState::Modified:
		if(bUsingGitLfsLocking)
		{
			return FName("Subversion.NotInDepot");
		}
		else
		{
			return FName("Subversion.CheckedOut");
		}
	case EWorkingCopyState::Added:
		return FName("Subversion.OpenForAdd");
	case EWorkingCopyState::Renamed:
	case EWorkingCopyState::Copied:
		return FName("Subversion.Branched");
	case EWorkingCopyState::Deleted: // Deleted & Missing files does not show in Content Browser
	case EWorkingCopyState::Missing:
		return FName("Subversion.MarkedForDelete");
	case EWorkingCopyState::Conflicted:
		return FName("Subversion.NotAtHeadRevision");
	case EWorkingCopyState::NotControlled:
		return FName("Subversion.NotInDepot");
	case EWorkingCopyState::Unknown:
	case EWorkingCopyState::Unchanged: // Unchanged is the same as "Pristine" (not checked out) for Perforce, ie no icon
	case EWorkingCopyState::Ignored:
	default:
		return NAME_None;
	}

	return NAME_None;
}

FName FGitSourceControlState::GetSmallIconName() const
{
	if(LockState == ELockState::Locked)
	{
		return FName("Subversion.CheckedOut_Small");
	}
	else if(LockState == ELockState::LockedOther)
	{
		return FName("Subversion.CheckedOutByOtherUser_Small");
	}
	else if (!IsCurrent())
	{
		return FName("Subversion.NotAtHeadRevision_Small");
	}

	switch(WorkingCopyState)
	{
	case EWorkingCopyState::Modified:
		if(bUsingGitLfsLocking)
		{
			return FName("Subversion.NotInDepot_Small");
		}
		else
		{
			return FName("Subversion.CheckedOut_Small");
		}
	case EWorkingCopyState::Added:
		return FName("Subversion.OpenForAdd_Small");
	case EWorkingCopyState::Renamed:
	case EWorkingCopyState::Copied:
		return FName("Subversion.Branched_Small");
	case EWorkingCopyState::Deleted: // Deleted & Missing files can appear in the Submit to Source Control window
	case EWorkingCopyState::Missing:
		return FName("Subversion.MarkedForDelete_Small");
	case EWorkingCopyState::Conflicted:
		return FName("Subversion.NotAtHeadRevision_Small");
	case EWorkingCopyState::NotControlled:
		return FName("Subversion.NotInDepot_Small");
	case EWorkingCopyState::Unknown:
	case EWorkingCopyState::Unchanged: // Unchanged is the same as "Pristine" (not checked out) for Perforce, ie no icon
	case EWorkingCopyState::Ignored:
	default:
		return NAME_None;
	}

	return NAME_None;
}

FText FGitSourceControlState::GetDisplayName() const
{
	if(LockState == ELockState::Locked)
	{
		return LOCTEXT("Locked", "Locked For Editing");
	}
	else if(LockState == ELockState::LockedOther)
	{
		return FText::Format( LOCTEXT("LockedOther", "Locked by "), FText::FromString(LockUser) );
	}
	else if (!IsCurrent())
	{
		return LOCTEXT("NotCurrent", "Not current");
	}

	switch(WorkingCopyState)
	{
	case EWorkingCopyState::Unknown:
		return LOCTEXT("Unknown", "Unknown");
	case EWorkingCopyState::Unchanged:
		return LOCTEXT("Unchanged", "Unchanged");
	case EWorkingCopyState::Added:
		return LOCTEXT("Added", "Added");
	case EWorkingCopyState::Deleted:
		return LOCTEXT("Deleted", "Deleted");
	case EWorkingCopyState::Modified:
		return LOCTEXT("Modified", "Modified");
	case EWorkingCopyState::Renamed:
		return LOCTEXT("Renamed", "Renamed");
	case EWorkingCopyState::Copied:
		return LOCTEXT("Copied", "Copied");
	case EWorkingCopyState::Conflicted:
		return LOCTEXT("ContentsConflict", "Contents Conflict");
	case EWorkingCopyState::Ignored:
		return LOCTEXT("Ignored", "Ignored");
	case EWorkingCopyState::NotControlled:
		return LOCTEXT("NotControlled", "Not Under Source Control");
	case EWorkingCopyState::Missing:
		return LOCTEXT("Missing", "Missing");
	}

	return FText();
}

FText FGitSourceControlState::GetDisplayTooltip() const
{
	if(LockState == ELockState::Locked)
	{
		return LOCTEXT("Locked_Tooltip", "Locked for editing by current user");
	}
	else if(LockState == ELockState::LockedOther)
	{
		return FText::Format( LOCTEXT("LockedOther_Tooltip", "Locked for editing by: {0}"), FText::FromString(LockUser) );
	}
	else if (!IsCurrent())
	{
		return LOCTEXT("NotCurrent_Tooltip", "The file(s) are not at the head revision");
	}

	switch(WorkingCopyState)
	{
	case EWorkingCopyState::Unknown:
		return LOCTEXT("Unknown_Tooltip", "Unknown source control state");
	case EWorkingCopyState::Unchanged:
		return LOCTEXT("Pristine_Tooltip", "There are no modifications");
	case EWorkingCopyState::Added:
		return LOCTEXT("Added_Tooltip", "Item is scheduled for addition");
	case EWorkingCopyState::Deleted:
		return LOCTEXT("Deleted_Tooltip", "Item is scheduled for deletion");
	case EWorkingCopyState::Modified:
		return LOCTEXT("Modified_Tooltip", "Item has been modified");
	case EWorkingCopyState::Renamed:
		return LOCTEXT("Renamed_Tooltip", "Item has been renamed");
	case EWorkingCopyState::Copied:
		return LOCTEXT("Copied_Tooltip", "Item has been copied");
	case EWorkingCopyState::Conflicted:
		return LOCTEXT("ContentsConflict_Tooltip", "The contents of the item conflict with updates received from the repository.");
	case EWorkingCopyState::Ignored:
		return LOCTEXT("Ignored_Tooltip", "Item is being ignored.");
	case EWorkingCopyState::NotControlled:
		return LOCTEXT("NotControlled_Tooltip", "Item is not under version control.");
	case EWorkingCopyState::Missing:
		return LOCTEXT("Missing_Tooltip", "Item is missing (e.g., you moved or deleted it without using Git). This also indicates that a directory is incomplete (a checkout or update was interrupted).");
	}

	return FText();
}

const FString& FGitSourceControlState::GetFilename() const
{
	return LocalFilename;
}

const FDateTime& FGitSourceControlState::GetTimeStamp() const
{
	return TimeStamp;
}

// Deleted and Missing assets cannot appear in the Content Browser, but the do in the Submit files to Source Control window!
bool FGitSourceControlState::CanCheckIn() const
{
	if(bUsingGitLfsLocking)
	{
		return ( ( (LockState == ELockState::Locked) && !IsConflicted() ) || (WorkingCopyState == EWorkingCopyState::Added) ) && IsCurrent();
	}
	else
	{
		return (WorkingCopyState == EWorkingCopyState::Added
			|| WorkingCopyState == EWorkingCopyState::Deleted
			|| WorkingCopyState == EWorkingCopyState::Missing
			|| WorkingCopyState == EWorkingCopyState::Modified
			|| WorkingCopyState == EWorkingCopyState::Renamed) && IsCurrent();
	}
}

bool FGitSourceControlState::CanCheckout() const
{
	if(bUsingGitLfsLocking)
	{
		// We don't want to allow checkout if the file is out-of-date, as modifying an out-of-date binary file will most likely result in a merge conflict
		return (WorkingCopyState == EWorkingCopyState::Unchanged || WorkingCopyState == EWorkingCopyState::Modified) && LockState == ELockState::NotLocked && IsCurrent();
	}
	else
	{
		return false; // With Git all tracked files in the working copy are always already checked-out (as opposed to Perforce)
	}
}

bool FGitSourceControlState::IsCheckedOut() const
{
	if (bUsingGitLfsLocking)
	{
		return LockState == ELockState::Locked;
	}
	else
	{
		return IsSourceControlled(); // With Git all tracked files in the working copy are always checked-out (as opposed to Perforce)
	}
}

bool FGitSourceControlState::IsCheckedOutOther(FString* Who) const
{
	if (Who != NULL)
	{
		*Who = LockUser;
	}
	return LockState == ELockState::LockedOther;
}

bool FGitSourceControlState::IsCurrent() const
{
	return !bNewerVersionOnServer;
}

bool FGitSourceControlState::IsSourceControlled() const
{
	return WorkingCopyState != EWorkingCopyState::NotControlled && WorkingCopyState != EWorkingCopyState::Ignored && WorkingCopyState != EWorkingCopyState::Unknown;
}

bool FGitSourceControlState::IsAdded() const
{
	return WorkingCopyState == EWorkingCopyState::Added;
}

bool FGitSourceControlState::IsDeleted() const
{
	return WorkingCopyState == EWorkingCopyState::Deleted || WorkingCopyState == EWorkingCopyState::Missing;
}

bool FGitSourceControlState::IsIgnored() const
{
	return WorkingCopyState == EWorkingCopyState::Ignored;
}

bool FGitSourceControlState::CanEdit() const
{
	return IsCurrent(); // With Git all files in the working copy are always editable (as opposed to Perforce)
}

bool FGitSourceControlState::CanDelete() const
{
	return !IsCheckedOutOther() && IsSourceControlled() && IsCurrent();
}

bool FGitSourceControlState::IsUnknown() const
{
	return WorkingCopyState == EWorkingCopyState::Unknown;
}

bool FGitSourceControlState::IsModified() const
{
	// Warning: for Perforce, a checked-out file is locked for modification (whereas with Git all tracked files are checked-out),
	// so for a clean "check-in" (commit) checked-out files unmodified should be removed from the changeset (the index)
	// http://stackoverflow.com/questions/12357971/what-does-revert-unchanged-files-mean-in-perforce
	//
	// Thus, before check-in UE4 Editor call RevertUnchangedFiles() in PromptForCheckin() and CheckinFiles().
	//
	// So here we must take care to enumerate all states that need to be commited,
	// all other will be discarded :
	//  - Unknown
	//  - Unchanged
	//  - NotControlled
	//  - Ignored
	return WorkingCopyState == EWorkingCopyState::Added
		|| WorkingCopyState == EWorkingCopyState::Deleted
		|| WorkingCopyState == EWorkingCopyState::Modified
		|| WorkingCopyState == EWorkingCopyState::Renamed
		|| WorkingCopyState == EWorkingCopyState::Copied
		|| WorkingCopyState == EWorkingCopyState::Missing
		|| WorkingCopyState == EWorkingCopyState::Conflicted;
}

bool FGitSourceControlState::CanAdd() const
{
	return WorkingCopyState == EWorkingCopyState::NotControlled;
}

bool FGitSourceControlState::IsConflicted() const
{
	return WorkingCopyState == EWorkingCopyState::Conflicted;
}

bool FGitSourceControlState::CanRevert() const
{
	return CanCheckIn();
}

#undef LOCTEXT_NAMESPACE
<commit_msg>Change conflict state icon to ModifiedOtherBranch to avoid confusion with NotAtHeadRevision state<commit_after>// Copyright (c) 2014-2018 Sebastien Rombauts (sebastien.rombauts@gmail.com)
//
// Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt
// or copy at http://opensource.org/licenses/MIT)

#include "GitSourceControlState.h"

#define LOCTEXT_NAMESPACE "GitSourceControl.State"

int32 FGitSourceControlState::GetHistorySize() const
{
	return History.Num();
}

TSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::GetHistoryItem( int32 HistoryIndex ) const
{
	check(History.IsValidIndex(HistoryIndex));
	return History[HistoryIndex];
}

TSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::FindHistoryRevision( int32 RevisionNumber ) const
{
	for(const auto& Revision : History)
	{
		if(Revision->GetRevisionNumber() == RevisionNumber)
		{
			return Revision;
		}
	}

	return nullptr;
}

TSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::FindHistoryRevision(const FString& InRevision) const
{
	for(const auto& Revision : History)
	{
		if(Revision->GetRevision() == InRevision)
		{
			return Revision;
		}
	}

	return nullptr;
}

TSharedPtr<class ISourceControlRevision, ESPMode::ThreadSafe> FGitSourceControlState::GetBaseRevForMerge() const
{
	for(const auto& Revision : History)
	{
		// look for the the SHA1 id of the file, not the commit id (revision)
		if(Revision->FileHash == PendingMergeBaseFileHash)
		{
			return Revision;
		}
	}

	return nullptr;
}

// @todo add Slate icons for git specific states (NotAtHead vs Conflicted...)
FName FGitSourceControlState::GetIconName() const
{
	if(LockState == ELockState::Locked)
	{
		return FName("Subversion.CheckedOut");
	}
	else if(LockState == ELockState::LockedOther)
	{
		return FName("Subversion.CheckedOutByOtherUser");
	}
	else if (!IsCurrent())
	{
		return FName("Subversion.NotAtHeadRevision");
	}

	switch(WorkingCopyState)
	{
	case EWorkingCopyState::Modified:
		if(bUsingGitLfsLocking)
		{
			return FName("Subversion.NotInDepot");
		}
		else
		{
			return FName("Subversion.CheckedOut");
		}
	case EWorkingCopyState::Added:
		return FName("Subversion.OpenForAdd");
	case EWorkingCopyState::Renamed:
	case EWorkingCopyState::Copied:
		return FName("Subversion.Branched");
	case EWorkingCopyState::Deleted: // Deleted & Missing files does not show in Content Browser
	case EWorkingCopyState::Missing:
		return FName("Subversion.MarkedForDelete");
	case EWorkingCopyState::Conflicted:
		return FName("Subversion.ModifiedOtherBranch");
	case EWorkingCopyState::NotControlled:
		return FName("Subversion.NotInDepot");
	case EWorkingCopyState::Unknown:
	case EWorkingCopyState::Unchanged: // Unchanged is the same as "Pristine" (not checked out) for Perforce, ie no icon
	case EWorkingCopyState::Ignored:
	default:
		return NAME_None;
	}

	return NAME_None;
}

FName FGitSourceControlState::GetSmallIconName() const
{
	if(LockState == ELockState::Locked)
	{
		return FName("Subversion.CheckedOut_Small");
	}
	else if(LockState == ELockState::LockedOther)
	{
		return FName("Subversion.CheckedOutByOtherUser_Small");
	}
	else if (!IsCurrent())
	{
		return FName("Subversion.NotAtHeadRevision_Small");
	}

	switch(WorkingCopyState)
	{
	case EWorkingCopyState::Modified:
		if(bUsingGitLfsLocking)
		{
			return FName("Subversion.NotInDepot_Small");
		}
		else
		{
			return FName("Subversion.CheckedOut_Small");
		}
	case EWorkingCopyState::Added:
		return FName("Subversion.OpenForAdd_Small");
	case EWorkingCopyState::Renamed:
	case EWorkingCopyState::Copied:
		return FName("Subversion.Branched_Small");
	case EWorkingCopyState::Deleted: // Deleted & Missing files can appear in the Submit to Source Control window
	case EWorkingCopyState::Missing:
		return FName("Subversion.MarkedForDelete_Small");
	case EWorkingCopyState::Conflicted:
		return FName("Subversion.ModifiedOtherBranch_Small");
	case EWorkingCopyState::NotControlled:
		return FName("Subversion.NotInDepot_Small");
	case EWorkingCopyState::Unknown:
	case EWorkingCopyState::Unchanged: // Unchanged is the same as "Pristine" (not checked out) for Perforce, ie no icon
	case EWorkingCopyState::Ignored:
	default:
		return NAME_None;
	}

	return NAME_None;
}

FText FGitSourceControlState::GetDisplayName() const
{
	if(LockState == ELockState::Locked)
	{
		return LOCTEXT("Locked", "Locked For Editing");
	}
	else if(LockState == ELockState::LockedOther)
	{
		return FText::Format( LOCTEXT("LockedOther", "Locked by "), FText::FromString(LockUser) );
	}
	else if (!IsCurrent())
	{
		return LOCTEXT("NotCurrent", "Not current");
	}

	switch(WorkingCopyState)
	{
	case EWorkingCopyState::Unknown:
		return LOCTEXT("Unknown", "Unknown");
	case EWorkingCopyState::Unchanged:
		return LOCTEXT("Unchanged", "Unchanged");
	case EWorkingCopyState::Added:
		return LOCTEXT("Added", "Added");
	case EWorkingCopyState::Deleted:
		return LOCTEXT("Deleted", "Deleted");
	case EWorkingCopyState::Modified:
		return LOCTEXT("Modified", "Modified");
	case EWorkingCopyState::Renamed:
		return LOCTEXT("Renamed", "Renamed");
	case EWorkingCopyState::Copied:
		return LOCTEXT("Copied", "Copied");
	case EWorkingCopyState::Conflicted:
		return LOCTEXT("ContentsConflict", "Contents Conflict");
	case EWorkingCopyState::Ignored:
		return LOCTEXT("Ignored", "Ignored");
	case EWorkingCopyState::NotControlled:
		return LOCTEXT("NotControlled", "Not Under Source Control");
	case EWorkingCopyState::Missing:
		return LOCTEXT("Missing", "Missing");
	}

	return FText();
}

FText FGitSourceControlState::GetDisplayTooltip() const
{
	if(LockState == ELockState::Locked)
	{
		return LOCTEXT("Locked_Tooltip", "Locked for editing by current user");
	}
	else if(LockState == ELockState::LockedOther)
	{
		return FText::Format( LOCTEXT("LockedOther_Tooltip", "Locked for editing by: {0}"), FText::FromString(LockUser) );
	}
	else if (!IsCurrent())
	{
		return LOCTEXT("NotCurrent_Tooltip", "The file(s) are not at the head revision");
	}

	switch(WorkingCopyState)
	{
	case EWorkingCopyState::Unknown:
		return LOCTEXT("Unknown_Tooltip", "Unknown source control state");
	case EWorkingCopyState::Unchanged:
		return LOCTEXT("Pristine_Tooltip", "There are no modifications");
	case EWorkingCopyState::Added:
		return LOCTEXT("Added_Tooltip", "Item is scheduled for addition");
	case EWorkingCopyState::Deleted:
		return LOCTEXT("Deleted_Tooltip", "Item is scheduled for deletion");
	case EWorkingCopyState::Modified:
		return LOCTEXT("Modified_Tooltip", "Item has been modified");
	case EWorkingCopyState::Renamed:
		return LOCTEXT("Renamed_Tooltip", "Item has been renamed");
	case EWorkingCopyState::Copied:
		return LOCTEXT("Copied_Tooltip", "Item has been copied");
	case EWorkingCopyState::Conflicted:
		return LOCTEXT("ContentsConflict_Tooltip", "The contents of the item conflict with updates received from the repository.");
	case EWorkingCopyState::Ignored:
		return LOCTEXT("Ignored_Tooltip", "Item is being ignored.");
	case EWorkingCopyState::NotControlled:
		return LOCTEXT("NotControlled_Tooltip", "Item is not under version control.");
	case EWorkingCopyState::Missing:
		return LOCTEXT("Missing_Tooltip", "Item is missing (e.g., you moved or deleted it without using Git). This also indicates that a directory is incomplete (a checkout or update was interrupted).");
	}

	return FText();
}

const FString& FGitSourceControlState::GetFilename() const
{
	return LocalFilename;
}

const FDateTime& FGitSourceControlState::GetTimeStamp() const
{
	return TimeStamp;
}

// Deleted and Missing assets cannot appear in the Content Browser, but the do in the Submit files to Source Control window!
bool FGitSourceControlState::CanCheckIn() const
{
	if(bUsingGitLfsLocking)
	{
		return ( ( (LockState == ELockState::Locked) && !IsConflicted() ) || (WorkingCopyState == EWorkingCopyState::Added) ) && IsCurrent();
	}
	else
	{
		return (WorkingCopyState == EWorkingCopyState::Added
			|| WorkingCopyState == EWorkingCopyState::Deleted
			|| WorkingCopyState == EWorkingCopyState::Missing
			|| WorkingCopyState == EWorkingCopyState::Modified
			|| WorkingCopyState == EWorkingCopyState::Renamed) && IsCurrent();
	}
}

bool FGitSourceControlState::CanCheckout() const
{
	if(bUsingGitLfsLocking)
	{
		// We don't want to allow checkout if the file is out-of-date, as modifying an out-of-date binary file will most likely result in a merge conflict
		return (WorkingCopyState == EWorkingCopyState::Unchanged || WorkingCopyState == EWorkingCopyState::Modified) && LockState == ELockState::NotLocked && IsCurrent();
	}
	else
	{
		return false; // With Git all tracked files in the working copy are always already checked-out (as opposed to Perforce)
	}
}

bool FGitSourceControlState::IsCheckedOut() const
{
	if (bUsingGitLfsLocking)
	{
		return LockState == ELockState::Locked;
	}
	else
	{
		return IsSourceControlled(); // With Git all tracked files in the working copy are always checked-out (as opposed to Perforce)
	}
}

bool FGitSourceControlState::IsCheckedOutOther(FString* Who) const
{
	if (Who != NULL)
	{
		*Who = LockUser;
	}
	return LockState == ELockState::LockedOther;
}

bool FGitSourceControlState::IsCurrent() const
{
	return !bNewerVersionOnServer;
}

bool FGitSourceControlState::IsSourceControlled() const
{
	return WorkingCopyState != EWorkingCopyState::NotControlled && WorkingCopyState != EWorkingCopyState::Ignored && WorkingCopyState != EWorkingCopyState::Unknown;
}

bool FGitSourceControlState::IsAdded() const
{
	return WorkingCopyState == EWorkingCopyState::Added;
}

bool FGitSourceControlState::IsDeleted() const
{
	return WorkingCopyState == EWorkingCopyState::Deleted || WorkingCopyState == EWorkingCopyState::Missing;
}

bool FGitSourceControlState::IsIgnored() const
{
	return WorkingCopyState == EWorkingCopyState::Ignored;
}

bool FGitSourceControlState::CanEdit() const
{
	return IsCurrent(); // With Git all files in the working copy are always editable (as opposed to Perforce)
}

bool FGitSourceControlState::CanDelete() const
{
	return !IsCheckedOutOther() && IsSourceControlled() && IsCurrent();
}

bool FGitSourceControlState::IsUnknown() const
{
	return WorkingCopyState == EWorkingCopyState::Unknown;
}

bool FGitSourceControlState::IsModified() const
{
	// Warning: for Perforce, a checked-out file is locked for modification (whereas with Git all tracked files are checked-out),
	// so for a clean "check-in" (commit) checked-out files unmodified should be removed from the changeset (the index)
	// http://stackoverflow.com/questions/12357971/what-does-revert-unchanged-files-mean-in-perforce
	//
	// Thus, before check-in UE4 Editor call RevertUnchangedFiles() in PromptForCheckin() and CheckinFiles().
	//
	// So here we must take care to enumerate all states that need to be commited,
	// all other will be discarded :
	//  - Unknown
	//  - Unchanged
	//  - NotControlled
	//  - Ignored
	return WorkingCopyState == EWorkingCopyState::Added
		|| WorkingCopyState == EWorkingCopyState::Deleted
		|| WorkingCopyState == EWorkingCopyState::Modified
		|| WorkingCopyState == EWorkingCopyState::Renamed
		|| WorkingCopyState == EWorkingCopyState::Copied
		|| WorkingCopyState == EWorkingCopyState::Missing
		|| WorkingCopyState == EWorkingCopyState::Conflicted;
}

bool FGitSourceControlState::CanAdd() const
{
	return WorkingCopyState == EWorkingCopyState::NotControlled;
}

bool FGitSourceControlState::IsConflicted() const
{
	return WorkingCopyState == EWorkingCopyState::Conflicted;
}

bool FGitSourceControlState::CanRevert() const
{
	return CanCheckIn();
}

#undef LOCTEXT_NAMESPACE
<|endoftext|>


<commit_before>/*
 * Copyright (c) 2001 Stephen Williams (steve@icarus.com)
 * Copyright (c) 2001 Stephan Boettcher <stephan@nevis.columbia.edu>
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form under the terms of the GNU
 *    General Public License as published by the Free Software
 *    Foundation; either version 2 of the License, or (at your option)
 *    any later version.
 *
 *    This program 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 this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */
#if !defined(WINNT)
#ident "$Id: vpi_vthr_vector.cc,v 1.1 2001/05/10 00:26:53 steve Exp $"
#endif

/*
 * vpiReg handles are handled here. These objects represent vectors of
 * .var objects that can be manipulated by the VPI module.
 */

# include  "vpi_priv.h"
# include  "vthread.h"
# include  <stdio.h>
# include  <malloc.h>
# include  <assert.h>

struct __vpiVThrVec {
      struct __vpiHandle base;
      unsigned short bas;
      unsigned short wid;
      char *name;
};

inline static
unsigned get_bit(struct __vpiVThrVec *rfp, unsigned idx)
{
      return vthread_get_bit(vpip_current_vthread, rfp->bas+idx);
}

inline static
void set_bit(struct __vpiVThrVec *rfp, unsigned idx, unsigned bit)
{
      return vthread_put_bit(vpip_current_vthread, rfp->bas+idx, bit);
}

/*
 * Hex digits that represent 4-value bits of Verilog are not as
 * trivially obvious to display as if the bits were the usual 2-value
 * bits. So, although it is possible to write a function that
 * generates a correct character for 4*4-value bits, it is easier to
 * just perform the lookup in a table. This only takes 256 bytes,
 * which is not many executable instructions:-)
 *
 * The table is calculated as compile time, therefore, by the
 * draw_tt.c program.
 */

extern const char hex_digits[256];

extern const char oct_digits[256];

/*
 *  vpi_get
 */
static int vthr_vec_get(int code, vpiHandle ref)
{
      assert((ref->vpi_type->type_code==vpiNet)
	     || (ref->vpi_type->type_code==vpiReg)
	     || (ref->vpi_type->type_code==vpiConstant));

      struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;

      switch (code) {

	  case vpiSigned:
	    return 0;

	  case vpiSize:
	    return rfp->wid;

	  default:
	    return 0;
      }
}

static char* vthr_vec_get_str(int code, vpiHandle ref)
{
      assert((ref->vpi_type->type_code==vpiNet)
	     || (ref->vpi_type->type_code==vpiReg));

      struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;

      switch (code) {

	  case vpiFullName:
	    return (char*)rfp->name;
      }

      return 0;
}

static char buf[4096];

static void vthr_vec_DecStrVal(struct __vpiVThrVec*rfp, s_vpi_value*vp)
{
      unsigned long val = 0;
      unsigned count_x = 0, count_z = 0;

      for (unsigned idx = 0 ;  idx < rfp->wid ;  idx += 1) {
	    val *= 2;
	    switch (get_bit(rfp, idx)) {
		case 0:
		  break;
		case 1:
		  val += 1;
		  break;
		case 2:
		  count_x += 1;
		  break;
		case 3:
		  count_z += 1;
		  break;
	    }
      }

      if (count_x == rfp->wid) {
	    buf[0] = 'x';
	    buf[1] = 0;
	    return;
      }

      if (count_x > 0) {
	    buf[0] = 'X';
	    buf[1] = 0;
	    return;
      }

      if (count_z == rfp->wid) {
	    buf[0] = 'z';
	    buf[1] = 0;
	    return;
      }

      if (count_z > 0) {
	    buf[0] = 'Z';
	    buf[1] = 0;
	    return;
      }

      sprintf(buf, "%lu", val);
}

/*
 * The get_value method reads the values of the functors and returns
 * the vector to the caller. This causes no side-effect, and reads the
 * variables like a %load would.
 */
static void vthr_vec_get_value(vpiHandle ref, s_vpi_value*vp)
{
      assert((ref->vpi_type->type_code==vpiNet)
	     || (ref->vpi_type->type_code==vpiReg)
	     || (ref->vpi_type->type_code==vpiConstant));

      struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;

      unsigned wid = rfp->wid;

      switch (vp->format) {

	  case vpiBinStrVal:
	    for (unsigned idx = 0 ;  idx < wid ;  idx += 1) {
		  buf[wid-idx-1] = "01xz"[get_bit(rfp, idx)];
	    }
	    buf[wid] = 0;
	    vp->value.str = buf;
	    break;

	  case vpiHexStrVal: {
		unsigned hval, hwid;
		hwid = (wid + 3) / 4;
		buf[hwid] = 0;
		hval = 0;
		for (unsigned idx = 0 ;  idx < wid ;  idx += 1) {
		      hval = hval | (get_bit(rfp, idx) << 2*(idx % 4));

		      if (idx%4 == 3) {
			    hwid -= 1;
			    buf[hwid] = hex_digits[hval];
			    hval = 0;
		      }
		}

		if (hwid > 0) {
		      hwid -= 1;
		      buf[hwid] = hex_digits[hval];
		      hval = 0;
		}
		vp->value.str = buf;
		break;
	  }

	  case vpiOctStrVal: {
		unsigned hval, hwid;
		hwid = (wid + 2) / 3;
		buf[hwid] = 0;
		hval = 0;
		for (unsigned idx = 0 ;  idx < wid ;  idx += 1) {
		      hval = hval | (get_bit(rfp,idx) << 2*(idx % 3));

		      if (idx%3 == 2) {
			    hwid -= 1;
			    buf[hwid] = oct_digits[hval];
			    hval = 0;
		      }
		}

		if (hwid > 0) {
		      hwid -= 1;
		      buf[hwid] = oct_digits[hval];
		      hval = 0;
		}
		vp->value.str = buf;
		break;
	  }

	  case vpiDecStrVal:
	    vthr_vec_DecStrVal(rfp, vp);
	    vp->value.str = buf;
	    break;

	  default:
	      /* XXXX Not implemented yet. */
	    assert(0);
      }
}

/*
 * The put_value method writes the value into the vector.
 */
static vpiHandle vthr_vec_put_value(vpiHandle ref, s_vpi_value*vp,
				  p_vpi_time when, int flags)
{
      assert((ref->vpi_type->type_code==vpiNet)
	     || (ref->vpi_type->type_code==vpiReg));

      struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;

	/* XXXX delays are not yet supported. */
      assert(flags == vpiNoDelay);

      unsigned wid = rfp->wid;

      switch (vp->format) {

	  case vpiIntVal: {
		assert(wid <= sizeof(long));

		long val = vp->value.integer;
		for (unsigned idx = 0 ;  idx < wid ;  idx += 1) {
		      set_bit(rfp, idx, val&1);
		      val >>= 1;
		}
		break;
	  }

	  case vpiScalarVal:
	    switch (vp->value.scalar) {
		case vpi0:
		  set_bit(rfp, 0, 0);
		  break;
		case vpi1:
		  set_bit(rfp, 0, 1);
		  break;
		case vpiX:
		  set_bit(rfp, 0, 2);
		  break;
		case vpiZ:
		  set_bit(rfp, 0, 3);
		  break;
		default:
		  assert(0);
	    }
	    break;

	  case vpiVectorVal: {
		assert(wid <= sizeof (unsigned long));

		unsigned long aval = vp->value.vector->aval;
		unsigned long bval = vp->value.vector->bval;
		for (unsigned idx = 0 ;  idx < wid ;  idx += 1) {
		      int bit = (aval&1) | (((bval^aval)<<1)&2);
		      set_bit(rfp, idx, bit);
		      aval >>= 1;
		      bval >>= 1;
		}
		break;
	  }

	  default:
	    assert(0);

      }

      return ref;
}

// The code fully supports vpiReg, vpi_Net, but we do not
// create such things, yet.  Lacking a neme, for example.

static const struct __vpirt vpip_vthr_const_rt = {
      vpiConstant,
      vthr_vec_get,
      vthr_vec_get_str,
      vthr_vec_get_value,
      vthr_vec_put_value,
      0,
      0
};

/*
 * Construct a vpiReg object. Give the object specified dimensions,
 * and point to the specified functor for the lsb.
 */
vpiHandle vpip_make_vthr_vector(unsigned base, unsigned wid)
{
      struct __vpiVThrVec*obj = (struct __vpiVThrVec*)
	    malloc(sizeof(struct __vpiVThrVec));
      obj->base.vpi_type = &vpip_vthr_const_rt;
      obj->bas = base;
      obj->wid = wid;
      obj->name = "T<>";

      return &obj->base;
}

/*
 * $Log: vpi_vthr_vector.cc,v $
 * Revision 1.1  2001/05/10 00:26:53  steve
 *  VVP support for memories in expressions,
 *  including general support for thread bit
 *  vectors as system task parameters.
 *  (Stephan Boettcher)
 *
 */

<commit_msg> Get bit ordering right when making decimal strings.<commit_after>/*
 * Copyright (c) 2001 Stephen Williams (steve@icarus.com)
 * Copyright (c) 2001 Stephan Boettcher <stephan@nevis.columbia.edu>
 *
 *    This source code is free software; you can redistribute it
 *    and/or modify it in source code form under the terms of the GNU
 *    General Public License as published by the Free Software
 *    Foundation; either version 2 of the License, or (at your option)
 *    any later version.
 *
 *    This program 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 this program; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
 */
#if !defined(WINNT)
#ident "$Id: vpi_vthr_vector.cc,v 1.2 2001/05/20 00:40:12 steve Exp $"
#endif

/*
 * vpiReg handles are handled here. These objects represent vectors of
 * .var objects that can be manipulated by the VPI module.
 */

# include  "vpi_priv.h"
# include  "vthread.h"
# include  <stdio.h>
# include  <malloc.h>
# include  <assert.h>

struct __vpiVThrVec {
      struct __vpiHandle base;
      unsigned short bas;
      unsigned short wid;
      char *name;
};

inline static
unsigned get_bit(struct __vpiVThrVec *rfp, unsigned idx)
{
      return vthread_get_bit(vpip_current_vthread, rfp->bas+idx);
}

inline static
void set_bit(struct __vpiVThrVec *rfp, unsigned idx, unsigned bit)
{
      return vthread_put_bit(vpip_current_vthread, rfp->bas+idx, bit);
}

/*
 * Hex digits that represent 4-value bits of Verilog are not as
 * trivially obvious to display as if the bits were the usual 2-value
 * bits. So, although it is possible to write a function that
 * generates a correct character for 4*4-value bits, it is easier to
 * just perform the lookup in a table. This only takes 256 bytes,
 * which is not many executable instructions:-)
 *
 * The table is calculated as compile time, therefore, by the
 * draw_tt.c program.
 */

extern const char hex_digits[256];

extern const char oct_digits[256];

/*
 *  vpi_get
 */
static int vthr_vec_get(int code, vpiHandle ref)
{
      assert((ref->vpi_type->type_code==vpiNet)
	     || (ref->vpi_type->type_code==vpiReg)
	     || (ref->vpi_type->type_code==vpiConstant));

      struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;

      switch (code) {

	  case vpiSigned:
	    return 0;

	  case vpiSize:
	    return rfp->wid;

	  default:
	    return 0;
      }
}

static char* vthr_vec_get_str(int code, vpiHandle ref)
{
      assert((ref->vpi_type->type_code==vpiNet)
	     || (ref->vpi_type->type_code==vpiReg));

      struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;

      switch (code) {

	  case vpiFullName:
	    return (char*)rfp->name;
      }

      return 0;
}

static char buf[4096];

static void vthr_vec_DecStrVal(struct __vpiVThrVec*rfp, s_vpi_value*vp)
{
      unsigned long val = 0;
      unsigned count_x = 0, count_z = 0;

      for (unsigned idx = 0 ;  idx < rfp->wid ;  idx += 1) {
	    val *= 2;
	    switch (get_bit(rfp, rfp->wid-idx-1)) {
		case 0:
		  break;
		case 1:
		  val += 1;
		  break;
		case 2:
		  count_x += 1;
		  break;
		case 3:
		  count_z += 1;
		  break;
	    }
      }

      if (count_x == rfp->wid) {
	    buf[0] = 'x';
	    buf[1] = 0;
	    return;
      }

      if (count_x > 0) {
	    buf[0] = 'X';
	    buf[1] = 0;
	    return;
      }

      if (count_z == rfp->wid) {
	    buf[0] = 'z';
	    buf[1] = 0;
	    return;
      }

      if (count_z > 0) {
	    buf[0] = 'Z';
	    buf[1] = 0;
	    return;
      }

      sprintf(buf, "%lu", val);
}

/*
 * The get_value method reads the values of the functors and returns
 * the vector to the caller. This causes no side-effect, and reads the
 * variables like a %load would.
 */
static void vthr_vec_get_value(vpiHandle ref, s_vpi_value*vp)
{
      assert((ref->vpi_type->type_code==vpiNet)
	     || (ref->vpi_type->type_code==vpiReg)
	     || (ref->vpi_type->type_code==vpiConstant));

      struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;

      unsigned wid = rfp->wid;

      switch (vp->format) {

	  case vpiBinStrVal:
	    for (unsigned idx = 0 ;  idx < wid ;  idx += 1) {
		  buf[wid-idx-1] = "01xz"[get_bit(rfp, idx)];
	    }
	    buf[wid] = 0;
	    vp->value.str = buf;
	    break;

	  case vpiHexStrVal: {
		unsigned hval, hwid;
		hwid = (wid + 3) / 4;
		buf[hwid] = 0;
		hval = 0;
		for (unsigned idx = 0 ;  idx < wid ;  idx += 1) {
		      hval = hval | (get_bit(rfp, idx) << 2*(idx % 4));

		      if (idx%4 == 3) {
			    hwid -= 1;
			    buf[hwid] = hex_digits[hval];
			    hval = 0;
		      }
		}

		if (hwid > 0) {
		      hwid -= 1;
		      buf[hwid] = hex_digits[hval];
		      hval = 0;
		}
		vp->value.str = buf;
		break;
	  }

	  case vpiOctStrVal: {
		unsigned hval, hwid;
		hwid = (wid + 2) / 3;
		buf[hwid] = 0;
		hval = 0;
		for (unsigned idx = 0 ;  idx < wid ;  idx += 1) {
		      hval = hval | (get_bit(rfp,idx) << 2*(idx % 3));

		      if (idx%3 == 2) {
			    hwid -= 1;
			    buf[hwid] = oct_digits[hval];
			    hval = 0;
		      }
		}

		if (hwid > 0) {
		      hwid -= 1;
		      buf[hwid] = oct_digits[hval];
		      hval = 0;
		}
		vp->value.str = buf;
		break;
	  }

	  case vpiDecStrVal:
	    vthr_vec_DecStrVal(rfp, vp);
	    vp->value.str = buf;
	    break;

	  default:
	      /* XXXX Not implemented yet. */
	    assert(0);
      }
}

/*
 * The put_value method writes the value into the vector.
 */
static vpiHandle vthr_vec_put_value(vpiHandle ref, s_vpi_value*vp,
				  p_vpi_time when, int flags)
{
      assert((ref->vpi_type->type_code==vpiNet)
	     || (ref->vpi_type->type_code==vpiReg));

      struct __vpiVThrVec*rfp = (struct __vpiVThrVec*)ref;

	/* XXXX delays are not yet supported. */
      assert(flags == vpiNoDelay);

      unsigned wid = rfp->wid;

      switch (vp->format) {

	  case vpiIntVal: {
		assert(wid <= sizeof(long));

		long val = vp->value.integer;
		for (unsigned idx = 0 ;  idx < wid ;  idx += 1) {
		      set_bit(rfp, idx, val&1);
		      val >>= 1;
		}
		break;
	  }

	  case vpiScalarVal:
	    switch (vp->value.scalar) {
		case vpi0:
		  set_bit(rfp, 0, 0);
		  break;
		case vpi1:
		  set_bit(rfp, 0, 1);
		  break;
		case vpiX:
		  set_bit(rfp, 0, 2);
		  break;
		case vpiZ:
		  set_bit(rfp, 0, 3);
		  break;
		default:
		  assert(0);
	    }
	    break;

	  case vpiVectorVal: {
		assert(wid <= sizeof (unsigned long));

		unsigned long aval = vp->value.vector->aval;
		unsigned long bval = vp->value.vector->bval;
		for (unsigned idx = 0 ;  idx < wid ;  idx += 1) {
		      int bit = (aval&1) | (((bval^aval)<<1)&2);
		      set_bit(rfp, idx, bit);
		      aval >>= 1;
		      bval >>= 1;
		}
		break;
	  }

	  default:
	    assert(0);

      }

      return ref;
}

// The code fully supports vpiReg, vpi_Net, but we do not
// create such things, yet.  Lacking a neme, for example.

static const struct __vpirt vpip_vthr_const_rt = {
      vpiConstant,
      vthr_vec_get,
      vthr_vec_get_str,
      vthr_vec_get_value,
      vthr_vec_put_value,
      0,
      0
};

/*
 * Construct a vpiReg object. Give the object specified dimensions,
 * and point to the specified functor for the lsb.
 */
vpiHandle vpip_make_vthr_vector(unsigned base, unsigned wid)
{
      struct __vpiVThrVec*obj = (struct __vpiVThrVec*)
	    malloc(sizeof(struct __vpiVThrVec));
      obj->base.vpi_type = &vpip_vthr_const_rt;
      obj->bas = base;
      obj->wid = wid;
      obj->name = "T<>";

      return &obj->base;
}

/*
 * $Log: vpi_vthr_vector.cc,v $
 * Revision 1.2  2001/05/20 00:40:12  steve
 *  Get bit ordering right when making decimal strings.
 *
 * Revision 1.1  2001/05/10 00:26:53  steve
 *  VVP support for memories in expressions,
 *  including general support for thread bit
 *  vectors as system task parameters.
 *  (Stephan Boettcher)
 *
 */

<|endoftext|>


<commit_before>/*
 * This program 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.
 *
 * Written (W) 2011 Heiko Strathmann
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 */

#include <shogun/base/init.h>
#include <shogun/base/Parameter.h>
#include <shogun/base/ParameterMap.h>

using namespace shogun;

void print_message(FILE* target, const char* str)
{
	fprintf(target, "%s", str);
}

void test_mapping_1()
{
	ParameterMap* map=new ParameterMap();

	map->put(
			new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_FLOAT64, 2),
			new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_INT32, 1)
	);

	map->put(
			new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_INT32, 1),
			new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_FLOAT64, 0)
	);

	/* finalizing the map is needed before accessing it */
	map->finalize_map();

	map->print_map();
	SG_SPRINT("\n");

	/* get some elements from map, one/two ARE in map, three and four are NOT */
	DynArray<SGParamInfo*> dummies;
	dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
			PT_INT32, 1));
	dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
			PT_FLOAT64, 2));
	dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
				PT_INT32, 2));
	dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
			PT_FLOAT64, 0));

	for (index_t i=0; i<dummies.get_num_elements(); ++i)
	{
		SGParamInfo* current=dummies.get_element(i);

		char* s=current->to_string();
		SG_SPRINT("searching for: %s\n", s);
		SG_FREE(s);

		if (i==2)
		{

		}

		SGParamInfo* result=map->get(current);
		if (result)
		{
			s=result->to_string();
			SG_SPRINT("found: %s\n\n", s);
			SG_FREE(s);
		}
		else
			SG_SPRINT("nothing found\n\n");

		delete current;
	}

	delete map;
}

void print_value(SGParamInfo* key, ParameterMap* map)
{
	SGParamInfo* current=map->get(key);
	key->print_param_info();
	SG_SPRINT("value: ");

	if (current)
		current->print_param_info();
	else
		SG_SPRINT("no element\n");

	SG_SPRINT("\n");
}

void test_mapping_2()
{
	ParameterMap* map=new ParameterMap();

	EContainerType cfrom=CT_SCALAR;
	EContainerType cto=CT_MATRIX;

	EStructType sfrom=ST_NONE;
	EStructType sto=ST_STRING;

	EPrimitiveType pfrom=PT_BOOL;
	EPrimitiveType pto=PT_SGOBJECT;

	map->put(new SGParamInfo("1", cfrom, sfrom, pfrom, 1),
			new SGParamInfo("eins", cto, sto, pto, 2));
	map->put(new SGParamInfo("2", cfrom, sfrom, pfrom, 2),
			new SGParamInfo("zwei", cto, sto, pto, 1));
	map->put(new SGParamInfo("3", cfrom, sfrom, pfrom, 3),
			new SGParamInfo("drei", cto, sto, pto, 5));
	map->put(new SGParamInfo("4", cfrom, sfrom, pfrom, 4),
			new SGParamInfo("vier", cto, sto, pto, 2));

	SG_SPRINT("before finalization:\n");
	map->print_map();
	map->finalize_map();

	SG_SPRINT("\n\nafter finalization:\n");
	map->print_map();

	SGParamInfo* key;

	SG_SPRINT("\n\ntesting map\n");
	key=new SGParamInfo("1", cfrom, sfrom, pfrom, 1);
	print_value(key, map);
	delete key;

	key=new SGParamInfo("2", cfrom, sfrom, pfrom, 2);
	print_value(key, map);
	delete key;

	key=new SGParamInfo("2", cto, sfrom, pfrom, 2);
	print_value(key, map);
	delete key;

	key=new SGParamInfo("2", cfrom, sto, pfrom, 2);
	print_value(key, map);
	delete key;

	key=new SGParamInfo("2", cfrom, sfrom, pto, 2);
	print_value(key, map);
	delete key;

	key=new SGParamInfo("5", cfrom, sfrom, pfrom, 5);
	print_value(key, map);
	delete key;

	delete map;
}

int main(int argc, char **argv)
{
	init_shogun(&print_message, &print_message, &print_message);

	test_mapping_1();
	test_mapping_2();

	exit_shogun();

	return 0;
}

<commit_msg>corrected error in example due to restriction that parameter step has to be one<commit_after>/*
 * This program 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.
 *
 * Written (W) 2011 Heiko Strathmann
 * Copyright (C) 2011 Berlin Institute of Technology and Max-Planck-Society
 */

#include <shogun/base/init.h>
#include <shogun/base/Parameter.h>
#include <shogun/base/ParameterMap.h>

using namespace shogun;

void print_message(FILE* target, const char* str)
{
	fprintf(target, "%s", str);
}

void test_mapping_1()
{
	ParameterMap* map=new ParameterMap();

	map->put(
			new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_FLOAT64, 2),
			new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_INT32, 1)
	);

	map->put(
			new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_INT32, 1),
			new SGParamInfo("number", CT_SCALAR, ST_NONE, PT_FLOAT64, 0)
	);

	map->put(
			new SGParamInfo("number_2", CT_SCALAR, ST_NONE, PT_INT32, 1),
			new SGParamInfo("number_to_keep", CT_SCALAR, ST_NONE, PT_INT32, 0)
	);

	/* finalizing the map is needed before accessing it */
	map->finalize_map();

	map->print_map();
	SG_SPRINT("\n");

	/* get some elements from map, one/two ARE in map, three and four are NOT */
	DynArray<SGParamInfo*> dummies;
	dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
			PT_INT32, 1));
	dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
			PT_FLOAT64, 2));
	dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
				PT_INT32, 2));
	dummies.append_element(new SGParamInfo("number", CT_SCALAR, ST_NONE,
			PT_FLOAT64, 0));
	dummies.append_element(new SGParamInfo("number_2", CT_SCALAR, ST_NONE,
			PT_INT32, 1));

	for (index_t i=0; i<dummies.get_num_elements(); ++i)
	{
		SGParamInfo* current=dummies.get_element(i);

		char* s=current->to_string();
		SG_SPRINT("searching for: %s\n", s);
		SG_FREE(s);

		SGParamInfo* result=map->get(current);
		if (result)
		{
			s=result->to_string();
			SG_SPRINT("found: %s\n\n", s);
			SG_FREE(s);
		}
		else
			SG_SPRINT("nothing found\n\n");

		delete current;
	}

	delete map;
}

void print_value(SGParamInfo* key, ParameterMap* map)
{
	SGParamInfo* current=map->get(key);
	key->print_param_info();
	SG_SPRINT("value: ");

	if (current)
		current->print_param_info();
	else
		SG_SPRINT("no element\n");

	SG_SPRINT("\n");
}

void test_mapping_2()
{
	ParameterMap* map=new ParameterMap();

	EContainerType cfrom=CT_SCALAR;
	EContainerType cto=CT_MATRIX;

	EStructType sfrom=ST_NONE;
	EStructType sto=ST_STRING;

	EPrimitiveType pfrom=PT_BOOL;
	EPrimitiveType pto=PT_SGOBJECT;

	map->put(new SGParamInfo("1", cfrom, sfrom, pfrom, 2),
			new SGParamInfo("eins", cto, sto, pto, 1));
	map->put(new SGParamInfo("2", cfrom, sfrom, pfrom, 2),
			new SGParamInfo("zwei", cto, sto, pto, 1));
	map->put(new SGParamInfo("3", cfrom, sfrom, pfrom, 4),
			new SGParamInfo("drei", cto, sto, pto, 3));
	map->put(new SGParamInfo("4", cfrom, sfrom, pfrom, 4),
			new SGParamInfo("vier", cto, sto, pto, 3));

	SG_SPRINT("before finalization:\n");
	map->print_map();
	map->finalize_map();

	SG_SPRINT("\n\nafter finalization:\n");
	map->print_map();

	SGParamInfo* key;

	SG_SPRINT("\n\ntesting map\n");
	key=new SGParamInfo("1", cfrom, sfrom, pfrom, 1);
	print_value(key, map);
	delete key;

	key=new SGParamInfo("2", cfrom, sfrom, pfrom, 2);
	print_value(key, map);
	delete key;

	key=new SGParamInfo("2", cto, sfrom, pfrom, 2);
	print_value(key, map);
	delete key;

	key=new SGParamInfo("2", cfrom, sto, pfrom, 2);
	print_value(key, map);
	delete key;

	key=new SGParamInfo("2", cfrom, sfrom, pto, 2);
	print_value(key, map);
	delete key;

	key=new SGParamInfo("5", cfrom, sfrom, pfrom, 4);
	print_value(key, map);
	delete key;

	delete map;
}

int main(int argc, char **argv)
{
	init_shogun(&print_message, &print_message, &print_message);

	test_mapping_1();
	test_mapping_2();

	exit_shogun();

	return 0;
}

<|endoftext|>