<commit_before>#include "tds2pdb.hpp"

#include <cstdint>
#include <iostream>

#include <boost/program_options.hpp>

#include "file_handling.hpp"

namespace po = boost::program_options;

/// Main entry point.
int32_t main(const int32_t argc, const char** argv)
{
  std::string input_file;
  // Option parsing.
  po::options_description desc("Generic options");
  desc.add_options()
    ("input-file,i", po::value<std::string>(&input_file)->required(), "input file")
    ("input-folder,f", po::value<std::string>(), "input folder")
    ("verbose,v", "verbose output")
    ("version", "print version string")
    ("help", "produce help message");

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);

  if (vm.count("help"))
  {
    desc.print(std::cout, 40);
    return EXIT_SUCCESS;
  }
  else if (vm.count("version"))
  {
    std::cout << argv[0] << " version: " << TDS2PDB_VERSION_MAJOR << "." << TDS2PDB_VERSION_MINOR << '\n';
    return EXIT_SUCCESS;
  }

  po::notify(vm);

  // Beginning of useful work.
  boost::filesystem::path tds_file, binary_file, pdb_file;
  std::tie(tds_file, binary_file, binary_file) = get_files(input_file.c_str());

  // If the .exe file does not exist, try a .dll file instead.
  if (boost::filesystem::exists(binary_file) == false)
  {
    binary_file.replace_extension(".dll");

    if (boost::filesystem::exists(binary_file) == false)
    {
      std::cout << "Error: there are no .dll or .exe files with the stem " << binary_file.stem().generic_string() << '\n';
      return EXIT_FAILURE;
    }
  }

  // auto tds_format = parse_tds(tds_file);

  return EXIT_SUCCESS;
}
<commit_msg>Do not overwrite the binary_file (.pdb) with the pdb_file (.pdb) path.<commit_after>#include "tds2pdb.hpp"

#include <cstdint>
#include <iostream>

#include <boost/program_options.hpp>

#include "file_handling.hpp"

namespace po = boost::program_options;

/// Main entry point.
int32_t main(const int32_t argc, const char** argv)
{
  std::string input_file;
  // Option parsing.
  po::options_description desc("Generic options");
  desc.add_options()
    ("input-file,i", po::value<std::string>(&input_file)->required(), "input file")
    ("input-folder,f", po::value<std::string>(), "input folder")
    ("verbose,v", "verbose output")
    ("version", "print version string")
    ("help", "produce help message");

  po::variables_map vm;
  po::store(po::parse_command_line(argc, argv, desc), vm);

  if (vm.count("help"))
  {
    desc.print(std::cout, 40);
    return EXIT_SUCCESS;
  }
  else if (vm.count("version"))
  {
    std::cout << argv[0] << " version: " << TDS2PDB_VERSION_MAJOR << "." << TDS2PDB_VERSION_MINOR << '\n';
    return EXIT_SUCCESS;
  }

  po::notify(vm);

  // Beginning of useful work.
  boost::filesystem::path tds_file, binary_file, pdb_file;
  std::tie(tds_file, binary_file, pdb_file) = get_files(input_file.c_str());

  // If the .exe file does not exist, try a .dll file instead.
  if (boost::filesystem::exists(binary_file) == false)
  {
    binary_file.replace_extension(".dll");

    if (boost::filesystem::exists(binary_file) == false)
    {
      std::cout << "Error: there are no .dll or .exe files with the stem " << binary_file.stem().generic_string() << '\n';
      return EXIT_FAILURE;
    }
  }

  // auto tds_format = parse_tds(tds_file);

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>#include <SFML/Graphics.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>

#include "renderer.h"
#include "player.h"
#include "coord.h"

GLuint Texture = 0;

GLdouble norm = 1 / sqrt( 3 );

GLdouble x = 0;
GLdouble y = 0;
GLdouble z = 0;
GLdouble radius = 1;
  GLdouble vertices[24] = { x - radius, y - radius, z + radius,
							x + radius, y - radius, z + radius,
							x + radius, y + radius, z + radius,
							x - radius, y + radius, z + radius,
							x - radius, y - radius, z - radius,
							x + radius, y - radius, z - radius,
							x + radius, y + radius, z - radius,
							x - radius, y + radius, z - radius };

  GLdouble normals[24] = { -norm, -norm,  norm,
						    norm, -norm,  norm,
						    norm,  norm,  norm,
						   -norm,  norm,  norm,
						   -norm, -norm, -norm,
						    norm, -norm, -norm,
						    norm,  norm, -norm,
						   -norm,  norm, -norm };

  GLdouble texcoords[24] = { 0.125, 0.0, 0.0,
						     0.0, 0.125, 0.0,
						     0.0, 0.0, 0.0,
						     0.125, 0.0, 0.0,
						     0.0, 0.125, 0.0,
						     0.0, 0.0, 0.0,
						     0.125, 0.0, 0.0,
						     0.0, 0.125, 0.0 };

  GLubyte indices[24] = { 7, 6, 5, 4,
						  5, 6, 2, 1,
						  4, 5, 1, 0,
						  1, 2, 3, 0,
						  3, 7, 4, 0,
						  6, 7, 3, 2 };

Renderer::Renderer(Terrain initterrain) : terrain(initterrain) {
    // Set color and depth clear value
    glClearDepth(1.f);
    glClearColor(0.f, 0.f, 0.f, 1.f); // black

    // Enable Z-buffer read and write
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);

    // Face culling to render half the polys
    glEnable(GL_CULL_FACE);

    // Setup a perspective projection
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(90.f, 1.f, 1.f, 500.f);

    // Lighting
    GLfloat LightAmbient[]  = { 0.5f, 0.5f, 0.5f, 1.0f }; // Ambient Light Values
    GLfloat LightDiffuse[]  = { 1.0f, 1.0f, 1.0f, 1.0f };	// Diffuse Light Values
    GLfloat LightPosition[] = { 0.0f, 0.0f, 2.0f, 1.0f };	// Light Position
    glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient);				// Setup The Ambient Light
    glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse);				// Setup The Diffuse Light
    glLightfv(GL_LIGHT1, GL_POSITION,LightPosition);			// Position The Light
    glEnable(GL_LIGHT1);							// Enable Light One

    //glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); // Let glcolor work with lighting
    //glEnable(GL_COLOR_MATERIAL); // Enable lighting
    glEnable(GL_TEXTURE_2D); // Enable textures
    //glEnable(GL_LIGHTING); // Enable lighting

    glShadeModel(GL_SMOOTH); // Enable Smooth Shading

    sf::Image Image;
    if (!Image.LoadFromFile("data/tiles.png"))
        return;

    glGenTextures(1, &Texture);
    glBindTexture(GL_TEXTURE_2D, Texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Image.GetWidth(), Image.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, Image.GetPixelsPtr());
}

// Don't forget to destroy our texture
//glDeleteTextures(1, &Texture);

void drawCube(float x, float y, float z, float length) {
    float subsize = length / 2;

    glPushMatrix(); // Preserve world matrix

    // Apply some transformations
    glTranslatef(x + subsize, y + subsize, z + subsize);
    glScalef(subsize, subsize, subsize);

    glDrawElements( GL_QUADS, 24, GL_UNSIGNED_BYTE, indices );

    glPopMatrix(); // Undo the translations
}

void renderNode(Octree<bool> terrain, float x, float y, float z, float size) {
    if (terrain.hasChildren) {
        float subsize = size / 2;
        renderNode(terrain.children[0], x,         y,         z,         subsize);
        renderNode(terrain.children[1], x+subsize, y,         z,         subsize);
        renderNode(terrain.children[2], x,         y+subsize, z,         subsize);
        renderNode(terrain.children[3], x+subsize, y+subsize, z,         subsize);
        renderNode(terrain.children[4], x,         y,         z+subsize, subsize);
        renderNode(terrain.children[5], x+subsize, y,         z+subsize, subsize);
        renderNode(terrain.children[6], x,         y+subsize, z+subsize, subsize);
        renderNode(terrain.children[7], x+subsize, y+subsize, z+subsize, subsize);
    } else if (terrain.value) {
        drawCube(x, y, z, size);
    }
}

void Renderer::render(Player player) {

    // Clear color and depth buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glMatrixMode(GL_MODELVIEW);

    glBindTexture(GL_TEXTURE_2D, Texture);

    glEnableClientState( GL_VERTEX_ARRAY );
    glEnableClientState( GL_NORMAL_ARRAY );
    glEnableClientState( GL_TEXTURE_COORD_ARRAY );

    glVertexPointer( 3, GL_DOUBLE, 0, &vertices[0] );
    glNormalPointer( GL_DOUBLE, 0, &normals[0] );
    glTexCoordPointer( 3, GL_DOUBLE, 0, &texcoords[0] );

    // Apply some transformations
    glLoadIdentity();
    glRotatef(-90 + player.Yrot, 1.f, 0.f, 0.f);
    glRotatef(player.Zrot, 0.f, 0.f, 1.f);
    glTranslatef(-player.X, -player.Y, -player.Z);    // Translate The Scene Based On Player Position

    // Loop through chunks and render them
    int i, j, k;
    for(i = 0; i < terrain.sizeX; i++)
        for(j = 0; j < terrain.sizeY; j++)
            for(k = 0; k < terrain.sizeZ; k++)
                renderNode(terrain.GeneratedTerrain[Coord(i,j,k)], i*terrain.chunkSize, j*terrain.chunkSize, k*terrain.chunkSize, terrain.chunkSize);

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
<commit_msg>Redo how the world translations are applied. This also fixes lighting, which we don't use anyway.<commit_after>#include <SFML/Graphics.hpp>
#include <iostream>
#include <fstream>
#include <string>
#include <stdio.h>

#include "renderer.h"
#include "player.h"
#include "coord.h"

GLuint Texture = 0;

GLdouble norm = 1 / sqrt( 3 );

GLdouble x = 0;
GLdouble y = 0;
GLdouble z = 0;
GLdouble radius = 1;
  GLdouble vertices[24] = { x - radius, y - radius, z + radius,
							x + radius, y - radius, z + radius,
							x + radius, y + radius, z + radius,
							x - radius, y + radius, z + radius,
							x - radius, y - radius, z - radius,
							x + radius, y - radius, z - radius,
							x + radius, y + radius, z - radius,
							x - radius, y + radius, z - radius };

  GLdouble normals[24] = { -norm, -norm,  norm,
						    norm, -norm,  norm,
						    norm,  norm,  norm,
						   -norm,  norm,  norm,
						   -norm, -norm, -norm,
						    norm, -norm, -norm,
						    norm,  norm, -norm,
						   -norm,  norm, -norm };

  GLdouble texcoords[24] = { 0.125, 0.0, 0.0,
						     0.0, 0.125, 0.0,
						     0.0, 0.0, 0.0,
						     0.125, 0.0, 0.0,
						     0.0, 0.125, 0.0,
						     0.0, 0.0, 0.0,
						     0.125, 0.0, 0.0,
						     0.0, 0.125, 0.0 };

  GLubyte indices[24] = { 7, 6, 5, 4,
						  5, 6, 2, 1,
						  4, 5, 1, 0,
						  1, 2, 3, 0,
						  3, 7, 4, 0,
						  6, 7, 3, 2 };

Renderer::Renderer(Terrain initterrain) : terrain(initterrain) {
    // Set color and depth clear value
    glClearDepth(1.f);
    glClearColor(0.f, 0.f, 0.f, 1.f); // black

    // Enable Z-buffer read and write
    glEnable(GL_DEPTH_TEST);
    glDepthMask(GL_TRUE);

    // Face culling to render half the polys
    glEnable(GL_CULL_FACE);

    // Lighting
    GLfloat LightAmbient[]  = { 0.5f, 0.5f, 0.5f, 1.0f }; // Ambient Light Values
    GLfloat LightDiffuse[]  = { 1.0f, 1.0f, 1.0f, 1.0f };	// Diffuse Light Values
    GLfloat LightPosition[] = { 0.0f, 0.0f, 2.0f, 1.0f };	// Light Position
    glLightfv(GL_LIGHT1, GL_AMBIENT, LightAmbient);				// Setup The Ambient Light
    glLightfv(GL_LIGHT1, GL_DIFFUSE, LightDiffuse);				// Setup The Diffuse Light
    glLightfv(GL_LIGHT1, GL_POSITION,LightPosition);			// Position The Light
    glEnable(GL_LIGHT1);							// Enable Light One

    //glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE); // Let glcolor work with lighting
    //glEnable(GL_COLOR_MATERIAL); // Enable lighting colors
    //glEnable(GL_LIGHTING); // Enable lighting
    glEnable(GL_TEXTURE_2D); // Enable textures

    glShadeModel(GL_SMOOTH); // Enable Smooth Shading

    // Load texture
    sf::Image Image;
    if (!Image.LoadFromFile("data/tiles.png"))
        return;

    glGenTextures(1, &Texture);
    glBindTexture(GL_TEXTURE_2D, Texture);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    gluBuild2DMipmaps(GL_TEXTURE_2D, GL_RGBA, Image.GetWidth(), Image.GetHeight(), GL_RGBA, GL_UNSIGNED_BYTE, Image.GetPixelsPtr());
}

// Don't forget to destroy our texture
//glDeleteTextures(1, &Texture);

void drawCube(float x, float y, float z, float length) {
    float subsize = length / 2;

    glPushMatrix(); // Preserve world matrix

    // Apply some transformations
    glTranslatef(x + subsize, y + subsize, z + subsize);
    glScalef(subsize, subsize, subsize);

    glDrawElements( GL_QUADS, 24, GL_UNSIGNED_BYTE, indices );

    glPopMatrix(); // Undo the translations
}

void renderNode(Octree<bool> terrain, float x, float y, float z, float size) {
    if (terrain.hasChildren) {
        float subsize = size / 2;
        renderNode(terrain.children[0], x,         y,         z,         subsize);
        renderNode(terrain.children[1], x+subsize, y,         z,         subsize);
        renderNode(terrain.children[2], x,         y+subsize, z,         subsize);
        renderNode(terrain.children[3], x+subsize, y+subsize, z,         subsize);
        renderNode(terrain.children[4], x,         y,         z+subsize, subsize);
        renderNode(terrain.children[5], x+subsize, y,         z+subsize, subsize);
        renderNode(terrain.children[6], x,         y+subsize, z+subsize, subsize);
        renderNode(terrain.children[7], x+subsize, y+subsize, z+subsize, subsize);
    } else if (terrain.value) {
        drawCube(x, y, z, size);
    }
}

void Renderer::render(Player player) {

    // Clear color and depth buffer
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    // Apply some transformations
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(90.f, 1.f, 1.f, 500.f);
    glRotatef(-90 + player.Yrot, 1.f, 0.f, 0.f);
    glRotatef(player.Zrot, 0.f, 0.f, 1.f);
    glTranslatef(-player.X, -player.Y, -player.Z);    // Translate The Scene Based On Player Position

    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();

    glBindTexture(GL_TEXTURE_2D, Texture);

    glEnableClientState( GL_VERTEX_ARRAY );
    glEnableClientState( GL_NORMAL_ARRAY );
    glEnableClientState( GL_TEXTURE_COORD_ARRAY );

    glVertexPointer( 3, GL_DOUBLE, 0, &vertices[0] );
    glNormalPointer( GL_DOUBLE, 0, &normals[0] );
    glTexCoordPointer( 3, GL_DOUBLE, 0, &texcoords[0] );

    // Loop through chunks and render them
    int i, j, k;
    for(i = 0; i < terrain.sizeX; i++)
        for(j = 0; j < terrain.sizeY; j++)
            for(k = 0; k < terrain.sizeZ; k++)
                renderNode(terrain.GeneratedTerrain[Coord(i,j,k)], i*terrain.chunkSize, j*terrain.chunkSize, k*terrain.chunkSize, terrain.chunkSize);

    glDisableClientState(GL_VERTEX_ARRAY);
    glDisableClientState(GL_NORMAL_ARRAY);
    glDisableClientState(GL_TEXTURE_COORD_ARRAY);
}
<|endoftext|>


<commit_before>#include <GLFW/glfw3.h>
#include <vulkan/vulkan.h>

#include <vector>
#include <iostream>

#include "debug/pretty_print.hpp"
#include "utils/demangle.hpp"

int main()
{
	if ( ! glfwInit()) {
		std::cout << "Failed to initialize GLFW!" << std::endl;
		return -1;
	}

	if ( ! glfwVulkanSupported()) {
		std::cout << "Vulkan is not supported on this system!" << std::endl;
		return -2;
	}

	// Initialize Vulkan

	VkApplicationInfo app_info = {};
	{
		app_info.sType              = VK_STRUCTURE_TYPE_APPLICATION_INFO;
		app_info.pNext              = nullptr;
		app_info.pApplicationName   = "VkVoxels";
		app_info.applicationVersion = create_version(0, 0, 1);
		app_info.pEngineName        = "VkVoxels Engine";
		app_info.engineVersion      = create_version(0, 0, 1);
		app_info.apiVersion         = create_version(1, 0, 0);
	}

	VkInstanceCreateInfo instance_create_info = {};
	{
		int required_extension_count = 0;
		auto required_extension_names = glfwGetRequiredInstanceExtensions(&required_extension_count);
		if (required_extension_names != nullptr) {
			instance_create_info.sType                   = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
			instance_create_info.pNext                   = nullptr;
			instance_create_info.flags                   = 0;
			instance_create_info.pApplicationInfo        = &app_info;
			instance_create_info.enabledLayerCount       = 0;
			instance_create_info.ppEnabledLayerNames     = nullptr;
			instance_create_info.enabledExtensionCount   = required_extension_count;
			instance_create_info.ppEnabledExtensionNames = required_extension_names;
		} else {
			std::cout << "Error getting Vulkan extensions from GLFW!" << std::endl;
			return -3;
		}
	}

	VkInstance instance;
	if (vkCreateInstance(&instance_create_info, nullptr, &instance) != VK_SUCCESS) {
		std::cout << "Error creating Vulkan instance!" << std::endl;
		return -4;
	}

	std::vector<VkPhysicalDevice> phys_devices;
	std::vector<std::vector<VkQueueFamilyProperties>> phys_queue_families;
	// List available devices
	{
		// Get device count
		uint32_t phys_device_count = 0;
		vkEnumeratePhysicalDevices(instance, &phys_device_count, nullptr);

		// Get devices
		phys_devices.resize(phys_device_count);
		vkEnumeratePhysicalDevices(instance, &phys_device_count, phys_devices.data());

		// Iterate over devices
		for (const auto &phys_device : phys_devices) {
			std::cout << "Found physical device!" << std::endl;
			VkPhysicalDeviceProperties phys_device_props;
			vkGetPhysicalDeviceProperties(phys_device, &phys_device_props);
			std::cout << phys_device_props << std::endl;

			std::cout << "Device Queue Families:" << std::endl;

			// Get Queue count
			uint32_t queue_count = 0;
			vkGetPhysicalDeviceQueueFamilyProperties(phys_device, &queue_count, nullptr);

			// Get Queues
			std::vector<VkQueueFamilyProperties> queue_props(queue_count);
			vkGetPhysicalDeviceQueueFamilyProperties(phys_device, &queue_count, queue_props.data());

			auto queue_index = 0u;
			for (const auto &queue_prop : queue_props) {
				std::cout << "Queue Number " << queue_index++ << std::endl;
				std::cout << queue_prop << std::endl;
			}
		}
	}

	if (phys_devices.empty()) {
		std::cout << "Could not find any physical devices!" << std::endl;
		return -5;
	}

	// Create the logical Vulkan device
	VkDevice device;
	{
		const float queue_priorities[] = {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f};
		VkDeviceQueueCreateInfo queue_create_info = {};
		{
			queue_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
			queue_create_info.pNext = nullptr;
			queue_create_info.flags = 0;
			queue_create_info.queueFamilyIndex = 0;
			queue_create_info.queueCount = 8;
			queue_create_info.pQueuePriorities = queue_priorities;
		}

		VkPhysicalDeviceFeatures phys_device_features;
		vkGetPhysicalDeviceFeatures(phys_devices[0], &phys_device_features);

		VkDeviceCreateInfo device_create_info = {};
		{
			device_create_info.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
			device_create_info.pNext = nullptr;
			device_create_info.flags = 0;
			device_create_info.queueCreateInfoCount = 1;
			device_create_info.pQueueCreateInfos = &queue_create_info;
			device_create_info.enabledLayerCount = 0;
			device_create_info.ppEnabledLayerNames = nullptr;
			device_create_info.enabledExtensionCount = 0;
			device_create_info.ppEnabledExtensionNames = nullptr;
			device_create_info.pEnabledFeatures = &phys_device_features;
		}

		if (vkCreateDevice(phys_devices[0], &device_create_info, nullptr, &device) != VK_SUCCESS) {
			std::cout << "Failed to create logical device!" << std::endl;
			return -6;
		}
	}

	vkDestroyDevice(device, nullptr);
	vkDestroyInstance(instance, nullptr);
	glfwTerminate();
	return 0;
}
<commit_msg>[General] Fix struct definition code alignment<commit_after>#include <GLFW/glfw3.h>
#include <vulkan/vulkan.h>

#include <vector>
#include <iostream>

#include "debug/pretty_print.hpp"
#include "utils/demangle.hpp"

int main()
{
	if ( ! glfwInit()) {
		std::cout << "Failed to initialize GLFW!" << std::endl;
		return -1;
	}

	if ( ! glfwVulkanSupported()) {
		std::cout << "Vulkan is not supported on this system!" << std::endl;
		return -2;
	}

	// Initialize Vulkan

	VkApplicationInfo app_info = {};
	{
		app_info.sType              = VK_STRUCTURE_TYPE_APPLICATION_INFO;
		app_info.pNext              = nullptr;
		app_info.pApplicationName   = "VkVoxels";
		app_info.applicationVersion = create_version(0, 0, 1);
		app_info.pEngineName        = "VkVoxels Engine";
		app_info.engineVersion      = create_version(0, 0, 1);
		app_info.apiVersion         = create_version(1, 0, 0);
	}

	VkInstanceCreateInfo instance_create_info = {};
	{
		int required_extension_count = 0;
		auto required_extension_names = glfwGetRequiredInstanceExtensions(&required_extension_count);
		if (required_extension_names != nullptr) {
			instance_create_info.sType                   = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
			instance_create_info.pNext                   = nullptr;
			instance_create_info.flags                   = 0;
			instance_create_info.pApplicationInfo        = &app_info;
			instance_create_info.enabledLayerCount       = 0;
			instance_create_info.ppEnabledLayerNames     = nullptr;
			instance_create_info.enabledExtensionCount   = required_extension_count;
			instance_create_info.ppEnabledExtensionNames = required_extension_names;
		} else {
			std::cout << "Error getting Vulkan extensions from GLFW!" << std::endl;
			return -3;
		}
	}

	VkInstance instance;
	if (vkCreateInstance(&instance_create_info, nullptr, &instance) != VK_SUCCESS) {
		std::cout << "Error creating Vulkan instance!" << std::endl;
		return -4;
	}

	std::vector<VkPhysicalDevice> phys_devices;
	std::vector<std::vector<VkQueueFamilyProperties>> phys_queue_families;
	// List available devices
	{
		// Get device count
		uint32_t phys_device_count = 0;
		vkEnumeratePhysicalDevices(instance, &phys_device_count, nullptr);

		// Get devices
		phys_devices.resize(phys_device_count);
		vkEnumeratePhysicalDevices(instance, &phys_device_count, phys_devices.data());

		// Iterate over devices
		for (const auto &phys_device : phys_devices) {
			std::cout << "Found physical device!" << std::endl;
			VkPhysicalDeviceProperties phys_device_props;
			vkGetPhysicalDeviceProperties(phys_device, &phys_device_props);
			std::cout << phys_device_props << std::endl;

			std::cout << "Device Queue Families:" << std::endl;

			// Get Queue count
			uint32_t queue_count = 0;
			vkGetPhysicalDeviceQueueFamilyProperties(phys_device, &queue_count, nullptr);

			// Get Queues
			std::vector<VkQueueFamilyProperties> queue_props(queue_count);
			vkGetPhysicalDeviceQueueFamilyProperties(phys_device, &queue_count, queue_props.data());

			auto queue_index = 0u;
			for (const auto &queue_prop : queue_props) {
				std::cout << "Queue Number " << queue_index++ << std::endl;
				std::cout << queue_prop << std::endl;
			}
		}
	}

	if (phys_devices.empty()) {
		std::cout << "Could not find any physical devices!" << std::endl;
		return -5;
	}

	// Create the logical Vulkan device
	VkDevice device;
	{
		const float queue_priorities[] = {1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f, 1.f};
		VkDeviceQueueCreateInfo queue_create_info = {};
		{
			queue_create_info.sType            = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
			queue_create_info.pNext            = nullptr;
			queue_create_info.flags            = 0;
			queue_create_info.queueFamilyIndex = 0;
			queue_create_info.queueCount       = 8;
			queue_create_info.pQueuePriorities = queue_priorities;
		}

		VkPhysicalDeviceFeatures phys_device_features;
		vkGetPhysicalDeviceFeatures(phys_devices[0], &phys_device_features);

		VkDeviceCreateInfo device_create_info = {};
		{
			device_create_info.sType                   = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
			device_create_info.pNext                   = nullptr;
			device_create_info.flags                   = 0;
			device_create_info.queueCreateInfoCount    = 1;
			device_create_info.pQueueCreateInfos       = &queue_create_info;
			device_create_info.enabledLayerCount       = 0;
			device_create_info.ppEnabledLayerNames     = nullptr;
			device_create_info.enabledExtensionCount   = 0;
			device_create_info.ppEnabledExtensionNames = nullptr;
			device_create_info.pEnabledFeatures        = &phys_device_features;
		}

		if (vkCreateDevice(phys_devices[0], &device_create_info, nullptr, &device) != VK_SUCCESS) {
			std::cout << "Failed to create logical device!" << std::endl;
			return -6;
		}
	}

	vkDestroyDevice(device, nullptr);
	vkDestroyInstance(instance, nullptr);
	glfwTerminate();
	return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include "fastqreader.h"
#include "unittest.h"
#include "mutscan.h"
#include <time.h>
#include "cmdline.h"

int main(int argc, char* argv[]){
    if (argc == 2 && strcmp(argv[1], "test")==0){
        UnitTest tester;
        tester.run();
        return 0;
    }
    cmdline::parser cmd;
    cmd.add<string>("read1", '1', "read1 file name", true, "");
    cmd.add<string>("read2", '2', "read2 file name", false, "");
    cmd.add<string>("mutation", 'm', "mutation file name", false, "");
    cmd.add<string>("html", 'h', "filename of html report, no html report if not specified", false, "");
    cmd.add<int>("thread", 't', "worker thread number, default is 4", false, 4);
    cmd.parse_check(argc, argv);
    string r1file = cmd.get<string>("read1");
    string r2file = cmd.get<string>("read2");
    string mutationFile = cmd.get<string>("mutation");
    string html = cmd.get<string>("html");
    int threadNum = cmd.get<int>("thread");

    clock_t t1 = clock();
    MutScan scanner(mutationFile, r1file, r2file, html, threadNum);
    scanner.scan();
    clock_t t2 = clock();
    printf("\nTime used: %f ms\n", (t2-t1)/1000.0);
}<commit_msg>add version number<commit_after>#include <stdio.h>
#include "fastqreader.h"
#include "unittest.h"
#include "mutscan.h"
#include <time.h>
#include "cmdline.h"

#define MUTSCAN_VER "1.1.0"

int main(int argc, char* argv[]){
    if (argc == 2 && strcmp(argv[1], "test")==0){
        UnitTest tester;
        tester.run();
        return 0;
    }
    cmdline::parser cmd;
    cmd.add<string>("read1", '1', "read1 file name", true, "");
    cmd.add<string>("read2", '2', "read2 file name", false, "");
    cmd.add<string>("mutation", 'm', "mutation file name", false, "");
    cmd.add<string>("html", 'h', "filename of html report, no html report if not specified", false, "");
    cmd.add<int>("thread", 't', "worker thread number, default is 4", false, 4);
    cmd.parse_check(argc, argv);
    string r1file = cmd.get<string>("read1");
    string r2file = cmd.get<string>("read2");
    string mutationFile = cmd.get<string>("mutation");
    string html = cmd.get<string>("html");
    int threadNum = cmd.get<int>("thread");

    clock_t t1 = clock();
    MutScan scanner(mutationFile, r1file, r2file, html, threadNum);
    scanner.scan();
    clock_t t2 = clock();
    printf("\nMutscan v%s, time used: %f ms\n", MUTSCAN_VER, (t2-t1)/1000.0);
}<|endoftext|>


<commit_before>#include <iostream>
#include <getopt.h>

#include "registrar.h"
#include "tree.h"
#include "utils.h"

// NOTE: there is no reason to clean this up either. This is just the test
// driver.

// The eventual merge into DASHMM will use the position member of Source and
// Target. Hence the following.
struct Source {
  Point position;
};

struct Target {
  Point position;
};

template <typename A, typename B>
class Stub {
};

template <typename A, typename B, template <typename, typename> class C,
          typename D>
class Stump {
};

// Register the actions with the runtime
Registrar<Source, Target, Stub, Stump, int> reg{};

using dualtree_t = DualTree<Source, Target, Stub, Stump, int>;

void usage(std::string exec) {
  std::cout << "Usage: " << exec << " --scaling=[w/s] "
            << "--datatype=[c/s] "
            << "--nsrc=num " << "--ntar=num "
            << "--threshold=num " << "--nseed=num " << std::endl;
  std::cout << "Note: --nseed=num required if --scaling=s" << std::endl;
}

/// The main action of the code starts here
int main_handler(int threshold, hpx_addr_t source_gas, hpx_addr_t target_gas) {
  Array<Source> sources{source_gas};
  Array<Target> targets{target_gas};

  hpx_time_t timer_start = hpx_time_now();

  // Perform some basic setup
  RankWise<dualtree_t> global_tree =
      dualtree_t::create(threshold, sources, targets);
  hpx_time_t timer_middle = hpx_time_now();

  // Start the partitioning proper
  hpx_addr_t partdone = dualtree_t::partition(global_tree, sources, targets);
  hpx_lco_wait(partdone);
  hpx_lco_delete_sync(partdone);
  hpx_time_t timer_end = hpx_time_now();

  // All done, spit out some timing information before cleaning up and halting
  double elapsed_total = hpx_time_diff_ms(timer_start, timer_end) / 1e3;
  double elapsed_setup = hpx_time_diff_ms(timer_start, timer_middle) / 1e3;
  double elapsed_dual = hpx_time_diff_ms(timer_middle, timer_end) / 1e3;
  std::cout << "Dual tree creation time: " << elapsed_total << "\n";
  std::cout << "  Setup: " << elapsed_setup << "\n";
  std::cout << "  Partition: " << elapsed_dual << "\n";

  // Here we clean up the allocated resources
  dualtree_t::destroy(global_tree);

  hpx_exit(0, nullptr);
}
HPX_ACTION(HPX_DEFAULT, 0, main_action, main_handler,
           HPX_INT, HPX_ADDR, HPX_ADDR);

int main(int argc, char *argv[]) {
  // default values
  char scaling = 'w'; // strong scale, 'w' for weak scaling
  char datatype = 'c'; // cubic point distribution, 's' for sphere distrbution
  int nsrc = 20; // total number of sources for strong scaling
                 // number of sources per rank for weak scaling
  int ntar = 20;
  int threshold = 1;
  int nseed = -1; // Number of seeds used for generating input for strong

  if (hpx_init(&argc, &argv)) {
    std::cout << "HPX: failed to initialize" << std::endl;
  }

  // Parse command line
  int opt = 0;
  static struct option long_options[] = {
    {"scaling", required_argument, 0, 's'},
    {"datatype", required_argument, 0, 'd'},
    {"nsrc", required_argument, 0, 'n'},
    {"ntar", required_argument, 0, 'm'},
    {"threshold", required_argument, 0, 'l'},
    {"nseed", required_argument, 0, 'r'},
    {"help", no_argument, 0, 'h'},
    {0, 0, 0, 0}
  };

  int long_index = 0;
  bool valid_arguments = true;
  while ((opt = getopt_long(argc, argv, "s:d:e:n:m:l:r:h",
                            long_options, &long_index)) != -1) {
    switch (opt) {
    case 's':
      scaling = *optarg;
      break;
    case 'd':
      datatype = *optarg;
      break;
    case 'n':
      nsrc = atoi(optarg);
      break;
    case 'm':
      ntar = atoi(optarg);
      break;
    case 'l':
      threshold = atoi(optarg);
      break;
    case 'r':
      nseed = atoi(optarg);
      break;
    case 'h':
      usage(std::string{argv[0]});
      valid_arguments = false;
      break;
    }
  }

  if (scaling == 's') {
    // For strong scaling test, @p nseed must be overwritten.
    if (nseed <= 0) {
      valid_arguments = false;
      usage(std::string{argv[0]});
    }
  }

  if (!valid_arguments) {
    hpx_finalize();
    return -1;
  }

  // First get the data setup
  Array<Source> sources = generate_points<Source>(scaling, datatype,
                                          nsrc, nseed, 0);
  Array<Target> targets = generate_points<Target>(scaling, datatype,
                                          ntar, nseed, nseed);

  // Then build the tree
  hpx_addr_t ssend = sources.data();  // TODO: this will eventually disappear
  hpx_addr_t tsend = targets.data();  // behind an interface
  if (hpx_run(&main_action, nullptr, &threshold, &ssend, &tsend)) {
    std::cout << "Failed to run main action" << std::endl;
  }

  // Then delete the point data
  sources.destroy();
  targets.destroy();

  hpx_finalize();

  return 0;
}
<commit_msg>S == T case seems functional. Should perhaps check the results somehow.<commit_after>#include <iostream>
#include <getopt.h>

#include "registrar.h"
#include "tree.h"
#include "utils.h"

// NOTE: there is no reason to clean this up either. This is just the test
// driver.

// The eventual merge into DASHMM will use the position member of Source and
// Target. Hence the following.
struct Source {
  Point position;
};

template <typename A, typename B>
class Stub {
};

template <typename A, typename B, template <typename, typename> class C,
          typename D>
class Stump {
};

// Register the actions with the runtime
Registrar<Source, Source, Stub, Stump, int> reg{};

using dualtree_t = DualTree<Source, Source, Stub, Stump, int>;

void usage(std::string exec) {
  std::cout << "Usage: " << exec << " --scaling=[w/s] "
            << "--datatype=[c/s] "
            << "--nsrc=num " << "--ntar=num "
            << "--threshold=num " << "--nseed=num "
            << "--samesandt " << std::endl;
  std::cout << "Note: --nseed=num required if --scaling=s" << std::endl;
}

/// The main action of the code starts here
int main_handler(int threshold, hpx_addr_t source_gas, hpx_addr_t target_gas) {
  Array<Source> sources{source_gas};
  Array<Source> targets{target_gas};

  hpx_time_t timer_start = hpx_time_now();

  // Perform some basic setup
  RankWise<dualtree_t> global_tree =
      dualtree_t::create(threshold, sources, targets);
  hpx_time_t timer_middle = hpx_time_now();

  // Start the partitioning proper
  hpx_addr_t partdone = dualtree_t::partition(global_tree, sources, targets);
  hpx_lco_wait(partdone);
  hpx_lco_delete_sync(partdone);
  hpx_time_t timer_end = hpx_time_now();

  // All done, spit out some timing information before cleaning up and halting
  double elapsed_total = hpx_time_diff_ms(timer_start, timer_end) / 1e3;
  double elapsed_setup = hpx_time_diff_ms(timer_start, timer_middle) / 1e3;
  double elapsed_dual = hpx_time_diff_ms(timer_middle, timer_end) / 1e3;
  std::cout << "Dual tree creation time: " << elapsed_total << "\n";
  std::cout << "  Setup: " << elapsed_setup << "\n";
  std::cout << "  Partition: " << elapsed_dual << "\n";

  // Here we clean up the allocated resources
  dualtree_t::destroy(global_tree);

  hpx_exit(0, nullptr);
}
HPX_ACTION(HPX_DEFAULT, 0, main_action, main_handler,
           HPX_INT, HPX_ADDR, HPX_ADDR);

int main(int argc, char *argv[]) {
  // default values
  char scaling = 'w'; // strong scale, 'w' for weak scaling
  char datatype = 'c'; // cubic point distribution, 's' for sphere distrbution
  int nsrc = 20; // total number of sources for strong scaling
                 // number of sources per rank for weak scaling
  int ntar = 20;
  int threshold = 1;
  int nseed = -1; // Number of seeds used for generating input for strong
  int samesandt = 0;

  if (hpx_init(&argc, &argv)) {
    std::cout << "HPX: failed to initialize" << std::endl;
  }

  // Parse command line
  int opt = 0;
  static struct option long_options[] = {
    {"scaling", required_argument, 0, 's'},
    {"datatype", required_argument, 0, 'd'},
    {"nsrc", required_argument, 0, 'n'},
    {"ntar", required_argument, 0, 'm'},
    {"threshold", required_argument, 0, 'l'},
    {"nseed", required_argument, 0, 'r'},
    {"help", no_argument, 0, 'h'},
    {"samesandt", no_argument, 0, 'w'},
    {0, 0, 0, 0}
  };

  int long_index = 0;
  bool valid_arguments = true;
  while ((opt = getopt_long(argc, argv, "s:d:e:n:m:l:r:h:w",
                            long_options, &long_index)) != -1) {
    switch (opt) {
    case 'd':
      datatype = *optarg;
      break;
    case 'h':
      usage(std::string{argv[0]});
      valid_arguments = false;
      break;
    case 'l':
      threshold = atoi(optarg);
      break;
    case 'm':
      ntar = atoi(optarg);
      break;
    case 'n':
      nsrc = atoi(optarg);
      break;
    case 'r':
      nseed = atoi(optarg);
      break;
    case 's':
      scaling = *optarg;
      break;
    case 'w':
      samesandt = 1;
      break;
    }
  }

  if (scaling == 's') {
    // For strong scaling test, @p nseed must be overwritten.
    if (nseed <= 0) {
      valid_arguments = false;
      usage(std::string{argv[0]});
    }
  }

  if (!valid_arguments) {
    hpx_finalize();
    return -1;
  }

  // First get the data setup
  Array<Source> sources = generate_points<Source>(scaling, datatype,
                                          nsrc, nseed, 0);
  Array<Source> targets{};
  if (samesandt) {
    targets = sources;
  } else {
    targets = generate_points<Source>(scaling, datatype, ntar, nseed, nseed);
  }

  // Then build the tree
  hpx_addr_t ssend = sources.data();  // TODO: this will eventually disappear
  hpx_addr_t tsend = targets.data();  // behind an interface
  if (hpx_run(&main_action, nullptr, &threshold, &ssend, &tsend)) {
    std::cout << "Failed to run main action" << std::endl;
  }

  // Then delete the point data
  sources.destroy();
  if (!samesandt) {
    targets.destroy();
  }

  hpx_finalize();

  return 0;
}
<|endoftext|>


<commit_before>/* Copyright (c) 2016 Tobias Koelsch
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "Utf8Codec.h"

static const misc::ConstStringRef utf8EncodingName("UTF-8");

static unicode::ParseResult computeCharSize(unicode::Utf32Char& firstCharValue, char firstChar) noexcept
{
  if((firstChar & 0x80) == 0) {
    firstCharValue = firstChar;
    return unicode::ParseResult(1);
  }
  if((firstChar & 0x40) != 0x40) {
    firstCharValue = 0;
    return unicode::ParseResult::InvalidCharacter;
  }
  if((firstChar & 0x20) == 0x00) {
    firstCharValue = firstChar & 0x1F;
    return unicode::ParseResult(2);
  }
  if((firstChar & 0x10) == 0x00) {
    firstCharValue = firstChar & 0x0F;
    return unicode::ParseResult(3);
  }
  if((firstChar & 0x08) == 0x00) {
    firstCharValue = firstChar & 0x07;
    return unicode::ParseResult(4);
  }
  firstCharValue = 0;
  return unicode::ParseResult::InvalidCharacter;
}

unicode::ParseResult unicode::Utf8Codec::parseNext(Utf32Char& chr, const char* data, const char* dataEnd) noexcept
{
  if(data == dataEnd) {
    return ParseResult::IncompleteCharacter;
  }
  Utf32Char tmpChr;
  const int32_t charSize = static_cast<int32_t>(computeCharSize(tmpChr, *data));
  if(charSize < 0) {
    return static_cast<ParseResult>(charSize);
  }
  if(static_cast<std::size_t>(charSize) > 4) {
    return ParseResult::InvalidCharacter;
  }
  if(data + static_cast<std::size_t>(charSize) > dataEnd) {
    return ParseResult::IncompleteCharacter;
  }
  for(int32_t pos = 1; pos < charSize; ++pos) {
    ++data;
    if((*data & 0xC0) != 0x80) {
      return ParseResult::InvalidCharacter;
    }
    tmpChr <<= 6;
    tmpChr |= *data & 0x3F;
  }
  switch(charSize) {
  case 2:
    if(tmpChr < 0x80) {
      return ParseResult::InvalidCharacter;
    }
    break;
  case 3:
    if(tmpChr < 0x800) {
      return ParseResult::InvalidCharacter;
    }
    break;
  case 4:
    if(tmpChr < 0x10000) {
      return ParseResult::InvalidCharacter;
    }
    break;
  }
  if(0xD800 <= tmpChr && tmpChr <= 0xDFFF) {
    return ParseResult::InvalidCharacter;
  }
  if(tmpChr > 0x10FFFF) {
    return ParseResult::InvalidCharacter;
  }

  chr = tmpChr;
  return static_cast<ParseResult>(charSize);
}

bool unicode::Utf8Codec::isAscii(const char c) noexcept
{
  return (c & 0x80) == 0;
}

unicode::ParseResult unicode::Utf8Codec::encodeChar(const unicode::Utf32Char chr, char* bufStart, const char* bufEnd) noexcept
{
  if(chr > 0x10FFFF)                 { return ParseResult::InvalidCharacter; }
  if(0xD800 <= chr && chr <= 0xDFFF) { return ParseResult::InvalidCharacter; }

  const uint bufSize = bufEnd - bufStart;
  // 0xxx xxxx
  if(chr <= 0x7F) {
    if(bufStart != nullptr) {
      if(bufSize < 1) { return ParseResult::IncompleteCharacter; }
      bufStart[0] = chr;
    }
    return ParseResult(1);
  }
  // 110x xxxx 10xx xxxx
  if(chr <= 0x07FF) {
    if(bufStart != nullptr) {
      if(bufSize < 2) { return ParseResult::IncompleteCharacter; }
      bufStart[0] = 0xC0 |  chr >> 6;
      bufStart[1] = 0x80 | (chr & 0x3F);
    }
    return ParseResult(2);
  }
  // 1110 xxxx 10xx xxxx 10xx xxxx
  if(chr <= 0xFFFF) {
    if(bufStart != nullptr) {
      if(bufSize < 3) { return ParseResult::IncompleteCharacter; }
      bufStart[0] = 0xE0 |   chr >> 12;
      bufStart[1] = 0x80 | ((chr >>  6) & 0x3F);
      bufStart[2] = 0x80 |  (chr        & 0x3F);
    }
    return ParseResult(3);
  }
  // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
  if(bufStart != nullptr) {
    if(bufSize < 4) { return ParseResult::IncompleteCharacter; }
    bufStart[0] = 0xF0 |   chr >> 18;
    bufStart[1] = 0x80 | ((chr >> 12) & 0x3F);
    bufStart[2] = 0x80 | ((chr >>  6) & 0x3F);
    bufStart[3] = 0x80 |  (chr        & 0x3F);
  }
  return ParseResult(4);
}

unicode::ParseResult unicode::Utf8Codec::appendChar(std::string& out, const unicode::Utf32Char chr)
{
  char buf[4];
  const ParseResult res = encodeChar(chr, buf, buf+4);
  if(isError(res)) {
    return res;
  }
  out.append(buf, buf+static_cast<int32_t>(res));
  return res;
}

bool unicode::Utf8Codec::hasBom(const char* data, const char* dataEnd) noexcept
{
  if(data + 3 > dataEnd) {
    return false;
  }
  return data[0] == char(0xEF)
      && data[1] == char(0xBB)
      && data[2] == char(0xBF);
}

bool unicode::Utf8Codec::isSupportedEncoding(const misc::ConstStringRef& encodingString) noexcept
{
  return encodingString == utf8EncodingName;
}
<commit_msg>improve parsing performance by giving precedence to probable cases<commit_after>/* Copyright (c) 2016 Tobias Koelsch
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

#include "Utf8Codec.h"

static const misc::ConstStringRef utf8EncodingName("UTF-8");

static unicode::ParseResult computeCharSize(unicode::Utf32Char& firstCharValue, char firstChar) noexcept
{
//  8421 8421
//  0xxx xxxx
//  110x xxxx xxxx xxxx
//  1110 xxxx xxxx xxxx xxxx xxxx
//  1111 0xxx xxxx xxxx xxxx xxxx xxxx xxxx

  if((firstChar & 0x80) == 0) {
    firstCharValue = firstChar;
    return unicode::ParseResult(1);
  }

  if((firstChar & 0x80) == 0) {
    firstCharValue = firstChar;
    return unicode::ParseResult(1);
  }
  if((firstChar & 0x40) != 0x40) {
    firstCharValue = 0;
    return unicode::ParseResult::InvalidCharacter;
  }
  if((firstChar & 0x20) == 0x00) {
    firstCharValue = firstChar & 0x1F;
    return unicode::ParseResult(2);
  }
  if((firstChar & 0x10) == 0x00) {
    firstCharValue = firstChar & 0x0F;
    return unicode::ParseResult(3);
  }
  if((firstChar & 0x08) == 0x00) {
    firstCharValue = firstChar & 0x07;
    return unicode::ParseResult(4);
  }
  firstCharValue = 0;
  return unicode::ParseResult::InvalidCharacter;
}

unicode::ParseResult unicode::Utf8Codec::parseNext(Utf32Char& chr, const char* data, const char* dataEnd) noexcept
{
  if(data == dataEnd) {
    return ParseResult::IncompleteCharacter;
  }
  Utf32Char tmpChr;
  const int32_t charSize = static_cast<int32_t>(computeCharSize(tmpChr, *data));
  if(charSize == 1) {
    chr = tmpChr;
    return static_cast<ParseResult>(charSize);
  }
  if(charSize < 0) {
    return static_cast<ParseResult>(charSize);
  }
  if(data + static_cast<std::size_t>(charSize) > dataEnd) {
    return ParseResult::IncompleteCharacter;
  }
  for(int32_t pos = 1; pos < charSize; ++pos) {
    ++data;
    if((*data & 0xC0) != 0x80) {
      return ParseResult::InvalidCharacter;
    }
    tmpChr <<= 6;
    tmpChr |= *data & 0x3F;
  }
  if(static_cast<std::size_t>(charSize) > 4) {
    return ParseResult::InvalidCharacter;
  }
  switch(charSize) {
  case 2:
    if(tmpChr < 0x80) {
      return ParseResult::InvalidCharacter;
    }
    break;
  case 3:
    if(tmpChr < 0x800) {
      return ParseResult::InvalidCharacter;
    }
    if(0xD800 <= tmpChr && tmpChr <= 0xDFFF) {
      return ParseResult::InvalidCharacter;
    }
    break;
  case 4:
    if(tmpChr < 0x10000) {
      return ParseResult::InvalidCharacter;
    }
    if(tmpChr > 0x10FFFF) {
      return ParseResult::InvalidCharacter;
    }
    break;
  }

  chr = tmpChr;
  return static_cast<ParseResult>(charSize);
}

bool unicode::Utf8Codec::isAscii(const char c) noexcept
{
  return (c & 0x80) == 0;
}

unicode::ParseResult unicode::Utf8Codec::encodeChar(const unicode::Utf32Char chr, char* bufStart, const char* bufEnd) noexcept
{
  const uint bufSize = bufEnd - bufStart;
  // 0xxx xxxx
  if(chr <= 0x7F) {
    if(bufStart != nullptr) {
      if(bufSize < 1) { return ParseResult::IncompleteCharacter; }
      bufStart[0] = chr;
    }
    return ParseResult(1);
  }

  // 110x xxxx 10xx xxxx
  if(chr <= 0x07FF) {
    if(bufStart != nullptr) {
      if(bufSize < 2) { return ParseResult::IncompleteCharacter; }
      bufStart[0] = 0xC0 |  chr >> 6;
      bufStart[1] = 0x80 | (chr & 0x3F);
    }
    return ParseResult(2);
  }

  if(chr > 0x10FFFF)                 { return ParseResult::InvalidCharacter; }

  // 1110 xxxx 10xx xxxx 10xx xxxx
  if(chr <= 0xFFFF) {
    if(bufStart != nullptr) {
      if(0xD800 <= chr && chr <= 0xDFFF) { return ParseResult::InvalidCharacter; }
      if(bufSize < 3) { return ParseResult::IncompleteCharacter; }
      bufStart[0] = 0xE0 |   chr >> 12;
      bufStart[1] = 0x80 | ((chr >>  6) & 0x3F);
      bufStart[2] = 0x80 |  (chr        & 0x3F);
    }
    return ParseResult(3);
  }
  // 1111 0xxx 10xx xxxx 10xx xxxx 10xx xxxx
  if(bufStart != nullptr) {
    if(bufSize < 4) { return ParseResult::IncompleteCharacter; }
    bufStart[0] = 0xF0 |   chr >> 18;
    bufStart[1] = 0x80 | ((chr >> 12) & 0x3F);
    bufStart[2] = 0x80 | ((chr >>  6) & 0x3F);
    bufStart[3] = 0x80 |  (chr        & 0x3F);
  }
  return ParseResult(4);
}

unicode::ParseResult unicode::Utf8Codec::appendChar(std::string& out, const unicode::Utf32Char chr)
{
  char buf[4];
  const ParseResult res = encodeChar(chr, buf, buf+4);
  if(isError(res)) {
    return res;
  }
  out.append(buf, buf+static_cast<int32_t>(res));
  return res;
}

bool unicode::Utf8Codec::hasBom(const char* data, const char* dataEnd) noexcept
{
  if(data + 3 > dataEnd) {
    return false;
  }
  return data[0] == char(0xEF)
      && data[1] == char(0xBB)
      && data[2] == char(0xBF);
}

bool unicode::Utf8Codec::isSupportedEncoding(const misc::ConstStringRef& encodingString) noexcept
{
  return encodingString == utf8EncodingName;
}
<|endoftext|>


<commit_before>/// \file main.cpp
///
/// \brief Defines main().
///
/// This file defines a main() function that forms the basis of a command-line
/// executable.
///
#include "template.hpp"
///
/// \brief Main program.
///
/// This function only exists to call desitemplate::version() and print its return value.
///
/// Note that the documentation for this function is here, rather than in
/// template.hpp, because main is not part of the namespace.  Nor is the
/// declaration of main() needed by the other functions.
///
/// \param argc Number of command line options.
/// \param argv The command line options.
///
/// \return The exit status that will be returned to the shell.
///
int main(int argc, char **argv)
{
    std::string tagURL("$HeadURL: https://desi.lbl.gov/svn/code/tools/desitemplate_cpp/tags/0.0.2/src/main.cpp $");
    std::string branchURL("$HeadURL: https://desi.lbl.gov/svn/code/tools/desitemplate_cpp/branches/test-coverage/src/main.cpp $");
    std::string trunkURL("$HeadURL: https://desi.lbl.gov/svn/code/tools/desitemplate_cpp/trunk/src/main.cpp $");
    std::cout << "Test SVN tag version: " << desitemplate::svn_version(tagURL) << std::endl;
    // std::cout << "Test SVN branch version: " << desitemplate::svn_version(branchURL) << std::endl;
    // std::cout << "Test SVN trunk version: " << desitemplate::svn_version(branchURL) << std::endl;
    std::cout << "Test GIT version: " << desitemplate::version() << std::endl;
    return 0;
}
<commit_msg>add test of parse_version<commit_after>/// \file main.cpp
///
/// \brief Defines main().
///
/// This file defines a main() function that forms the basis of a command-line
/// executable.
///
#include "template.hpp"
///
/// \brief Main program.
///
/// This function only exists to call desitemplate::version() and print its return value.
///
/// Note that the documentation for this function is here, rather than in
/// template.hpp, because main is not part of the namespace.  Nor is the
/// declaration of main() needed by the other functions.
///
/// \param argc Number of command line options.
/// \param argv The command line options.
///
/// \return The exit status that will be returned to the shell.
///
int main(int argc, char **argv)
{
    std::string version1("1.2.3.4");
    int parse_version_result[4];
    desitemplate::parse_version(parse_version_result, version1);
    for (int i = 0; i < 4; i++) {
        if (parse_version_result[i] != i+1) {
            std::cerr << "ERROR: parsed_version[" << i << "] != " << i+1 << std::endl;
            return 1;
        }
    }
    std::string tagURL("$HeadURL: https://desi.lbl.gov/svn/code/tools/desitemplate_cpp/tags/0.0.2/src/main.cpp $");
    std::string branchURL("$HeadURL: https://desi.lbl.gov/svn/code/tools/desitemplate_cpp/branches/test-coverage/src/main.cpp $");
    std::string trunkURL("$HeadURL: https://desi.lbl.gov/svn/code/tools/desitemplate_cpp/trunk/src/main.cpp $");
    std::cout << "Test SVN tag version: " << desitemplate::svn_version(tagURL) << std::endl;
    // std::cout << "Test SVN branch version: " << desitemplate::svn_version(branchURL) << std::endl;
    // std::cout << "Test SVN trunk version: " << desitemplate::svn_version(branchURL) << std::endl;
    std::cout << "Test GIT version: " << desitemplate::version() << std::endl;
    return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <vector>

#include "World.h"
#include "Renderer.h"
#include "ForwardRasterizer.h"
#include "DeferredRasterizer.h"
#include "Camera.h"
#include "Light.h"
#include "DirectionalLight.h"
#include "PointLight.h"
#include "OrthographicCamera.h"
#include "PerspectiveCamera.h"
#include "Constants.h"

// Forward declaration utils functions
void buildAlignedBox(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side);
GeometryObject* buildPlainBox(Material* material, const RGBColor& color, const Point3D& center, const float side);
GeometryObject* buildTexturedBox(Material* material, const Point3D& center, const float side);

void buildHorizontalPlane(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side);
GeometryObject* buildTexturedPlane(Material* material, const Point3D& center, const float side);
GeometryObject* buildPlainPlane(Material* material, const RGBColor& color, const Point3D& center, const float side);
GeometryObject* buildMultiColorBox(Material* material, const Point3D& center, const float side);

const std::vector<GeometryObject*> setupFlatScene();
const std::vector<GeometryObject*> setupTexturedScene();

Camera * camera;
Renderer * renderer;
int main (){
  std::vector<Light*> lights = {
    new DirectionalLight(Colors::WHITE, Vector3D(1, 0.4, -1))
  };
  const std::vector<GeometryObject*> objects_flat = setupFlatScene();
  const std::vector<GeometryObject*> objects_textured = setupTexturedScene();

  World * world = new World(objects_flat, lights, camera);
#ifdef _FORWARD
  renderer = new ForwardRasterizer(world);
#endif

#ifdef _DEFERRED
  renderer = new DeferredRasterizer(world);
#endif

#ifdef _ORTHOGRAPHIC
  camera = new OrthographicCamera(CAMERA_POS, CAMERA_TARGET, IMAGE_HEIGHT, IMAGE_WIDTH, renderer);
#endif

#ifdef _PERSPECTIVE
  camera = new PerspectiveCamera(CAMERA_POS, CAMERA_TARGET, IMAGE_HEIGHT, IMAGE_WIDTH, renderer);
#endif
  world->m_camera = camera;
  renderer->render();
  renderer->export_output(IMAGE_NAME);
  return 0;
}

const std::vector<GeometryObject*> setupFlatScene() {
  std::vector<GeometryObject*> objects;

  // Objects

  GeometryObject* ground = buildPlainPlane(Materials::FLAT_PLASTIC, Colors::GREY, Point3D(0, 0, 0), 500);
  objects.push_back(ground);

  GeometryObject* flat_box = buildPlainBox(Materials::FLAT_PLASTIC, Colors::RED, Point3D(0, 0, 0), 100);
  flat_box->translate(Vector3D(150, 50, 100));
  flat_box->rotate(0, 45, 0);
  objects.push_back(flat_box);

  GeometryObject* flat_box2 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::CYAN, Point3D(150, 125, 100), 50);
  objects.push_back(flat_box2);

  GeometryObject* flying_box = buildPlainBox(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(-100, 120, 75), 75);
  flying_box->rotate(45, -45, 45);
  objects.push_back(flying_box);

  GeometryObject* multicolor_box = buildMultiColorBox(Materials::FLAT_PLASTIC, Point3D(-100, 50, -90), 100);
  multicolor_box->rotate(0, -45, 0);
  objects.push_back(multicolor_box);

  GeometryObject* small_box2 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::PURPLE, Point3D(150, 37.5, -220), 75);
  objects.push_back(small_box2);
  return objects;
}

const std::vector<GeometryObject*> setupTexturedScene() {
  std::vector<GeometryObject*> objects;

  // Objects
  GeometryObject* ground = buildTexturedPlane(Materials::BRICK, Point3D(0, 0, 0), 500);
  objects.push_back(ground);

  GeometryObject* flat_box = buildTexturedBox(Materials::BOX, Point3D(0, 0, 0), 100);
  flat_box->translate(Vector3D(150, 50, 100));
  flat_box->rotate(0, 45, 0);
  objects.push_back(flat_box);

  GeometryObject* flat_box2 = buildTexturedBox(Materials::BOX, Point3D(150, 125, 100), 50);
  objects.push_back(flat_box2);

  GeometryObject* flying_box = buildTexturedBox(Materials::BOX, Point3D(-100, 120, 75), 75);
  flying_box->rotate(45, -45, 45);
  objects.push_back(flying_box);

  GeometryObject* small_box1 = buildTexturedBox(Materials::BOX, Point3D(-100, 50, -90), 100);
  small_box1->rotate(0, -45, 0);
  objects.push_back(small_box1);

  GeometryObject* default_box = buildTexturedBox(Materials::DEFAULT, Point3D(150, 37.5, -220), 75);
  objects.push_back(default_box);

  return objects;
}

void buildAlignedBox(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side) {
  const float half_diagonal = (side / 2) / sin(PI / 2); // Distance to center
                                                        // Front
  const Point3D v1(-half_diagonal, -half_diagonal, -half_diagonal);
  const Point3D v2(v1.x, v1.y + side, v1.z);
  const Point3D v3(v1.x + side, v1.y + side, v1.z);
  const Point3D v4(v1.x + side, v1.y, v1.z);
  // Back
  const Point3D v5(v1.x, v1.y, v1.z + side);
  const Point3D v6(v2.x, v2.y, v2.z + side);
  const Point3D v7(v3.x, v3.y, v3.z + side);
  const Point3D v8(v4.x, v4.y, v4.z + side);

  vertices = {
    // Front face
    v1, v2, v3, v4,

    // Back face
    v5, v6, v7, v8,

    // Top face
    v2, v6, v7, v3,

    // Bottom face
    v1, v5, v8, v4,

    // Left face
    v1, v2, v6, v5,

    // Right face
    v4, v3, v7, v8
  };

  texture_coords = {
    // Texture coordinates
    // Front face
    Vector2D(0, 0),
    Vector2D(0, 1),
    Vector2D(1, 1),
    Vector2D(1, 0),

    // Back face
    Vector2D(1, 1),
    Vector2D(1, 0),
    Vector2D(0, 0),
    Vector2D(0, 1),
    // Top face
    Vector2D(0, 0),
    Vector2D(0, 1),
    Vector2D(1, 1),
    Vector2D(1, 0),
    //// Bottom face
    Vector2D(0, 0),
    Vector2D(0, 1),
    Vector2D(1, 1),
    Vector2D(1, 0),
    //// Left face
    Vector2D(1, 0),
    Vector2D(1, 1),
    Vector2D(0, 1),
    Vector2D(0, 0),
    //// Right face
    Vector2D(0, 0),
    Vector2D(0, 1),
    Vector2D(1, 1),
    Vector2D(1, 0)
  };

  indices = {
    // Vertices indices
    // Front face
    0, 1, 2,
    2, 3, 0,

    // Back face
    6, 5, 4,
    4, 7, 6,

    // Top face
    8, 9, 10,
    10, 11, 8,

    // Bottom face
    14, 13, 12,
    12, 15, 14,

    // Left face
    16, 19, 18,
    18, 17, 16,

    // Right face
    20, 21, 22,
    22, 23, 20
  };
}

GeometryObject* buildPlainBox(Material* material, const RGBColor& color, const Point3D& center, const float side) {
  const std::vector<RGBColor> colors = std::vector<RGBColor>(24, color);

  std::vector<Point3D> vertices;
  std::vector<Vector2D> texture_coords;
  std::vector<uint32_t> indices;
  buildAlignedBox(vertices, texture_coords, indices, side);
  GeometryObject* box = new GeometryObject(material, vertices, colors, texture_coords, indices, center);

  return box;
}

GeometryObject* buildMultiColorBox(Material* material, const Point3D& center, const float side) {
  const std::vector<RGBColor> colors = {
    Colors::GREEN,
    Colors::YELLOW,
    Colors::WHITE,
    Colors::CYAN,

    Colors::BLACK,
    Colors::BLACK,
    Colors::BLACK,
    Colors::BLACK,

    Colors::YELLOW,
    Colors::RED,
    Colors::PURPLE,
    Colors::WHITE,

    Colors::BLACK,
    Colors::BLACK,
    Colors::BLACK,
    Colors::BLACK,

    Colors::BLACK,
    Colors::BLACK,
    Colors::BLACK,
    Colors::BLACK,

    Colors::CYAN,
    Colors::WHITE,
    Colors::PURPLE,
    Colors::BLUE,
  };

  std::vector<Point3D> vertices;
  std::vector<Vector2D> texture_coords;
  std::vector<uint32_t> indices;
  buildAlignedBox(vertices, texture_coords, indices, side);
  GeometryObject* box = new GeometryObject(material, vertices, colors, texture_coords, indices, center);

  return box;
}

GeometryObject* buildTexturedBox(Material* material, const Point3D& center, const float side) {
  std::vector<Point3D> vertices;
  std::vector<Vector2D> texture_coords;
  std::vector<uint32_t> indices;
  buildAlignedBox(vertices, texture_coords, indices, side);
  GeometryObject* box = new GeometryObject(material, vertices, std::vector<RGBColor>(), texture_coords, indices, center);
  return box;
}

void buildHorizontalPlane(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side) {
  const float half_diagonal = (side / 2) / sin(PI / 2); // Distance to center

  const Point3D v1(-half_diagonal, 0, -half_diagonal);
  const Point3D v2(v1.x, v1.y, v1.z + side);
  const Point3D v3(v1.x + side, v1.y, v1.z + side);
  const Point3D v4(v1.x + side, v1.y, v1.z);

  vertices = {
    // Vertices positions
    v1, v2, v3, v4
  };

  texture_coords = {
    // Texture coordinates
    Vector2D(0, 0),
    Vector2D(0, 2),
    Vector2D(2, 2),
    Vector2D(2, 0),
  };

  indices = {
    // Indices
    0, 1, 2,
    2, 3, 0
  };
}

GeometryObject* buildPlainPlane(Material* material, const RGBColor& color, const Point3D& center, const float side) {
  const std::vector<RGBColor> colors = std::vector<RGBColor>(4, color);
  std::vector<Point3D> vertices;
  std::vector<Vector2D> texture_coords;
  std::vector<uint32_t> indices;
  buildHorizontalPlane(vertices, texture_coords, indices, side);
  GeometryObject* box = new GeometryObject(material, vertices, colors, texture_coords, indices, center);
  return box;
}

GeometryObject* buildTexturedPlane(Material* material, const Point3D& center, const float side) {
  std::vector<Point3D> vertices;
  std::vector<Vector2D> texture_coords;
  std::vector<uint32_t> indices;
  buildHorizontalPlane(vertices, texture_coords, indices, side);
  GeometryObject* box = new GeometryObject(material, vertices, std::vector<RGBColor>(), texture_coords, indices, center);
  return box;
}<commit_msg>Replaced one simple rotation with quaternion based rotation<commit_after>#include <iostream>
#include <vector>

#include "World.h"
#include "Renderer.h"
#include "ForwardRasterizer.h"
#include "DeferredRasterizer.h"
#include "Camera.h"
#include "Light.h"
#include "DirectionalLight.h"
#include "PointLight.h"
#include "OrthographicCamera.h"
#include "PerspectiveCamera.h"
#include "Constants.h"

// Forward declaration utils functions
void buildAlignedBox(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side);
GeometryObject* buildPlainBox(Material* material, const RGBColor& color, const Point3D& center, const float side);
GeometryObject* buildTexturedBox(Material* material, const Point3D& center, const float side);

void buildHorizontalPlane(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side);
GeometryObject* buildTexturedPlane(Material* material, const Point3D& center, const float side);
GeometryObject* buildPlainPlane(Material* material, const RGBColor& color, const Point3D& center, const float side);
GeometryObject* buildMultiColorBox(Material* material, const Point3D& center, const float side);

const std::vector<GeometryObject*> setupFlatScene();
const std::vector<GeometryObject*> setupTexturedScene();

Camera * camera;
Renderer * renderer;
int main (){
  std::vector<Light*> lights = {
    new DirectionalLight(Colors::WHITE, Vector3D(1, 0.4, -1))
  };
  const std::vector<GeometryObject*> objects_flat = setupFlatScene();
  const std::vector<GeometryObject*> objects_textured = setupTexturedScene();

  World * world = new World(objects_flat, lights, camera);
#ifdef _FORWARD
  renderer = new ForwardRasterizer(world);
#endif

#ifdef _DEFERRED
  renderer = new DeferredRasterizer(world);
#endif

#ifdef _ORTHOGRAPHIC
  camera = new OrthographicCamera(CAMERA_POS, CAMERA_TARGET, IMAGE_HEIGHT, IMAGE_WIDTH, renderer);
#endif

#ifdef _PERSPECTIVE
  camera = new PerspectiveCamera(CAMERA_POS, CAMERA_TARGET, IMAGE_HEIGHT, IMAGE_WIDTH, renderer);
#endif
  world->m_camera = camera;
  renderer->render();
  renderer->export_output(IMAGE_NAME);
  return 0;
}

const std::vector<GeometryObject*> setupFlatScene() {
  std::vector<GeometryObject*> objects;

  // Objects

  GeometryObject* ground = buildPlainPlane(Materials::FLAT_PLASTIC, Colors::GREY, Point3D(0, 0, 0), 500);
  objects.push_back(ground);

  GeometryObject* flat_box = buildPlainBox(Materials::FLAT_PLASTIC, Colors::RED, Point3D(0, 0, 0), 100);
  flat_box->translate(Vector3D(150, 50, 100));
  flat_box->rotate(45, Vector3D(0, 1, 0));
  //flat_box->rotate(0, 45, 0);
  objects.push_back(flat_box);

  GeometryObject* flat_box2 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::CYAN, Point3D(150, 125, 100), 50);
  objects.push_back(flat_box2);

  GeometryObject* flying_box = buildPlainBox(Materials::FLAT_PLASTIC, Colors::YELLOW, Point3D(-100, 120, 75), 75);
  flying_box->rotate(45, -45, 45);
  objects.push_back(flying_box);

  GeometryObject* multicolor_box = buildMultiColorBox(Materials::FLAT_PLASTIC, Point3D(-100, 50, -90), 100);
  multicolor_box->rotate(0, -45, 0);
  objects.push_back(multicolor_box);

  GeometryObject* small_box2 = buildPlainBox(Materials::FLAT_PLASTIC, Colors::PURPLE, Point3D(150, 37.5, -220), 75);
  objects.push_back(small_box2);
  return objects;
}

const std::vector<GeometryObject*> setupTexturedScene() {
  std::vector<GeometryObject*> objects;

  // Objects
  GeometryObject* ground = buildTexturedPlane(Materials::BRICK, Point3D(0, 0, 0), 500);
  objects.push_back(ground);

  GeometryObject* flat_box = buildTexturedBox(Materials::BOX, Point3D(0, 0, 0), 100);
  flat_box->translate(Vector3D(150, 50, 100));
  flat_box->rotate(0, 45, 0);
  objects.push_back(flat_box);

  GeometryObject* flat_box2 = buildTexturedBox(Materials::BOX, Point3D(150, 125, 100), 50);
  objects.push_back(flat_box2);

  GeometryObject* flying_box = buildTexturedBox(Materials::BOX, Point3D(-100, 120, 75), 75);
  flying_box->rotate(45, -45, 45);
  objects.push_back(flying_box);

  GeometryObject* small_box1 = buildTexturedBox(Materials::BOX, Point3D(-100, 50, -90), 100);
  small_box1->rotate(0, -45, 0);
  objects.push_back(small_box1);

  GeometryObject* default_box = buildTexturedBox(Materials::DEFAULT, Point3D(150, 37.5, -220), 75);
  objects.push_back(default_box);

  return objects;
}

void buildAlignedBox(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side) {
  const float half_diagonal = (side / 2) / sin(PI / 2); // Distance to center
                                                        // Front
  const Point3D v1(-half_diagonal, -half_diagonal, -half_diagonal);
  const Point3D v2(v1.x, v1.y + side, v1.z);
  const Point3D v3(v1.x + side, v1.y + side, v1.z);
  const Point3D v4(v1.x + side, v1.y, v1.z);
  // Back
  const Point3D v5(v1.x, v1.y, v1.z + side);
  const Point3D v6(v2.x, v2.y, v2.z + side);
  const Point3D v7(v3.x, v3.y, v3.z + side);
  const Point3D v8(v4.x, v4.y, v4.z + side);

  vertices = {
    // Front face
    v1, v2, v3, v4,

    // Back face
    v5, v6, v7, v8,

    // Top face
    v2, v6, v7, v3,

    // Bottom face
    v1, v5, v8, v4,

    // Left face
    v1, v2, v6, v5,

    // Right face
    v4, v3, v7, v8
  };

  texture_coords = {
    // Texture coordinates
    // Front face
    Vector2D(0, 0),
    Vector2D(0, 1),
    Vector2D(1, 1),
    Vector2D(1, 0),

    // Back face
    Vector2D(1, 1),
    Vector2D(1, 0),
    Vector2D(0, 0),
    Vector2D(0, 1),
    // Top face
    Vector2D(0, 0),
    Vector2D(0, 1),
    Vector2D(1, 1),
    Vector2D(1, 0),
    //// Bottom face
    Vector2D(0, 0),
    Vector2D(0, 1),
    Vector2D(1, 1),
    Vector2D(1, 0),
    //// Left face
    Vector2D(1, 0),
    Vector2D(1, 1),
    Vector2D(0, 1),
    Vector2D(0, 0),
    //// Right face
    Vector2D(0, 0),
    Vector2D(0, 1),
    Vector2D(1, 1),
    Vector2D(1, 0)
  };

  indices = {
    // Vertices indices
    // Front face
    0, 1, 2,
    2, 3, 0,

    // Back face
    6, 5, 4,
    4, 7, 6,

    // Top face
    8, 9, 10,
    10, 11, 8,

    // Bottom face
    14, 13, 12,
    12, 15, 14,

    // Left face
    16, 19, 18,
    18, 17, 16,

    // Right face
    20, 21, 22,
    22, 23, 20
  };
}

GeometryObject* buildPlainBox(Material* material, const RGBColor& color, const Point3D& center, const float side) {
  const std::vector<RGBColor> colors = std::vector<RGBColor>(24, color);

  std::vector<Point3D> vertices;
  std::vector<Vector2D> texture_coords;
  std::vector<uint32_t> indices;
  buildAlignedBox(vertices, texture_coords, indices, side);
  GeometryObject* box = new GeometryObject(material, vertices, colors, texture_coords, indices, center);

  return box;
}

GeometryObject* buildMultiColorBox(Material* material, const Point3D& center, const float side) {
  const std::vector<RGBColor> colors = {
    Colors::GREEN,
    Colors::YELLOW,
    Colors::WHITE,
    Colors::CYAN,

    Colors::BLACK,
    Colors::BLACK,
    Colors::BLACK,
    Colors::BLACK,

    Colors::YELLOW,
    Colors::RED,
    Colors::PURPLE,
    Colors::WHITE,

    Colors::BLACK,
    Colors::BLACK,
    Colors::BLACK,
    Colors::BLACK,

    Colors::BLACK,
    Colors::BLACK,
    Colors::BLACK,
    Colors::BLACK,

    Colors::CYAN,
    Colors::WHITE,
    Colors::PURPLE,
    Colors::BLUE,
  };

  std::vector<Point3D> vertices;
  std::vector<Vector2D> texture_coords;
  std::vector<uint32_t> indices;
  buildAlignedBox(vertices, texture_coords, indices, side);
  GeometryObject* box = new GeometryObject(material, vertices, colors, texture_coords, indices, center);

  return box;
}

GeometryObject* buildTexturedBox(Material* material, const Point3D& center, const float side) {
  std::vector<Point3D> vertices;
  std::vector<Vector2D> texture_coords;
  std::vector<uint32_t> indices;
  buildAlignedBox(vertices, texture_coords, indices, side);
  GeometryObject* box = new GeometryObject(material, vertices, std::vector<RGBColor>(), texture_coords, indices, center);
  return box;
}

void buildHorizontalPlane(std::vector<Point3D>& vertices, std::vector<Vector2D>& texture_coords, std::vector<uint32_t>& indices, const float side) {
  const float half_diagonal = (side / 2) / sin(PI / 2); // Distance to center

  const Point3D v1(-half_diagonal, 0, -half_diagonal);
  const Point3D v2(v1.x, v1.y, v1.z + side);
  const Point3D v3(v1.x + side, v1.y, v1.z + side);
  const Point3D v4(v1.x + side, v1.y, v1.z);

  vertices = {
    // Vertices positions
    v1, v2, v3, v4
  };

  texture_coords = {
    // Texture coordinates
    Vector2D(0, 0),
    Vector2D(0, 2),
    Vector2D(2, 2),
    Vector2D(2, 0),
  };

  indices = {
    // Indices
    0, 1, 2,
    2, 3, 0
  };
}

GeometryObject* buildPlainPlane(Material* material, const RGBColor& color, const Point3D& center, const float side) {
  const std::vector<RGBColor> colors = std::vector<RGBColor>(4, color);
  std::vector<Point3D> vertices;
  std::vector<Vector2D> texture_coords;
  std::vector<uint32_t> indices;
  buildHorizontalPlane(vertices, texture_coords, indices, side);
  GeometryObject* box = new GeometryObject(material, vertices, colors, texture_coords, indices, center);
  return box;
}

GeometryObject* buildTexturedPlane(Material* material, const Point3D& center, const float side) {
  std::vector<Point3D> vertices;
  std::vector<Vector2D> texture_coords;
  std::vector<uint32_t> indices;
  buildHorizontalPlane(vertices, texture_coords, indices, side);
  GeometryObject* box = new GeometryObject(material, vertices, std::vector<RGBColor>(), texture_coords, indices, center);
  return box;
}<|endoftext|>


<commit_before>#include <fstream>
#include <iostream>
#include <vector>
#include <stdlib.h>

#include "../include/enum.h"
#include "../include/betterEnum.h"
#include "../include/linear.h"
#include "../include/Helper/fileUtils.h"
#include "../include/Helper/timingRoutines.h"

int main()
{
	std::ifstream input;
	input.open("MSS_TestProblems.txt");
    if(!input.is_open())
    {
        input.close();
        std::cout << "MSS_TestProblems.txt not found in current directory. Now exiting." << std::endl;
        exit(1);
    }

    std::ofstream out;
    out.open("MSS_TestResults.txt");

	std::vector<std::vector<int>*>* processedInts = Helper::processMSSFile(input);
    input.close();

	out << "Results of enumFunction: \n";
	for(uint i = 0; i < processedInts->size(); i++)
	{
        int start;
        int end;
        int total = enumFunction(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
        std::cout << '\n';
	}

	out << "Results of betterEnumFunction: \n";
	for(uint i = 0; i < processedInts->size(); i++)
	{
        int start;
        int end;
        int total = betterEnumFunction(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
        std::cout << '\n';
	}
	out << "Results of linear function: \n";
	for(uint i = 0; i < processedInts->size(); i++)
	{
        int start;
        int end;
        int total = linear(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
		std::cout << '\n';
	}
    out.close();

    std::cout << "Running timing function for enumFunction: " << std::endl;
    int enumValsN[] = {1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800};

    for(int i = 0; i < 10; i++)
    {
        std::vector<int>* randNums = Helper::GenRandNums(enumValsN[i]);
        int(*funPtr1)(std::vector<int>) = &enumFunction;
        Helper::ClockMSSFunction(funPtr1, randNums);
    }

    std::cout << "Running timing function for betterEnumFunction: " << std::endl;
    int betterEnumValsN[] = {15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000, 60000};

    for(int i = 0; i < 10; i++)
    {
        std::vector<int>* randNums = Helper::GenRandNums(betterEnumValsN[i]);
        int(*funPtr1)(std::vector<int>) = &betterEnumFunction;
        Helper::ClockMSSFunction(funPtr1, randNums);
    }

	return 0;
}
<commit_msg>Add first pass at linear timings<commit_after>#include <fstream>
#include <iostream>
#include <vector>
#include <stdlib.h>

#include "../include/enum.h"
#include "../include/betterEnum.h"
#include "../include/linear.h"
#include "../include/Helper/fileUtils.h"
#include "../include/Helper/timingRoutines.h"

int main()
{
	std::ifstream input;
	input.open("MSS_TestProblems.txt");
    if(!input.is_open())
    {
        input.close();
        std::cout << "MSS_TestProblems.txt not found in current directory. Now exiting." << std::endl;
        exit(1);
    }

    std::ofstream out;
    out.open("MSS_TestResults.txt");

	std::vector<std::vector<int>*>* processedInts = Helper::processMSSFile(input);
    input.close();

	out << "Results of enumFunction: \n";
	for(uint i = 0; i < processedInts->size(); i++)
	{
        int start;
        int end;
        int total = enumFunction(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
        std::cout << '\n';
	}

	out << "Results of betterEnumFunction: \n";
	for(uint i = 0; i < processedInts->size(); i++)
	{
        int start;
        int end;
        int total = betterEnumFunction(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
        std::cout << '\n';
	}
	out << "Results of linear function: \n";
	for(uint i = 0; i < processedInts->size(); i++)
	{
        int start;
        int end;
        int total = linear(*(processedInts->at(i)), start, end);
        Helper::WriteResultsToFile(out, *processedInts->at(i), start, end, total);
		std::cout << '\n';
	}
    out.close();

    std::cout << "Running timing function for enumFunction: " << std::endl;
    int enumValsN[] = {1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800};

    for(int i = 0; i < 10; i++)
    {
        std::vector<int>* randNums = Helper::GenRandNums(enumValsN[i]);
        int(*funPtr1)(std::vector<int>) = &enumFunction;
        Helper::ClockMSSFunction(funPtr1, randNums);
    }

    std::cout << "Running timing function for betterEnumFunction: " << std::endl;
    int betterEnumValsN[] = {15000, 20000, 25000, 30000, 35000, 40000, 45000, 50000, 55000, 60000};

    for(int i = 0; i < 10; i++)
    {
        std::vector<int>* randNums = Helper::GenRandNums(betterEnumValsN[i]);
        int(*funPtr1)(std::vector<int>) = &betterEnumFunction;
        Helper::ClockMSSFunction(funPtr1, randNums);
    }

    std::cout << "Running timing function for linear: " << std::endl;
    int linearN[] = {100000, 200000, 300000, 400000, 500000, 600000, 700000, 800000, 900000, 1000000};

    for(int i = 0; i < 10; i++)
    {
        std::vector<int>* randNums = Helper::GenRandNums(linearN[i]);
        int(*funPtr1)(std::vector<int>) = &linear;
        Helper::ClockMSSFunction(funPtr1, randNums);
    }

	return 0;
}
<|endoftext|>


<commit_before>/*
  Original code from tekkies/CVdrone (get actual address from github)

  Modified by Elliot Greenlee, Caleb Mennen, Jacob Pollack
  COSC 402 Senior Design

  Min Kao Drone Tour
  See readme at (get actual address from github)
*/

#include "ardrone/ardrone.h"
#include "structures.h"
#include "objectFollowing/objectFollowing.h"
#include "manual/manual.h"
#include "lineFollowing/lineFollowing.h"
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>

using namespace std;

class Control {
  public:
    //AR.Drone class
    ARDrone ardrone;

    int key;
    FlyingMode flyingmode;
    double speed;
    int batteryPercentage;
    bool flying;

    ControlMovements controlMovements;

    FILE *flight_log;

};

void detectFlyingMode(ARDrone *ardrone, int key, FlyingMode *flyingMode) {

  //switch between flying modes
  if (key == 'b') {
    *flyingMode = Manual;
    ardrone->setCamera(0);
    printf("Manual flying mode is enabled\n");
    printf("Press n for object following and m for line following\n");
    printf("While in manual mode, use q and a for up and down, t and g for forward and backward, and f and h for left and right. Press space to take off.\n\n");
  }
  else if (key == 'n') {
    *flyingMode = ObjectFollow;
    ardrone->setCamera(0);
    printf("Object Following flying mode is enabled\n");
    printf("Press b for manual and m for line following\n");
    printf("While in object following mode, use l to toggle learning a specific color. Press space to take off after learning a color.\n\n");
  }
  else if (key == 'm') {
    *flyingMode = LineFollow;
    ardrone->setCamera(1);
    printf("Line Following flying mode is enabled\n");
    printf("Press b for manual and n for object following\n");
    printf("No control for line following yet exists\n\n");
  }
}

int main(int argc, char *argv[])
{
  Control control;

  //Control classes
  ObjectFollowing objectFollowing;
  //TODO: ManualDriving manualDriving;
  //TODO: LineFollowing lineFollwing;

  //Display variables
  FILE *flight_log;

  char modeDisplay[80]; //print buffer for flying mode
  char flyingDisplay[80]; //print buffer for if flying
  char speedDisplay[80]; //print buffer for speed

  cv::Scalar green = CV_RGB(0,255,0); //putText color value

  //Drone control
  float speed = 0.0;
  double vx = 0.0;
  double vy = 0.0;
  double vz = 0.0;
  double vr = 0.0;
  ControlMovements controlMovements;

  FlyingMode flyingMode = Manual;

  //Initializing Message
  printf("Connecting to the drone\n");
  printf("If there is no version number response in the next 10 seconds, please restart the drone and code.\n");
  printf("To disconnect, press the ESC key\n\n");
  fflush(stdout);

  // Initialize
  if (!control.ardrone.open()) {
    printf("Failed to initialize.\n");
    return -1;
  }

  //Set drone on flat surface and initialize
  control.ardrone.setFlatTrim();

  //initialize object following code
  objectFollowing.initializeObjectFollowing();

  //Print default command information
  printf("Currently the drone is in manual mode.\n");
  printf("Use the b key for manual mode, the n key for object following, and the m key for line following. The number keys can be used to set a speed. Use spacebar to take off and land, which is required before any control can be executed.\n\n");

  flight_log = fopen("flight_log.txt", "w");

  // Main loop
  while (1) {
    control.key = cv::waitKey(33); // Key input

    if (control.key == 0x1b) { break; } //press the escape key to exit

    //TODO:Write battery percentage to screen
    printf("%d\n", control.ardrone.getBatteryPercentage());

    detectFlyingMode(&(control.ardrone), control.key, &flyingMode);

    // Get an image
    cv::Mat image = control.ardrone.getImage();

    //Speed
    if ((control.key >= '0') && (control.key <= '9')) //number keys
    {
      speed = (control.key-'0')*0.1;
    }

    //Write speed to image
    sprintf(speedDisplay, "Speed = %3.2f", speed);
    putText(image, speedDisplay, cvPoint(30,40), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);

    //Take off / Landing
    if (control.key == ' ') { //spacebar
      if (control.ardrone.onGround()) {
        control.ardrone.takeoff();
	fprintf(flight_log, "TAKEOFF\n");
        std::this_thread::sleep_for(std::chrono::milliseconds(5000));
      }
      else {
        control.ardrone.landing();
	fprintf(flight_log, "LAND\n");
      }
    }

    //Write if grounded or flying to image
    if (control.ardrone.onGround()) {
      sprintf(flyingDisplay, "Landed");
    }
    else {
      sprintf(flyingDisplay, "Flying");
    }
    putText(image, flyingDisplay, cvPoint(200,40), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);

    switch (flyingMode) {
      case Manual:
        //TODO: Allow user to set camera mode in Manual
        //TODO: Change 0/1 to CONSTANTS of 0 = front, 1 = bottom

        //TODO: Scale these values for normal human control when in manual mode
        controlMovements = manualMovement(control.key);

        sprintf(modeDisplay, "Manual Mode");

        //TODO: Move this into manualMovement(control.key) function
        displayManualInfo(&image, controlMovements);

        vx = controlMovements.vx;
        vy = controlMovements.vy;
        vz = controlMovements.vz;
        vr = controlMovements.vr;
        break;

      case ObjectFollow:

        controlMovements = objectFollowing.detectObject(image, control.key);

        vx = controlMovements.vx;
        vy = controlMovements.vy;
        vz = controlMovements.vz;
        vr = controlMovements.vr;

        sprintf(modeDisplay, "Object Following Mode");
        break;

      case LineFollow:
        sprintf(modeDisplay, "Line Following Mode");
        break;
    }

    putText(image, modeDisplay, cvPoint(30,20), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);

    fprintf(flight_log, "ardrone.move3D(vx=%f, vy=%f, vz=%f, vr=%f)\n", (speed), (vy * speed), (vz * speed), vr);

    control.ardrone.move3D(vx * speed, vy * speed, vz * speed, vr);

    //Display the camera feed
    cv::imshow("camera", image);
  }

  //Write hsv values to a file
  objectFollowing.closeObjectFollowing();
  //TODO: closeManual();
  //TODO: closeLineFollowing();

  //Close connection to drone
  control.ardrone.close();

  return 0;
}
<commit_msg>Move flyingMode into Control class.<commit_after>/*
  Original code from tekkies/CVdrone (get actual address from github)

  Modified by Elliot Greenlee, Caleb Mennen, Jacob Pollack
  COSC 402 Senior Design

  Min Kao Drone Tour
  See readme at (get actual address from github)
*/

#include "ardrone/ardrone.h"
#include "structures.h"
#include "objectFollowing/objectFollowing.h"
#include "manual/manual.h"
#include "lineFollowing/lineFollowing.h"
#include <iostream>
#include <vector>
#include <chrono>
#include <thread>

using namespace std;

class Control {
  public:
    //AR.Drone class
    ARDrone ardrone;

    int key;
    FlyingMode flyingMode = Manual;
    double speed;
    int batteryPercentage;
    bool flying;

    ControlMovements controlMovements;

    FILE *flight_log;

};

void detectFlyingMode(ARDrone *ardrone, int key, FlyingMode *flyingMode) {

  //switch between flying modes
  if (key == 'b') {
    *flyingMode = Manual;
    ardrone->setCamera(0);
    printf("Manual flying mode is enabled\n");
    printf("Press n for object following and m for line following\n");
    printf("While in manual mode, use q and a for up and down, t and g for forward and backward, and f and h for left and right. Press space to take off.\n\n");
  }
  else if (key == 'n') {
    *flyingMode = ObjectFollow;
    ardrone->setCamera(0);
    printf("Object Following flying mode is enabled\n");
    printf("Press b for manual and m for line following\n");
    printf("While in object following mode, use l to toggle learning a specific color. Press space to take off after learning a color.\n\n");
  }
  else if (key == 'm') {
    *flyingMode = LineFollow;
    ardrone->setCamera(1);
    printf("Line Following flying mode is enabled\n");
    printf("Press b for manual and n for object following\n");
    printf("No control for line following yet exists\n\n");
  }
}

int main(int argc, char *argv[])
{
  Control control;

  //Control classes
  ObjectFollowing objectFollowing;
  //TODO: ManualDriving manualDriving;
  //TODO: LineFollowing lineFollwing;

  //Display variables
  FILE *flight_log;

  char modeDisplay[80]; //print buffer for flying mode
  char flyingDisplay[80]; //print buffer for if flying
  char speedDisplay[80]; //print buffer for speed

  cv::Scalar green = CV_RGB(0,255,0); //putText color value

  //Drone control
  float speed = 0.0;
  double vx = 0.0;
  double vy = 0.0;
  double vz = 0.0;
  double vr = 0.0;
  ControlMovements controlMovements;

  //Initializing Message
  printf("Connecting to the drone\n");
  printf("If there is no version number response in the next 10 seconds, please restart the drone and code.\n");
  printf("To disconnect, press the ESC key\n\n");
  fflush(stdout);

  // Initialize
  if (!control.ardrone.open()) {
    printf("Failed to initialize.\n");
    return -1;
  }

  //Set drone on flat surface and initialize
  control.ardrone.setFlatTrim();

  //initialize object following code
  objectFollowing.initializeObjectFollowing();

  //Print default command information
  printf("Currently the drone is in manual mode.\n");
  printf("Use the b key for manual mode, the n key for object following, and the m key for line following. The number keys can be used to set a speed. Use spacebar to take off and land, which is required before any control can be executed.\n\n");

  flight_log = fopen("flight_log.txt", "w");

  // Main loop
  while (1) {
    control.key = cv::waitKey(33); // Key input

    if (control.key == 0x1b) { break; } //press the escape key to exit

    //TODO:Write battery percentage to screen
    printf("%d\n", control.ardrone.getBatteryPercentage());

    detectFlyingMode(&(control.ardrone), control.key, &(control.flyingMode));

    // Get an image
    cv::Mat image = control.ardrone.getImage();

    //Speed
    if ((control.key >= '0') && (control.key <= '9')) //number keys
    {
      speed = (control.key-'0')*0.1;
    }

    //Write speed to image
    sprintf(speedDisplay, "Speed = %3.2f", speed);
    putText(image, speedDisplay, cvPoint(30,40), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);

    //Take off / Landing
    if (control.key == ' ') { //spacebar
      if (control.ardrone.onGround()) {
        control.ardrone.takeoff();
	fprintf(flight_log, "TAKEOFF\n");
        std::this_thread::sleep_for(std::chrono::milliseconds(5000));
      }
      else {
        control.ardrone.landing();
	fprintf(flight_log, "LAND\n");
      }
    }

    //Write if grounded or flying to image
    if (control.ardrone.onGround()) {
      sprintf(flyingDisplay, "Landed");
    }
    else {
      sprintf(flyingDisplay, "Flying");
    }
    putText(image, flyingDisplay, cvPoint(200,40), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);

    switch (control.flyingMode) {
      case Manual:
        //TODO: Allow user to set camera mode in Manual
        //TODO: Change 0/1 to CONSTANTS of 0 = front, 1 = bottom

        //TODO: Scale these values for normal human control when in manual mode
        controlMovements = manualMovement(control.key);

        sprintf(modeDisplay, "Manual Mode");

        //TODO: Move this into manualMovement(control.key) function
        displayManualInfo(&image, controlMovements);

        vx = controlMovements.vx;
        vy = controlMovements.vy;
        vz = controlMovements.vz;
        vr = controlMovements.vr;
        break;

      case ObjectFollow:

        controlMovements = objectFollowing.detectObject(image, control.key);

        vx = controlMovements.vx;
        vy = controlMovements.vy;
        vz = controlMovements.vz;
        vr = controlMovements.vr;

        sprintf(modeDisplay, "Object Following Mode");
        break;

      case LineFollow:
        sprintf(modeDisplay, "Line Following Mode");
        break;
    }

    putText(image, modeDisplay, cvPoint(30,20), cv::FONT_HERSHEY_COMPLEX_SMALL, 0.8, green, 1, CV_AA);

    fprintf(flight_log, "ardrone.move3D(vx=%f, vy=%f, vz=%f, vr=%f)\n", (speed), (vy * speed), (vz * speed), vr);

    control.ardrone.move3D(vx * speed, vy * speed, vz * speed, vr);

    //Display the camera feed
    cv::imshow("camera", image);
  }

  //Write hsv values to a file
  objectFollowing.closeObjectFollowing();
  //TODO: closeManual();
  //TODO: closeLineFollowing();

  //Close connection to drone
  control.ardrone.close();

  return 0;
}
<|endoftext|>