<commit_before>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "component_score_json_writer_process.h"

#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>

#include <vistk/scoring/scoring_result.h>

#include <vistk/utilities/path.h>

#include <boost/algorithm/string/predicate.hpp>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>

#include <fstream>
#include <string>

/**
 * \file component_score_json_writer_process.cxx
 *
 * \brief Implementation of a process which writes out component scores to a file in JSON.
 */

namespace vistk
{

class component_score_json_writer_process::priv
{
  public:
    typedef port_t tag_t;
    typedef std::vector<tag_t> tags_t;

    priv();
    priv(path_t const& output_path, tags_t const& tags_);
    ~priv();

    path_t const path;

    std::ofstream fout;

    tags_t tags;

    static config::key_t const config_path;
    static port_t const port_score_prefix;
};

config::key_t const component_score_json_writer_process::priv::config_path = "path";
process::port_t const component_score_json_writer_process::priv::port_score_prefix = process::port_t("score/");

component_score_json_writer_process
::component_score_json_writer_process(config_t const& config)
  : process(config)
  , d(new priv)
{
  declare_configuration_key(priv::config_path, boost::make_shared<conf_info>(
    config::value_t(),
    config::description_t("The path to output scores to.")));
}

component_score_json_writer_process
::~component_score_json_writer_process()
{
}

void
component_score_json_writer_process
::_configure()
{
  // Configure the process.
  {
    path_t const path = config_value<path_t>(priv::config_path);

    d.reset(new priv(path, d->tags));
  }

  path_t::string_type const path = d->path.native();

  if (path.empty())
  {
    static std::string const reason = "The path given was empty";
    config::value_t const value = config::value_t(path.begin(), path.end());

    throw invalid_configuration_value_exception(name(), priv::config_path, value, reason);
  }

  d->fout.open(path.c_str());

  if (!d->fout.good())
  {
    std::string const file_path(path.begin(), path.end());
    std::string const reason = "Failed to open the path: " + file_path;

    throw invalid_configuration_exception(name(), reason);
  }

  process::_configure();
}

void
component_score_json_writer_process
::_init()
{
  if (!d->tags.size())
  {
    static std::string const reason = "There must be at least one component score to write";

    throw invalid_configuration_exception(name(), reason);
  }

  process::_init();
}

void
component_score_json_writer_process
::_step()
{
#define JSON_KEY(key) \
  ("\"" key "\": ")
#define JSON_ATTR(key, value) \
  JSON_KEY(key) << value
#define JSON_SEP \
  "," << std::endl
#define JSON_OBJECT_BEGIN \
  "{" << std::endl
#define JSON_OBJECT_END \
  "}"

  d->fout << JSON_OBJECT_BEGIN;

  /// \todo Name runs.
  d->fout << JSON_ATTR("name", "\"(unnamed)\"");
  d->fout << JSON_SEP;
  /// \todo Insert date.
  d->fout << JSON_ATTR("date", "\"\"");
  d->fout << JSON_SEP;
  /// \todo Get git hash.
  d->fout << JSON_ATTR("hash", "\"\"");
  d->fout << JSON_SEP;
  d->fout << JSON_ATTR("config", "{}");
  d->fout << JSON_SEP;
  d->fout << JSON_KEY("results") << JSON_OBJECT_BEGIN;

  bool first = true;

  BOOST_FOREACH (priv::tag_t const& tag, d->tags)
  {
    if (!first)
    {
      d->fout << JSON_SEP;
    }

    first = false;

    d->fout << JSON_KEY(+ tag +);

    d->fout << JSON_OBJECT_BEGIN;

    scoring_result_t const result = grab_from_port_as<scoring_result_t>(priv::port_score_prefix + tag);

    d->fout << JSON_ATTR("true-positive", result->true_positives);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("false-positive", result->false_positives);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("total-true", result->total_trues);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("total-possible", result->total_possible);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("percent-detection", result->percent_detection());
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("precision", result->precision());
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("specificity", result->specificity());

    d->fout << JSON_OBJECT_END;
  }

  d->fout << std::endl;
  d->fout << JSON_OBJECT_END;
  d->fout << std::endl;
  d->fout << JSON_OBJECT_END;
  d->fout << std::endl;

#undef JSON_OBJECT_END
#undef JSON_OBJECT_BEGIN
#undef JSON_SEP
#undef JSON_ATTR
#undef JSON_KEY

  process::_step();
}

process::port_info_t
component_score_json_writer_process
::_input_port_info(port_t const& port)
{
  if (boost::starts_with(port, priv::port_score_prefix))
  {
    priv::tag_t const tag = port.substr(priv::port_score_prefix.size());

    priv::tags_t::const_iterator const i = std::find(d->tags.begin(), d->tags.end(), tag);

    if (i == d->tags.end())
    {
      d->tags.push_back(tag);

      port_flags_t required;

      required.insert(flag_required);

      declare_input_port(port, boost::make_shared<port_info>(
        "score",
        required,
        port_description_t("The \'" + tag + "\' score component.")));
    }
  }

  return process::_input_port_info(port);
}

component_score_json_writer_process::priv
::priv()
{
}

component_score_json_writer_process::priv
::priv(path_t const& output_path, tags_t const& tags_)
  : path(output_path)
  , tags(tags_)
{
}

component_score_json_writer_process::priv
::~priv()
{
}

}
<commit_msg>Add the ability to output score statistics<commit_after>/*ckwg +5
 * Copyright 2011 by Kitware, Inc. All Rights Reserved. Please refer to
 * KITWARE_LICENSE.TXT for licensing information, or contact General Counsel,
 * Kitware, Inc., 28 Corporate Drive, Clifton Park, NY 12065.
 */

#include "component_score_json_writer_process.h"

#include <vistk/pipeline/datum.h>
#include <vistk/pipeline/process_exception.h>

#include <vistk/scoring/scoring_result.h>
#include <vistk/scoring/scoring_statistics.h>
#include <vistk/scoring/statistics.h>

#include <vistk/utilities/path.h>

#include <boost/algorithm/string/predicate.hpp>
#include <boost/foreach.hpp>
#include <boost/make_shared.hpp>

#include <fstream>
#include <string>

/**
 * \file component_score_json_writer_process.cxx
 *
 * \brief Implementation of a process which writes out component scores to a file in JSON.
 */

namespace vistk
{

class component_score_json_writer_process::priv
{
  public:
    typedef port_t tag_t;
    typedef std::vector<tag_t> tags_t;

    typedef std::map<tag_t, bool> tag_stat_map_t;

    priv();
    priv(path_t const& output_path, tags_t const& tags_);
    ~priv();

    path_t const path;

    std::ofstream fout;

    tags_t tags;
    tag_stat_map_t tag_stats;

    static config::key_t const config_path;
    static port_t const port_score_prefix;
    static port_t const port_stats_prefix;
};

config::key_t const component_score_json_writer_process::priv::config_path = "path";
process::port_t const component_score_json_writer_process::priv::port_score_prefix = process::port_t("score/");
process::port_t const component_score_json_writer_process::priv::port_stats_prefix = process::port_t("stats/");

component_score_json_writer_process
::component_score_json_writer_process(config_t const& config)
  : process(config)
  , d(new priv)
{
  declare_configuration_key(priv::config_path, boost::make_shared<conf_info>(
    config::value_t(),
    config::description_t("The path to output scores to.")));
}

component_score_json_writer_process
::~component_score_json_writer_process()
{
}

void
component_score_json_writer_process
::_configure()
{
  // Configure the process.
  {
    path_t const path = config_value<path_t>(priv::config_path);

    d.reset(new priv(path, d->tags));
  }

  path_t::string_type const path = d->path.native();

  if (path.empty())
  {
    static std::string const reason = "The path given was empty";
    config::value_t const value = config::value_t(path.begin(), path.end());

    throw invalid_configuration_value_exception(name(), priv::config_path, value, reason);
  }

  d->fout.open(path.c_str());

  if (!d->fout.good())
  {
    std::string const file_path(path.begin(), path.end());
    std::string const reason = "Failed to open the path: " + file_path;

    throw invalid_configuration_exception(name(), reason);
  }

  process::_configure();
}

void
component_score_json_writer_process
::_init()
{
  if (!d->tags.size())
  {
    static std::string const reason = "There must be at least one component score to write";

    throw invalid_configuration_exception(name(), reason);
  }

  BOOST_FOREACH (priv::tag_t const& tag, d->tags)
  {
    port_t const port_stat = priv::port_stats_prefix + tag;

    d->tag_stats[tag] = false;

    if (input_port_edge(port_stat))
    {
      d->tag_stats[tag] = true;
    }
  }

  process::_init();
}

void
component_score_json_writer_process
::_step()
{
#define JSON_KEY(key) \
  ("\"" key "\": ")
#define JSON_ATTR(key, value) \
  JSON_KEY(key) << value
#define JSON_SEP \
  "," << std::endl
#define JSON_OBJECT_BEGIN \
  "{" << std::endl
#define JSON_OBJECT_END \
  "}"

  d->fout << JSON_OBJECT_BEGIN;

  /// \todo Name runs.
  d->fout << JSON_ATTR("name", "\"(unnamed)\"");
  d->fout << JSON_SEP;
  /// \todo Insert date.
  d->fout << JSON_ATTR("date", "\"\"");
  d->fout << JSON_SEP;
  /// \todo Get git hash.
  d->fout << JSON_ATTR("hash", "\"\"");
  d->fout << JSON_SEP;
  d->fout << JSON_ATTR("config", "{}");
  d->fout << JSON_SEP;
  d->fout << JSON_KEY("results") << JSON_OBJECT_BEGIN;

  bool first = true;

  BOOST_FOREACH (priv::tag_t const& tag, d->tags)
  {
    if (!first)
    {
      d->fout << JSON_SEP;
    }

    first = false;

    d->fout << JSON_KEY(+ tag +);

    d->fout << JSON_OBJECT_BEGIN;

    scoring_result_t const result = grab_from_port_as<scoring_result_t>(priv::port_score_prefix + tag);

    d->fout << JSON_ATTR("true-positive", result->true_positives);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("false-positive", result->false_positives);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("total-true", result->total_trues);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("total-possible", result->total_possible);
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("percent-detection", result->percent_detection());
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("precision", result->precision());
    d->fout << JSON_SEP;
    d->fout << JSON_ATTR("specificity", result->specificity());

    if (d->tag_stats[tag])
    {
      port_t const port_stats = priv::port_stats_prefix + tag;

      d->fout << JSON_SEP;

#define OUTPUT_STATISTICS(key, stats)                                        \
  do                                                                         \
  {                                                                          \
    d->fout << JSON_KEY(key);                                                \
    d->fout << JSON_OBJECT_BEGIN;                                            \
    d->fout << JSON_ATTR("count", stats->count());                           \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("min", stats->minimum());                           \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("max", stats->maximum());                           \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("mean", stats->mean());                             \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("median", stats->median());                         \
    d->fout << JSON_SEP;                                                     \
    d->fout << JSON_ATTR("standard-deviation", stats->standard_deviation()); \
    d->fout << JSON_OBJECT_END;                                              \
  } while (false)

      scoring_statistics_t const sc_stats = grab_from_port_as<scoring_statistics_t>(port_stats);

      statistics_t const pd_stats = sc_stats->percent_detection_stats();
      statistics_t const precision_stats = sc_stats->precision_stats();
      statistics_t const specificity_stats = sc_stats->specificity_stats();

      d->fout << JSON_KEY("statistics");
      d->fout << JSON_OBJECT_BEGIN;
      OUTPUT_STATISTICS("percent-detection", pd_stats);
      d->fout << JSON_SEP;
      OUTPUT_STATISTICS("precision", precision_stats);
      d->fout << JSON_SEP;
      OUTPUT_STATISTICS("specificity", specificity_stats);
      d->fout << JSON_OBJECT_END;

#undef OUTPUT_STATISTICS
    }

    d->fout << JSON_OBJECT_END;
  }

  d->fout << std::endl;
  d->fout << JSON_OBJECT_END;
  d->fout << std::endl;
  d->fout << JSON_OBJECT_END;
  d->fout << std::endl;

#undef JSON_OBJECT_END
#undef JSON_OBJECT_BEGIN
#undef JSON_SEP
#undef JSON_ATTR
#undef JSON_KEY

  process::_step();
}

process::port_info_t
component_score_json_writer_process
::_input_port_info(port_t const& port)
{
  if (boost::starts_with(port, priv::port_score_prefix))
  {
    priv::tag_t const tag = port.substr(priv::port_score_prefix.size());

    priv::tags_t::const_iterator const i = std::find(d->tags.begin(), d->tags.end(), tag);

    if (i == d->tags.end())
    {
      port_t const port_score = priv::port_score_prefix + tag;
      port_t const port_stats = priv::port_stats_prefix + tag;

      d->tags.push_back(tag);

      port_flags_t required;

      required.insert(flag_required);

      declare_input_port(port_score, boost::make_shared<port_info>(
        "score",
        required,
        port_description_t("The \'" + tag + "\' score component.")));
      declare_input_port(port_stats, boost::make_shared<port_info>(
        "statistics/score",
        port_flags_t(),
        port_description_t("The \'" + tag + "\' score statistics component.")));
    }
  }

  return process::_input_port_info(port);
}

component_score_json_writer_process::priv
::priv()
{
}

component_score_json_writer_process::priv
::priv(path_t const& output_path, tags_t const& tags_)
  : path(output_path)
  , tags(tags_)
{
}

component_score_json_writer_process::priv
::~priv()
{
}

}
<|endoftext|>


<commit_before>7f1c9f9c-2749-11e6-b99c-e0f84713e7b8<commit_msg>Too poor for Dropbox<commit_after>7f2d2d4f-2749-11e6-91ca-e0f84713e7b8<|endoftext|>


<commit_before>#include <time.h>
#include <sys/time.h>
#include <stdio.h>

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

#include <cuda.h>
#include <cuda_runtime_api.h>

#include "wave.h"

#define WIDTH 1600
#define HEIGHT 1600

#define WAVES_COUNT 4

Wave waves[WAVES_COUNT] =
{
    {320, 100, 3, 1, 0, 0},
    {320, 60, 5, 5, 2, 0},
    {160, 40, 2, 8, 1, 0},
    {80, 40, 1, -4, 1, 0}
};

unsigned char bitmap[WIDTH][HEIGHT];

unsigned char *dev_bitmap;
int *dev_time;
__constant__ Wave dev_waves[WAVES_COUNT];

dim3 grids(WIDTH/16, HEIGHT/16);
dim3 threads(16, 16);

__global__ void computeBitmap(int *t, unsigned char *bitmap)
{
    int x = threadIdx.x + blockIdx.x * blockDim.x;
    int y = threadIdx.y + blockIdx.y * blockDim.y;

    float sum = 0.0;
    for (int k = 0; k < WAVES_COUNT; k++)
    {
        Wave w = dev_waves[k];
        float tmp = sin((w.dx * x + w.dy * y) / w.wavelength +
                             *t * w.speed * 0.001 + w.phase) + 1;
        sum += w.amplitude * tmp * tmp / 2.0;
    }
    bitmap[x*WIDTH + y] = sum / WAVES_COUNT  + (255 / 2);
}

void display(void)
{
    static int t = 0;
    timeval start, end_frame, end_compute;
    cudaEvent_t start_event, stop_event;
    float cudaTime;

    gettimeofday(&start, NULL);
    cudaEventCreate(&start_event);
    cudaEventCreate(&stop_event);
    cudaEventRecord(start_event, 0);

    t += 10;
    cudaMemcpy(dev_time, &t, sizeof(int), cudaMemcpyHostToDevice);

    computeBitmap<<<grids, threads>>>(dev_time, dev_bitmap);

    cudaMemcpy(bitmap, dev_bitmap, WIDTH * HEIGHT * sizeof(unsigned char), cudaMemcpyDeviceToHost);

    cudaEventRecord(stop_event, 0);
    cudaEventSynchronize(stop_event);

    gettimeofday(&end_compute, NULL);

    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f (1.0, 1.0, 1.0);
    glRasterPos2i(-1, -1);
    glDrawPixels(WIDTH, HEIGHT, GL_LUMINANCE, GL_UNSIGNED_BYTE, bitmap);
    glutSwapBuffers();
    glutPostRedisplay();

    gettimeofday(&end_frame, NULL);

    cudaEventElapsedTime(&cudaTime, start_event, stop_event);

    printf("Frame time: %d ms, Computation time: %.1f ms\n",
           (end_frame.tv_sec - start.tv_sec) * 1000 + (end_frame.tv_usec - start.tv_usec),
           cudaTime);

    cudaEventDestroy(start_event);
    cudaEventDestroy(stop_event);
}

int main(int argc, char **argv)
{
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(WIDTH, HEIGHT);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("CUDA Demo");
    glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
    glClearColor (0.0, 1.0, 0.0, 0.0);
    glutIdleFunc(display);

    cudaMalloc((void**)&dev_bitmap, WIDTH * HEIGHT * sizeof(unsigned char));
    cudaMalloc((void**)&dev_time, sizeof(int));

    cudaMemcpyToSymbol(dev_waves, waves, WAVES_COUNT * sizeof(Wave));

    glutMainLoop();

    cudaFree(dev_bitmap);
    cudaFree(dev_time);
    cudaFree(dev_waves);
}
<commit_msg>CUDA Step 3: Graphics Interop<commit_after>#include <time.h>
#include <sys/time.h>
#include <stdio.h>

#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glx.h>
#include <GL/glext.h>
#include <GL/freeglut.h>

#include <cuda.h>
#include <cuda_runtime_api.h>
#include <cuda_gl_interop.h>

#include "wave.h"

#define WIDTH 1600
#define HEIGHT 1600

#define WAVES_COUNT 4

Wave waves[WAVES_COUNT] =
{
    {320, 100, 3, 1, 0, 0},
    {320, 60, 5, 5, 2, 0},
    {160, 40, 2, 8, 1, 0},
    {80, 40, 1, -4, 1, 0}
};

unsigned char bitmap[WIDTH][HEIGHT];

unsigned char *dev_bitmap;
int *dev_time;
__constant__ Wave dev_waves[WAVES_COUNT];

dim3 grids(WIDTH/16, HEIGHT/16);
dim3 threads(16, 16);

GLuint buffer;
cudaGraphicsResource *resource;

__global__ void computeBitmap(int *t, unsigned char *bitmap)
{
    int x = threadIdx.x + blockIdx.x * blockDim.x;
    int y = threadIdx.y + blockIdx.y * blockDim.y;

    float sum = 0.0;
    for (int k = 0; k < WAVES_COUNT; k++)
    {
        Wave w = dev_waves[k];
        float tmp = sin((w.dx * x + w.dy * y) / w.wavelength +
                             *t * w.speed * 0.001 + w.phase) + 1;
        sum += w.amplitude * tmp * tmp / 2.0;
    }
    bitmap[x*WIDTH + y] = sum / WAVES_COUNT  + (255 / 2);
}

void display(void)
{
    static int t = 0;
    timeval start, end_frame, end_compute;
    cudaEvent_t start_event, stop_event;
    float cudaTime;

    gettimeofday(&start, NULL);
    cudaEventCreate(&start_event);
    cudaEventCreate(&stop_event);
    cudaEventRecord(start_event, 0);

    t += 10;
    cudaMemcpy(dev_time, &t, sizeof(int), cudaMemcpyHostToDevice);

    size_t size;
    cudaGraphicsMapResources(1, &resource);
    cudaGraphicsResourceGetMappedPointer((void**)&dev_bitmap, &size, resource);

    computeBitmap<<<grids, threads>>>(dev_time, dev_bitmap);

    cudaGraphicsUnmapResources(1, &resource);

    cudaEventRecord(stop_event, 0);
    cudaEventSynchronize(stop_event);

    gettimeofday(&end_compute, NULL);

    glClear(GL_COLOR_BUFFER_BIT);
    glColor3f (1.0, 1.0, 1.0);
    glRasterPos2i(-1, -1);
    glDrawPixels(WIDTH, HEIGHT, GL_LUMINANCE, GL_UNSIGNED_BYTE, NULL);
    glutSwapBuffers();
    glutPostRedisplay();

    gettimeofday(&end_frame, NULL);

    cudaEventElapsedTime(&cudaTime, start_event, stop_event);

    printf("Frame time: %d ms, Computation time: %.1f ms\n",
           (end_frame.tv_sec - start.tv_sec) * 1000 + (end_frame.tv_usec - start.tv_usec),
           cudaTime);

    cudaEventDestroy(start_event);
    cudaEventDestroy(stop_event);
}

int main(int argc, char **argv)
{
    int device;
    cudaGetDevice(&device);
    cudaGLSetGLDevice(device);

    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB);
    glutInitWindowSize(WIDTH, HEIGHT);
    glutInitWindowPosition(100, 100);
    glutCreateWindow("CUDA Demo");
    glPixelStorei (GL_UNPACK_ALIGNMENT, 1);
    glClearColor (0.0, 1.0, 0.0, 0.0);
    glutIdleFunc(display);

    glGenBuffers( 1, &buffer );
    glBindBuffer( GL_PIXEL_UNPACK_BUFFER_ARB, buffer );
    glBufferData( GL_PIXEL_UNPACK_BUFFER_ARB, WIDTH * HEIGHT, NULL, GL_DYNAMIC_DRAW_ARB );

    cudaGraphicsGLRegisterBuffer(&resource, buffer, cudaGraphicsMapFlagsWriteDiscard);

    cudaMalloc((void**)&dev_time, sizeof(int));

    cudaMemcpyToSymbol(dev_waves, waves, WAVES_COUNT * sizeof(Wave));

    glutMainLoop();

    cudaGraphicsUnregisterResource(resource);
}
<|endoftext|>


<commit_before>160e00d7-ad5a-11e7-a8c4-ac87a332f658<commit_msg>fixed bug<commit_after>1686dbfa-ad5a-11e7-9e25-ac87a332f658<|endoftext|>


<commit_before>//#pragma warning(disable : 4425)
#include "rbindv.hpp"	//#include "rbind.hpp"
#include <iostream>
#include <string>

struct Func	{
	int operator ()(int a, int& b, int c = 1) const
		{ return a * 10000 + (b *= 100) + c; }
	int memFun(int a, int b, int c = 1) const
		{ return a * 10000 + b * 100 + c; }
};

int main()
{
	using namespace std::placeholders;
	using namespace mymd::placeholders;
	Func f;
	int a = 2014, b = 2, c = 3, result = 0;
	//----------------------------------------------------------------------------------
	//basic   基本
	auto b1 = mymd::rbind(f, _1, _2, _3);
	result = b1(a, b, c);
	std::cout << "---- basic use" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	std::cout << std::endl;
	auto b1_1 = mymd::rbind(f, until(_3rd));
	result = b1_1(a, b, c);
	std::cout << "---- basic use(placeholders range)" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	std::cout << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 2, c = 10;
	//preset default value     デフォルト値の設定
	auto b2 = mymd::rbind(f, a, _1, _2nd = 11);
	result = b2(b, c);
	std::cout << "---- do not use default value" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	a = 2014, b = 2, c = 10;
	result = b2(b);
	std::cout << "---- use default value for c(=11)" <<std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	std::cout << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 4, c = 30;
	//optional argument     引数省略
	auto b3 = mymd::rbind(_1st, 2014, _2nd, _3rd);
	result = b3(Func(), b);
	std::cout << "---- use default value of original functor for c(=1)" << std::endl;
	std::cout << "b = " << b << ", c = " << c << ", result = " << result << std::endl;
	std::cout << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 2, c = 1;
	std::string str("abcdefg");
	//convert argument by yield method     yieldメソッドによる引数変換
	auto b4 = mymd::rbind(&Func::memFun	,
			    &f			,
			    2014		,
			    _1			,
			    _2nd.yield([](const std::string& s){ return s.length(); })
			    );
	result = b4(b, str);
	std::cout << "---- convert augument by yield for the last argument" << std::endl;
	std::cout << "b = " << b << ", s = " << str << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	return 0;
}
<commit_msg>Update main.cpp<commit_after>#include "rbindv.hpp"	//#include "rbind.hpp"
#include <iostream>
#include <string>
#include <type_traits>

struct Func	{
	int operator ()(int a, int& b, int c = 1) const
		{ return a * 10000 + (b *= 100) + c; }
	int memFun(int a, int b, int c = 1) const
		{ return a * 10000 + b * 100 + c; }
};

int main()
{
	using namespace std::placeholders;
	using namespace mymd::placeholders;
	Func f;
	int a = 2014, b = 2, c = 3, result = 0;
	//----------------------------------------------------------------------------------
	//basic   基本
	auto b1 = mymd::rbind(f, _1, _2, _3);
	result = b1(a, b, c);
	std::cout << "---- basic use" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	auto b1_1 = mymd::rbind(f, until(_3rd));
	result = b1_1(a, b, c);
	std::cout << "---- basic use(placeholders range)" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 2, c = 10;
	//preset default value     デフォルト値の設定
	auto b2 = mymd::rbind(f, a, _1, _2nd = 11);
	result = b2(b, c);
	std::cout << "---- do not use default value" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	a = 2014, b = 2, c = 10;
	result = b2(b);
	std::cout << "---- use default value for c(=11)" <<std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 4, c = 30;
	//optional argument     引数省略
	auto b3 = mymd::rbind(_1st, 2014, _2nd, _3rd);
	result = b3(Func(), b);
	std::cout << "---- use default value of original functor for c(=1)" << std::endl;
	std::cout << "b = " << b << ", c = " << c << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	a = 2014, b = 2, c = 1;
	std::string str("abcdefg");
	//convert argument by yield method     yieldメソッドによる引数変換
	auto b4 = mymd::rbind(&Func::memFun	,
			    &f			,
			    2014		,
			    _1			,
			    _2nd.yield([](const std::string& s){ return s.length(); })
			    );
	result = b4(b, str);
	std::cout << "---- convert augument by yield for the last argument" << std::endl;
	std::cout << "b = " << b << ", s = " << str << ", result = " << result << std::endl;
	//----------------------------------------------------------------------------------
	//parameter type assert   引数の型の制約
	auto b5 = mymd::rbind(f, _1, _2, _3rd.assert<std::is_integral>());
	result = b5(a, b=8, c=23);
	std::cout << "---- parameter type assert" << std::endl;
	std::cout << "a = " << a << ", b = " << b << ", c = " << c << ", result = " << result << std::endl;
	return 0;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <map>
#include "3rdparty/tinyxml2/tinyxml2.h"
using namespace tinyxml2;
using namespace std;

typedef uint32_t (*func)(void*);
char gMem[1024];
uint32_t gMemFreeStart = 0;
map<string,func> gFuncMap;
map<string,char*> gMemMap;

uint32_t cmd_fopen(void*param){
    cout<<"1) open file"<<endl;
    XMLElement* e = (XMLElement*)param;

    const char* hd = e->Attribute("handle");
    const char* md = e->Attribute("mode");
    const char* fn = e->Attribute("file");
    if(!hd || !md || !fn){
        cout<<"Errror!no attr"<<endl;
        return 0;
    }

    FILE* f = fopen(fn,md);
    memcpy(gMem+gMemFreeStart,f,sizeof(FILE*));
    gMemFreeStart += sizeof(FILE*);

    // 变量名和内存映射关系
    gMemMap.insert(pair<string,char*>(string(hd),(char*)f));

    return 0;
}
uint32_t cmd_fwrite(void* param){
    cout<<"2) write file"<<endl;
    XMLElement* e = (XMLElement*)param;

    const char* hd = e->Attribute("handle");
    const char* dt= e->Attribute("data");
    int sz;
    XMLError err = e->QueryIntAttribute("size",&sz);
    if(!hd || !dt || (err!=XML_NO_ERROR)) {
        cout << "Errror!attr error" << endl;
        return 0;
    }
    FILE* f = (FILE*)gMemMap.find(hd)->second;
    fwrite(dt,sizeof(char),sz,f);

    return 0;
}
uint32_t cmd_fclose(void* param){
    cout<<"3) close file"<<endl;
    XMLElement* e = (XMLElement*)param;
    const char* hd = e->Attribute("handle");
    if(!hd){
        cout<<"Error!Attr error!"<<endl;
        return 0;
    }
    FILE* f = (FILE*)gMemMap.find(hd)->second;
    fclose(f);
    return 0;
}

int main___t() {

    gFuncMap.insert(pair<string,func>("fopen",cmd_fopen));
    gFuncMap.insert(pair<string,func>("fwrite",cmd_fwrite));
    gFuncMap.insert(pair<string,func>("fclose",cmd_fclose));

    XMLDocument doc;
    XMLError err = XML_NO_ERROR;
    err = doc.LoadFile("/Users/tkorays/invoker/task.xml");
    if(err!=XML_NO_ERROR){
        cout<<"Open File Failed"<<endl;
        return 0;
    }

    XMLElement* e = doc.FirstChildElement("proc");
    if(e==0){
        cout<<"root node must be a proc"<<endl;
        return 0;
    }
    e = e->FirstChildElement();
    while(e){
        const char* proc_name = e->Name();

        // 查表获取函数入口
        map<string,func>::iterator it = gFuncMap.find(string(proc_name));
        if(it==gFuncMap.end()){
            cout<<"not found proc function"<<endl;
        }else{
            func f = it->second;
            f((void*)e);
        }
        e = e->NextSiblingElement();
    }
    return 0;
}<commit_msg>rm main file<commit_after><|endoftext|>


<commit_before>#define ALL
#ifdef ALL
#include <iostream>

#include <n/core/Timer.h>

#include <n/math/Plane.h>
#include <n/io/File.h>

#include <SDL2/SDL.h>
#include <n/graphics/ImageLoader.h>
#include <n/graphics/GLContext.h>
#include <n/graphics/Texture.h>
#include <n/graphics/Scene.h>
#include <n/graphics/GL.h>
#include <n/graphics/StaticBuffer.h>
#include <n/graphics/TriangleBuffer.h>
#include <n/graphics/VertexArrayObject.h>
#include <n/graphics/ShaderCombinaison.h>
#include <n/graphics/Camera.h>
#include <n/graphics/StaticMesh.h>
#include <n/graphics/Material.h>
#include <n/graphics/MeshLoader.h>
#include <n/graphics/MaterialLoader.h>

#include <n/math/StaticConvexVolume.h>
#include <n/math/ConvexVolume.h>

using namespace n;
using namespace n::graphics;
using namespace n::math;
using namespace n::core;

SDL_Window *createWindow() {
	SDL_Window *mainWindow = 0;
	if(SDL_Init(SDL_INIT_VIDEO) < 0) {
		fatal("Unable to initialize SDL");
	}
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	if(!(mainWindow = SDL_CreateWindow("n 2.1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN))) {
		fatal("Unable to create window");
	}
	SDL_GL_CreateContext(mainWindow);
	SDL_GL_SetSwapInterval(0);

	GLContext::getContext();

	return mainWindow;
}

bool run(SDL_Window *mainWindow) {
	SDL_GL_SwapWindow(mainWindow);
	SDL_Event e;
	bool cc = true;
	while(SDL_PollEvent(&e)) {
		if(e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)) {
			cc = false;
			break;
		}
	}
	return cc;
}

class Cube : public StaticMesh
{
	public:
		Cube() : StaticMesh(MeshLoader::load<String>("scube.obj")) {
			axis = ((Vec3(random(), random(), random()) - 0.5) * 2).normalized();
		}

		virtual void render(RenderQueue &qu) override {
			static Timer timer;
			static double x = 0;
			double t = timer.reset();
			x += t;
			Quaternion<> q = Quaternion<>::fromAxisAngle(axis.cross(Vec3(1, 0, 0)).cross(axis), t);
			axis = q(axis);
			setRotation(Quaternion<>::fromAxisAngle(axis, x));
			if(!getMeshInstance().isValid()) {
				fatal("Unable to load mesh");
			}
			StaticMesh::render(qu);
		}

	private:
		Vec3 axis;
};

int main(int, char **) {

	SDL_Window *win = createWindow();

	Shader<VertexShader> vert("#version 420 core\n"
										"layout(location = 0) in vec3 n_VertexPosition;"
										"layout(location = 1) in vec3 n_VertexNormal;"
										"uniform mat4 n_ViewProjectionMatrix;"
										"uniform mat4 n_ModelMatrix;"
										"out vec3 normal;"
										"void main() {"
											"gl_Position = n_ViewProjectionMatrix * n_ModelMatrix * vec4(n_VertexPosition, 1.0);"
											"normal = (n_ModelMatrix * vec4(n_VertexNormal, 1.0)).xyz;"
										"}");

	Shader<FragmentShader> frag("#version 420 core\n"
										"layout(location = 0) out vec4 n_FragColor;"
										"in vec3 normal;"
										"uniform vec4 n_Color;"
										"void main() {"
											//"n_FragColor = vec4(color * 0.5 + 0.5, 1.0);"
											"n_FragColor = vec4(vec3(dot(normal, normalize(vec3(1, 1, 1))) * 0.75 + 0.25) * n_Color.rgb, n_Color.a);"
										"}");

	ShaderCombinaison shader(&frag, &vert, 0);
	if(!shader.isValid()) {
		std::cerr<<shader.getLogs()<<std::endl;
		std::cerr<<frag.getLogs()<<std::endl;
		std::cerr<<vert.getLogs()<<std::endl;
		fatal("Unable to compile shader.");
	}

	shader.bind();

	Camera cam;
	cam.setPosition(Vec3(0, 0, 3));
	cam.setRotation(Quaternion<>::fromEuler(0, toRad(90), 0));

	GLContext::getContext()->setProjectionMatrix(cam.getProjectionMatrix());
	GLContext::getContext()->setViewMatrix(cam.getViewMatrix());
	Scene scene;
	/*for(uint i = 0; i != 1000; i++) {
		Cube *cube = new Cube();
		cube->setPosition(Vec3(random(), random(), random()) * 100 - 50);
		scene.insert(cube);
	}*/

	scene.insert(new Cube());

	while(run(win)) {
		Timer timer;
		gl::glClear(GL_COLOR_BUFFER_BIT);
		core::Array<StaticMesh *> meshes = scene.query<StaticMesh>(cam);
		RenderQueue queue;
		for(Renderable *m : meshes) {
			m->render(queue);
		}
		for(const auto &q : queue.getBatches()) {
			q();
		}
		GLContext::getContext()->processTasks();
		if(GLContext::checkGLError()) {
			fatal("GL error");
		}
		gl::glFlush();
	}
	return 0;
}

#else

#include <n/core/Array.h>

int main(int, char **) {
	return 0;
}

#endif

<commit_msg>Oren-Nayar shading<commit_after>#define ALL
#ifdef ALL
#include <iostream>

#include <n/core/Timer.h>

#include <n/math/Plane.h>
#include <n/io/File.h>

#include <SDL2/SDL.h>
#include <n/graphics/ImageLoader.h>
#include <n/graphics/GLContext.h>
#include <n/graphics/Texture.h>
#include <n/graphics/Scene.h>
#include <n/graphics/GL.h>
#include <n/graphics/StaticBuffer.h>
#include <n/graphics/TriangleBuffer.h>
#include <n/graphics/VertexArrayObject.h>
#include <n/graphics/ShaderCombinaison.h>
#include <n/graphics/Camera.h>
#include <n/graphics/StaticMesh.h>
#include <n/graphics/Material.h>
#include <n/graphics/MeshLoader.h>
#include <n/graphics/MaterialLoader.h>

#include <n/math/StaticConvexVolume.h>
#include <n/math/ConvexVolume.h>

using namespace n;
using namespace n::graphics;
using namespace n::math;
using namespace n::core;

SDL_Window *createWindow() {
	SDL_Window *mainWindow = 0;
	if(SDL_Init(SDL_INIT_VIDEO) < 0) {
		fatal("Unable to initialize SDL");
	}
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 4);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 2);
	SDL_GL_SetAttribute(SDL_GL_CONTEXT_PROFILE_MASK, SDL_GL_CONTEXT_PROFILE_CORE);
	if(!(mainWindow = SDL_CreateWindow("n 2.1", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL | SDL_WINDOW_SHOWN))) {
		fatal("Unable to create window");
	}
	SDL_GL_CreateContext(mainWindow);
	SDL_GL_SetSwapInterval(0);

	GLContext::getContext();

	return mainWindow;
}

bool run(SDL_Window *mainWindow) {
	SDL_GL_SwapWindow(mainWindow);
	SDL_Event e;
	bool cc = true;
	while(SDL_PollEvent(&e)) {
		if(e.type == SDL_QUIT || (e.type == SDL_KEYDOWN && e.key.keysym.sym == SDLK_ESCAPE)) {
			cc = false;
			break;
		}
	}
	return cc;
}

class Cube : public StaticMesh
{
	public:
		Cube() : StaticMesh(MeshLoader::load<String>("scube.obj")) {
			axis = ((Vec3(random(), random(), random()) - 0.5) * 2).normalized();
		}

		virtual void render(RenderQueue &qu) override {
			static Timer timer;
			static double x = 0;
			double t = timer.reset();
			x += t;
			Quaternion<> q = Quaternion<>::fromAxisAngle(axis.cross(Vec3(1, 0, 0)).cross(axis), t);
			axis = q(axis);
			setRotation(Quaternion<>::fromAxisAngle(axis, x));
			if(!getMeshInstance().isValid()) {
				fatal("Unable to load mesh");
			}
			StaticMesh::render(qu);
		}

	private:
		Vec3 axis;
};

int main(int, char **) {

	SDL_Window *win = createWindow();

	Shader<VertexShader> vert("#version 420 core\n"
										"layout(location = 0) in vec3 n_VertexPosition;"
										"layout(location = 1) in vec3 n_VertexNormal;"
										"uniform mat4 n_ViewProjectionMatrix;"
										"uniform mat4 n_ModelMatrix;"
										"uniform vec3 n_Camera;"

										"out vec3 normal;"
										"out vec3 view;"

										"void main() {"
											"vec4 model = n_ModelMatrix * vec4(n_VertexPosition, 1.0);"
											"gl_Position = n_ViewProjectionMatrix * model;"
											"view = n_Camera - model.xyz;"
											"normal = (n_ModelMatrix * vec4(n_VertexNormal, 1.0)).xyz;"
										"}");

	Shader<FragmentShader> frag("#version 420 core\n"
										"layout(location = 0) out vec4 n_FragColor;"
										"in vec3 normal;"
										"in vec3 view;"
										"uniform vec4 n_Color;"
										"uniform vec3 n_Roughness;"

										"void main() {"
											"vec3 L = normalize(vec3(1, 1, 1));"
											"float o2 = n_Roughness * n_Roughness;"
											"float A = 1.0 - 0.5 * o2 / (o2 + 0.33);"
											"float B = (0.45 * o2) / (o2 + 0.09);"
											"float vn = dot(view, normal);"
											"float ln = dot(L, normal);"
											"float I = max(0.0, ln);"
											"float avn = acos(vn);"
											"float aln = acos(ln);"
											"float diff = max(0.0, dot(normalize(view - normal * vn), normalize(L - normal * ln)));"
											"float alpha = max(avn, aln);"
											"float beta = min(avn, aln);"
											"n_FragColor = n_Color * I * A + B * diff * sin(alpha) * tan(beta);"

										"}");

	ShaderCombinaison shader(&frag, &vert, 0);
	if(!shader.isValid()) {
		std::cerr<<shader.getLogs()<<std::endl;
		std::cerr<<frag.getLogs()<<std::endl;
		std::cerr<<vert.getLogs()<<std::endl;
		fatal("Unable to compile shader.");
	}

	shader.bind();

	Camera cam;
	cam.setPosition(Vec3(0, 0, 3));
	shader["n_Camera"] = Vec3(0, 0, 3);
	cam.setRotation(Quaternion<>::fromEuler(0, toRad(90), 0));

	GLContext::getContext()->setProjectionMatrix(cam.getProjectionMatrix());
	GLContext::getContext()->setViewMatrix(cam.getViewMatrix());
	Scene scene;
	/*for(uint i = 0; i != 1000; i++) {
		Cube *cube = new Cube();
		cube->setPosition(Vec3(random(), random(), random()) * 100 - 50);
		scene.insert(cube);
	}*/

	scene.insert(new Cube());

	while(run(win)) {
		Timer timer;
		gl::glClear(GL_COLOR_BUFFER_BIT);
		core::Array<StaticMesh *> meshes = scene.query<StaticMesh>(cam);
		RenderQueue queue;
		for(Renderable *m : meshes) {
			m->render(queue);
		}
		for(const auto &q : queue.getBatches()) {
			q();
		}
		GLContext::getContext()->processTasks();
		if(GLContext::checkGLError()) {
			fatal("GL error");
		}
		gl::glFlush();
	}
	return 0;
}

#else

#include <n/core/Array.h>

int main(int, char **) {
	return 0;
}

#endif

<|endoftext|>


<commit_before>#include <bits/stdc++.h>
using namespace std;

#define MAXN    100005
#define clip(X) min(X,10000)

// IMPLEMENTACAO/TESTES
// antes, procurar formulas menores nas maiores, mais ou menos R² * d(phi)
// dp para otimizar o renaming restringindo o nro maximo de literais
// procurar um benchmark
// adaptar entrada para o benchmark
// adaptar saida para algum provador, colocando em CNF

// MONOGRAFIA
// colocar exemplo 3.2

// formula
enum {CONJ=0,DISJ,IMPL,EQUI,NEGA,ATOM};
struct Vertex {
  char type;
  int literal;
  int up;
  vector<int> down;
  int p;
  Vertex() : p(1) {}
} G[MAXN];
int V = 0;

// create tree parsing formula from string
// first: tree
// second: number of literals
pair<vector<Vertex>,int> parse(string phi) {
  // check
  auto isvarsym = [](char c) {
    return
      ('0' <= c && c <= '9') ||
      ('a' <= c && c <= 'z') ||
      ('A' <= c && c <= 'Z')
    ;
  };

  vector<Vertex> ret(1);
  ret.back().type = CONJ;
  ret.back().up = 0;
  stack<int> S;
  S.push(0);
  map<string,int> id;
  int nextlit = 1;
  for (int i = 0; i < phi.size(); i++) {
    char c = phi[i];
    if (c == ' ' || c == '\t') continue;
    else if (c == '&') ret[S.top()].type = CONJ;
    else if (c == '|') ret[S.top()].type = DISJ;
    else if (c == '=') { ret[S.top()].type = IMPL; i++; }
    else if (c == '<') { ret[S.top()].type = EQUI; i += 2; }
    else if (c == '(' || c == '~') {
      S.push(ret.size());
      ret.emplace_back();
      ret.back().type = (c == '(' ? CONJ : NEGA);
    }
    else if (c == ')') {
      int u = S.top();
      S.pop();
      ret[u].up = S.top();
      ret[S.top()].down.push_back(u);
      if (ret[u].type != NEGA && ret[u].down.size() == 1) {
        int u1 = ret[u].down.front();
        ret[u].type = ret[u1].type;
        ret[u].down = ret[u1].down;
        for (int v : ret[u].down) ret[v].up = u;
      }
    }
    else { // literal
      string tmp = {phi[i]};
      while (i+1 < phi.size() && isvarsym(phi[i+1])) tmp += phi[++i];
      int& lit = id[tmp];
      if (!lit) lit = nextlit++;
      ret[S.top()].down.push_back(ret.size());
      ret.emplace_back();
      ret.back().type = ATOM;
      ret.back().literal = lit;
      ret.back().up = S.top();
      if (ret[S.top()].type == NEGA) { phi[i] = ')'; i--; }
    }
  }
  if (ret[0].down.size() == 1) {
    int u = ret[0].down.front();
    ret[0].type = ret[u].type;
    ret[0].down = ret[u].down;
    for (int v : ret[0].down) ret[v].up = 0;
  }
  return make_pair(ret,id.size());
}

void nnf(vector<Vertex>& T) {
  // copy tree rooted at u
  function<int(int)> copy = [&](int u) {
    int nu = T.size(); T.emplace_back();
    T[nu].type = T[u].type;
    T[nu].literal = T[u].literal;
    for (int v : T[u].down) {
      int tmp = copy(v);
      T[tmp].up = nu;
      T[nu].down.push_back(tmp);
    }
    return nu;
  };

  // remove implications and equivalences
  function<void(int)> dfs1 = [&](int u) {
    if (T[u].type == IMPL) {
      T[u].type = DISJ;
      int v = T[u].down.front();
      int negi = T.size(); T.emplace_back();
      T[negi].type = NEGA;
      T[u].down.front() = negi;
      T[negi].up = u;
      T[negi].down.push_back(v);
      T[v].up = negi;
    }
    else if (T[u].type == EQUI) {
      auto f = [&](int a, int b) {
        int impi = T.size(); T.emplace_back();
        T[impi].type = IMPL;
        T[u].down.push_back(impi);
        T[impi].up = u;
        T[impi].down.push_back(a), T[impi].down.push_back(b);
        T[a].up = impi, T[b].up = impi;
      };
      T[u].type = CONJ;
      int a = T[u].down.front(),  b = T[u].down.back();
      int c = copy(b),            d = copy(a);
      T[u].down.clear();
      f(a,b);
      f(c,d);
    }
    for (int v : T[u].down) dfs1(v);
  };
  dfs1(0);

  // remove negations
  function<void(int,bool)> dfs2 = [&](int u, bool neg) {
    if (!neg) {
      if (T[u].type == NEGA) {
        auto& phi1 = T[T[u].down.front()];
        if (phi1.type == NEGA) {
          auto& phi2 = T[phi1.down.front()];
          T[u].type = phi2.type;
          T[u].literal = phi2.literal;
          T[u].down = phi2.down;
          for (int v : T[u].down) T[v].up = u;
          phi1.type = CONJ, phi2.type = CONJ; // removing phi1 and phi2
        }
        else if (phi1.type != ATOM) { // CONJ or DISJ
          T[u].type = (phi1.type == CONJ ? DISJ : CONJ);
          T[u].down = phi1.down;
          for (int v : T[u].down) T[v].up = u;
          phi1.type = CONJ; // removing phi1
          neg = true;
        }
      }
    }
    else {
      if (T[u].type == NEGA) {
        auto& phi1 = T[T[u].down.front()];
        T[u].type = phi1.type;
        T[u].literal = phi1.literal;
        T[u].down = phi1.down;
        for (int v : T[u].down) T[v].up = u;
        phi1.type = CONJ; // removing phi1
        neg = false;
      }
      else if (T[u].type != ATOM) { // CONJ or DISJ
        T[u].type = (T[u].type == CONJ ? DISJ : CONJ);
      }
      else { // ATOM
        int atmi = copy(u);
        T[u].type = NEGA;
        T[u].down.push_back(atmi);
        T[atmi].up = u;
        neg = false;
      }
    }
    for (int v : T[u].down) dfs2(v,neg);
  };
  dfs2(0,false);
}

// build DAG from tree T
void build(const vector<Vertex>& T) {
  map<int,int> lit_newu;
  map<int,multiset<int>> oldp_newc;
  V = 1;

  // create vertices for literals
  for (int i = 0; i < T.size(); i++) if (T[i].type == ATOM) {
    auto& phi = T[i];
    int& u = lit_newu[phi.literal];
    if (!u) {
      u = ++V;
      G[u].type = ATOM;
      G[u].literal = phi.literal;
    }
    oldp_newc[phi.up].insert(u);
  }

  // search tree bottom-up to create vertices for subformulas
  for (map<multiset<int>,int> newc_newp; !oldp_newc.empty();) {
    list<pair<int,int>> tmp;
    for (auto kv = oldp_newc.begin(); kv != oldp_newc.end();) {
      auto& phi = T[kv->first];
      if (kv->second.size() < phi.down.size()) { kv++; continue; }
      int& u = newc_newp[kv->second];
      if (!u) {
        u = (phi.up != kv->first) ? ++V : 1;
        G[u].type = phi.type;
        for (int v : kv->second) G[u].down.push_back(v);
      }
      if (phi.up != kv->first) tmp.emplace_back(phi.up,u);
      oldp_newc.erase(kv++);
    }
    for (auto& kv : tmp) oldp_newc[kv.first].insert(kv.second);
  }
}

// position of u in a reverse toposort
int pos(int u) {
  static int next = 1, dp[MAXN] = {};
  int& ans = dp[u];
  if (ans) return ans;
  for (int v : G[u].down) pos(v);
  return ans = next++;
}

// p(phi(u))
int p(int u) {
  static int dp[MAXN] = {};
  int& ans = dp[u];
  if (ans) return ans;
  switch (G[u].type) {
    case CONJ: ans = 0; for (int v : G[u].down) ans = clip(ans+p(v)); break;
    case DISJ: ans = 1; for (int v : G[u].down) ans = clip(ans*p(v)); break;
    default:   ans = 1; break;
  }
  return ans;
}

// Boy de la Tour's top-down renaming
vector<int> R;
int nextR;
void R_rec(int u, int a) {
  auto& phi = G[u];
  if (phi.p == 1) return;

  // check renaming condition
  bool renamed = false;
  if (a > 1) {
    a = 1;
    renamed = true;
  }

  // search children
  if (phi.type == CONJ) {
    for (int v : phi.down) R_rec(v,a);
    phi.p = 0; for (int v : phi.down) phi.p = clip(phi.p+G[v].p);
  }
  else { // phi.type == DISJ
    int n = phi.down.size();

    vector<int> dp(n,1); // dp[i] = prod(phi_j.p), i < j < n
    for (int i = n-2; 0 <= i; i--) dp[i] = clip(G[phi.down[i+1]].p*dp[i+1]);

    int ai = a; // ai = a*prod(phi_j.p), 0 <= j < i
    for (int i = 0; i < n; i++) {
      R_rec(phi.down[i],clip(ai*dp[i]));
      ai = clip(ai*G[phi.down[i]].p);
    }
    phi.p = 1; for (int v : phi.down) phi.p = clip(phi.p*G[v].p);
  }

  if (renamed) {
    R.push_back(u);
    phi.type |= (1<<7);
    phi.literal = nextR++;
    phi.p = 1;
  }
}

// pretty print formula root at u
void print(int u, bool enclose = true) {
  auto& phi = G[u];

  // literal
  if (phi.type == ATOM || phi.type&(1<<7)) {
    cout << 'p' << phi.literal;
    return;
  }

  // negation
  if (phi.type == NEGA) {
    cout << '~';
    print(phi.down.front());
    return;
  }

  // subformulas
  if (enclose) cout << '(';
  char op = phi.type == CONJ ? '&' : '|';
  bool printed = false;
  for (int v : phi.down) {
    if (printed) cout << " " << op << " ";
    printed = true;
    print(v);
  }
  if (enclose) cout << ')';
}

int main() {

  // input
  string phi;
  getline(cin,phi);

  // preprocess
  auto tree = parse(phi);
  nnf(tree.first);
  build(tree.first);
  auto toposort = [](int u, int v){ return pos(u) < pos(v); };
  for (int u = 1; u <= V; u++) {
    auto& phi = G[u];
    sort(phi.down.begin(),phi.down.end(),toposort);
    phi.p = p(u);
  }
  print(1,false);
  cout << endl;

  // renaming
  nextR = tree.second+1;
  R_rec(1,1);

  // output
  print(1);
  for (int u : R) {
    auto& phi = G[u];
    printf(" & (~p%d | ",phi.literal);
    phi.type &= ~(1<<7);
    print(u);
    phi.type |=  (1<<7);
    printf(")");
  }
  cout << endl;

  return 0;
}
<commit_msg>Improving comments<commit_after>#include <bits/stdc++.h>
using namespace std;

#define MAXN    100005
#define clip(X) min(X,10000)

// IMPLEMENTACAO/TESTES
// procurar formulas menores nas maiores, mais ou menos R² * d(phi) (melhoria1)
// dp para otimizar o renaming limitando o nro maximo de literais   (melhoria2)
// procurar um benchmark e adaptar a entrada para ele
// adaptar a saida para algum provador, colocando em CNF

// MONOGRAFIA
// colocar exemplo 3.2

// formula
enum {CONJ=0,DISJ,IMPL,EQUI,NEGA,ATOM};
struct Vertex {
  char type;
  int literal;
  int up;
  vector<int> down;
  int p;
  Vertex() : p(1) {}
} G[MAXN];
int V = 0;

// create tree parsing formula from string
// first: tree
// second: number of literals
pair<vector<Vertex>,int> parse(string phi) {
  // tells if a character is valid for a variable name
  auto isvarsym = [](char c) {
    return
      ('0' <= c && c <= '9') ||
      ('a' <= c && c <= 'z') ||
      ('A' <= c && c <= 'Z')
    ;
  };

  vector<Vertex> ret(1);
  ret.back().type = CONJ;
  ret.back().up = 0;
  stack<int> S;
  S.push(0);
  map<string,int> id;
  int nextlit = 1;
  for (int i = 0; i < phi.size(); i++) {
    char c = phi[i];
    if (c == ' ' || c == '\t') continue;
    else if (c == '&') ret[S.top()].type = CONJ;
    else if (c == '|') ret[S.top()].type = DISJ;
    else if (c == '=') { ret[S.top()].type = IMPL; i++; }
    else if (c == '<') { ret[S.top()].type = EQUI; i += 2; }
    else if (c == '(' || c == '~') { // push
      S.push(ret.size());
      ret.emplace_back();
      ret.back().type = (c == '(' ? CONJ : NEGA);
    }
    else if (c == ')') { // pop
      int u = S.top();
      S.pop();
      ret[u].up = S.top();
      ret[S.top()].down.push_back(u);
      // removing multiple parentheses
      if (ret[u].type != NEGA && ret[u].down.size() == 1) {
        int u1 = ret[u].down.front();
        ret[u].type = ret[u1].type;
        ret[u].down = ret[u1].down;
        for (int v : ret[u].down) ret[v].up = u;
      }
    }
    else { // literal
      string tmp = {phi[i]};
      while (i+1 < phi.size() && isvarsym(phi[i+1])) tmp += phi[++i];
      int& lit = id[tmp];
      if (!lit) lit = nextlit++;
      ret[S.top()].down.push_back(ret.size());
      ret.emplace_back();
      ret.back().type = ATOM;
      ret.back().literal = lit;
      ret.back().up = S.top();
      if (ret[S.top()].type == NEGA) { phi[i] = ')'; i--; }
    }
  }
  // removing multiple parentheses
  if (ret[0].down.size() == 1) {
    int u = ret[0].down.front();
    ret[0].type = ret[u].type;
    ret[0].down = ret[u].down;
    for (int v : ret[0].down) ret[v].up = 0;
  }
  return make_pair(ret,id.size());
}

void nnf(vector<Vertex>& T) {
  // copy tree rooted at u
  function<int(int)> copy = [&](int u) {
    int nu = T.size(); T.emplace_back();
    T[nu].type = T[u].type;
    T[nu].literal = T[u].literal;
    for (int v : T[u].down) {
      int tmp = copy(v);
      T[tmp].up = nu;
      T[nu].down.push_back(tmp);
    }
    return nu;
  };

  // remove implications and equivalences
  function<void(int)> dfs1 = [&](int u) {
    if (T[u].type == IMPL) {
      T[u].type = DISJ;
      int v = T[u].down.front();
      int negi = T.size(); T.emplace_back();
      T[negi].type = NEGA;
      T[u].down.front() = negi;
      T[negi].up = u;
      T[negi].down.push_back(v);
      T[v].up = negi;
    }
    else if (T[u].type == EQUI) {
      auto f = [&](int a, int b) {
        int impi = T.size(); T.emplace_back();
        T[impi].type = IMPL;
        T[u].down.push_back(impi);
        T[impi].up = u;
        T[impi].down.push_back(a), T[impi].down.push_back(b);
        T[a].up = impi, T[b].up = impi;
      };
      T[u].type = CONJ;
      int a = T[u].down.front(),  b = T[u].down.back();
      int c = copy(b),            d = copy(a);
      T[u].down.clear();
      f(a,b);
      f(c,d);
    }
    for (int v : T[u].down) dfs1(v);
  };
  dfs1(0);

  // remove negations
  function<void(int,bool)> dfs2 = [&](int u, bool neg) {
    if (!neg) {
      if (T[u].type == NEGA) {
        auto& phi1 = T[T[u].down.front()];
        if (phi1.type == NEGA) {
          auto& phi2 = T[phi1.down.front()];
          T[u].type = phi2.type;
          T[u].literal = phi2.literal;
          T[u].down = phi2.down;
          for (int v : T[u].down) T[v].up = u;
          phi1.type = CONJ, phi2.type = CONJ; // removing phi1 and phi2
        }
        else if (phi1.type != ATOM) { // CONJ or DISJ
          T[u].type = (phi1.type == CONJ ? DISJ : CONJ);
          T[u].down = phi1.down;
          for (int v : T[u].down) T[v].up = u;
          phi1.type = CONJ; // removing phi1
          neg = true;
        }
      }
    }
    else {
      if (T[u].type == NEGA) {
        auto& phi1 = T[T[u].down.front()];
        T[u].type = phi1.type;
        T[u].literal = phi1.literal;
        T[u].down = phi1.down;
        for (int v : T[u].down) T[v].up = u;
        phi1.type = CONJ; // removing phi1
        neg = false;
      }
      else if (T[u].type != ATOM) { // CONJ or DISJ
        T[u].type = (T[u].type == CONJ ? DISJ : CONJ);
      }
      else { // ATOM
        int atmi = copy(u);
        T[u].type = NEGA;
        T[u].down.push_back(atmi);
        T[atmi].up = u;
        neg = false;
      }
    }
    for (int v : T[u].down) dfs2(v,neg);
  };
  dfs2(0,false);
}

// build DAG from tree T
void build(const vector<Vertex>& T) {
  map<int,int> lit_newu;
  map<int,multiset<int>> oldp_newc;
  V = 1;

  // create vertices for literals
  for (int i = 0; i < T.size(); i++) if (T[i].type == ATOM) {
    auto& phi = T[i];
    int& u = lit_newu[phi.literal];
    if (!u) {
      u = ++V;
      G[u].type = ATOM;
      G[u].literal = phi.literal;
    }
    oldp_newc[phi.up].insert(u);
  }

  // search tree bottom-up to create vertices for subformulas
  for (map<multiset<int>,int> newc_newp; !oldp_newc.empty();) {
    list<pair<int,int>> tmp;
    for (auto kv = oldp_newc.begin(); kv != oldp_newc.end();) {
      auto& phi = T[kv->first];
      if (kv->second.size() < phi.down.size()) { kv++; continue; }
      int& u = newc_newp[kv->second];
      if (!u) {
        u = (phi.up != kv->first) ? ++V : 1;
        G[u].type = phi.type;
        for (int v : kv->second) G[u].down.push_back(v);
      }
      if (phi.up != kv->first) tmp.emplace_back(phi.up,u);
      oldp_newc.erase(kv++);
    }
    for (auto& kv : tmp) oldp_newc[kv.first].insert(kv.second);
  }
}

// position of u in a reverse toposort
int pos(int u) {
  static int next = 1, dp[MAXN] = {};
  int& ans = dp[u];
  if (ans) return ans;
  for (int v : G[u].down) pos(v);
  return ans = next++;
}

// p(phi(u))
int p(int u) {
  static int dp[MAXN] = {};
  int& ans = dp[u];
  if (ans) return ans;
  switch (G[u].type) {
    case CONJ: ans = 0; for (int v : G[u].down) ans = clip(ans+p(v)); break;
    case DISJ: ans = 1; for (int v : G[u].down) ans = clip(ans*p(v)); break;
    default:   ans = 1; break;
  }
  return ans;
}

// Boy de la Tour's top-down renaming
vector<int> R;
int nextR;
void R_rec(int u, int a) {
  auto& phi = G[u];
  if (phi.p == 1) return;

  // check renaming condition
  bool renamed = false;
  if (a > 1) {
    a = 1;
    renamed = true;
  }

  // search children
  if (phi.type == CONJ) {
    for (int v : phi.down) R_rec(v,a);
    phi.p = 0; for (int v : phi.down) phi.p = clip(phi.p+G[v].p);
  }
  else { // phi.type == DISJ
    int n = phi.down.size();

    vector<int> dp(n,1); // dp[i] = prod(phi_j.p), i < j < n
    for (int i = n-2; 0 <= i; i--) dp[i] = clip(G[phi.down[i+1]].p*dp[i+1]);

    int ai = a; // ai = a*prod(phi_j.p), 0 <= j < i
    for (int i = 0; i < n; i++) {
      R_rec(phi.down[i],clip(ai*dp[i]));
      ai = clip(ai*G[phi.down[i]].p);
    }
    phi.p = 1; for (int v : phi.down) phi.p = clip(phi.p*G[v].p);
  }

  if (renamed) {
    R.push_back(u);
    phi.type |= (1<<7);
    phi.literal = nextR++;
    phi.p = 1;
  }
}

// pretty print formula rooted at u
void print(int u, bool enclose = true) {
  auto& phi = G[u];

  // literal
  if (phi.type == ATOM || phi.type&(1<<7)) {
    cout << 'p' << phi.literal;
    return;
  }

  // negation
  if (phi.type == NEGA) {
    cout << '~';
    print(phi.down.front());
    return;
  }

  // subformulas
  if (enclose) cout << '(';
  char op = phi.type == CONJ ? '&' : '|';
  bool printed = false;
  for (int v : phi.down) {
    if (printed) cout << " " << op << " ";
    printed = true;
    print(v);
  }
  if (enclose) cout << ')';
}

int main() {

  // input
  string phi;
  getline(cin,phi);

  // preprocess
  auto tree = parse(phi);
  nnf(tree.first);
  build(tree.first);
  auto toposort = [](int u, int v){ return pos(u) < pos(v); };
  for (int u = 1; u <= V; u++) {
    auto& phi = G[u];
    sort(phi.down.begin(),phi.down.end(),toposort);
    phi.p = p(u);
  }
  print(1,false);
  cout << endl;

  // renaming
  nextR = tree.second+1;
  R_rec(1,1);

  // output
  print(1);
  for (int u : R) {
    auto& phi = G[u];
    printf(" & (~p%d | ",phi.literal);
    phi.type &= ~(1<<7);
    print(u);
    phi.type |=  (1<<7);
    printf(")");
  }
  cout << endl;

  return 0;
}
<|endoftext|>


<commit_before>#include <QtGui/QApplication>
#include "mainwindow.h"

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

#include <stdio.h>
#include <iostream>
#include <vector>

#include "geom/chessgen.h"
#include "hardware/camera/camera.h"
#include "hardware/camera/opencvcamera.h"
#include "hardware/standards/calibrationstandard.h"
#include "hardware/standards/chessboardstandard.h"
#include "hardware/projector/projectionscreen.h"
/*!
\mainpage Scan Studio

Scan Studio allows users to quickly and easily scan 3D objects into the
industry-standard STL format.

\tableofcontents

\section License

\legalese
Copyright © 2013, Ryan Muller and Chris Thomas.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
\list
\li Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
\li Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
\endlist

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

\endlegalese
*/

int main(int argc, char** argv)
{
//*
    QApplication a(argc, argv);
    //MainWindow w;
    ProjectionScreen w;
    w.showMaximized();
    w.projectOnDisplay(0);
    return a.exec();
//*/
    // desired number of images; eventually an argument?
    unsigned int n = 12;

    // the two cameras we'll be using
    Camera *cam1;
    Camera *cam2;

    // our calibration standard
    CalibrationStandard *standard =
            new ChessboardStandard(cv::Size(9,12),
                                   25.4);

    // keep track of how many images remain
    unsigned int counter = n;

    // list of snapshots
    std::vector<cv::Mat> images1;
    std::vector<cv::Mat> images2;

    // snapshot holders
    cv::Mat snap1, snap2;

    // initialize the cameras however you like
    // they will probably be arguments in the future
    cam1 = new OpenCVCamera(0);
    cam2 = new OpenCVCamera(1);

    // if we're having trouble, abort abort abort
    if(!cam1->isOpen() || !cam2->isOpen())
        return -1;

    cam1->setResolution(800,600);
    cam2->setResolution(800,600);

    cv::namedWindow("Camera 1",1);
    cv::namedWindow("Camera 2",1);

    for(;;){
        snap1 = cam1->getFrame();
        snap2 = cam2->getFrame();

        cv::imshow("Camera 1",snap1);
        cv::imshow("Camera 2",snap2);

        if(cv::waitKey(2)>1) break;

    }

    return 0;

    /*

    unsigned int i;
    Mat edges1, edges0;
    Size size(4,11);

    int counter = NUM_IMAGES;

    vector<Point2f> corners1,corners0;
    bool found1,found0;

    vector<Point3f> chess = fr::ChessGen::getBoard(size,10.16,true);

    vector<vector<Point3f> > objectPoints;
    vector<vector<Point2f> > imagePoints1,imagePoints0;

    Mat camera0mat = Mat::eye(3,3,CV_64F);
    Mat distortion0mat = Mat::zeros(8, 1, CV_64F);
    Mat camera1mat = Mat::eye(3,3,CV_64F);
    Mat distortion1mat = Mat::zeros(8, 1, CV_64F);
    vector<Mat > rvecs0, rvecs1;
    vector<Mat > tvecs0, tvecs1;

    namedWindow("CAMERA 0",1);
    namedWindow("CAMERA 1",1);

    found0 = false;
    found1 = false;

    Mat frame0, frame1;

    for(;;)
    {
        cap1 >> frame1; // get a new frame from camera
        cvtColor(frame1, edges1, CV_BGR2GRAY);

        cap0 >> frame0;
        cvtColor(frame0,edges0,CV_BGR2GRAY);

        for(i=0;i<imagePoints1.size();i++){
            drawChessboardCorners(frame1,size,imagePoints1[i],true);
            drawChessboardCorners(frame0,size,imagePoints0[i],true);
        }

        imshow("CAMERA 0", frame0);
        imshow("CAMERA 1", frame1);

        if(waitKey(200)>=0){
            //found = findChessboardCorners(edges,size,corners);
            //
            found0 = findCirclesGrid(edges0,size,corners0
                                    ,CALIB_CB_ASYMMETRIC_GRID
                                    );//
            found1 = findCirclesGrid(edges1,size,corners1
                                    ,CALIB_CB_ASYMMETRIC_GRID
                                    );//
            if(found0&&found1){
                objectPoints.push_back(chess);
                imagePoints0.push_back(corners0);
                imagePoints1.push_back(corners1);
                if(--counter<= 0)
                    break;
            }
        }
        //else waitKey(30);
        //if(waitKey(30)>1) break;
    }

    double rpe0 = calibrateCamera(objectPoints,imagePoints0,
                                 Size(edges0.size[0],edges0.size[1]),
                                 camera0mat,distortion0mat,rvecs0,tvecs0,
                                 CV_CALIB_FIX_ASPECT_RATIO|
                                 CV_CALIB_FIX_PRINCIPAL_POINT);
    double rpe1 = calibrateCamera(objectPoints,imagePoints1,
                                 Size(edges1.size[0],edges1.size[1]),
                                 camera1mat,distortion1mat,rvecs1,tvecs1,
                                 CV_CALIB_FIX_ASPECT_RATIO|
                                 CV_CALIB_FIX_PRINCIPAL_POINT);

    cout << " ==== Camera 0 ====\n";
    cout << camera0mat << endl;
    cout << distortion0mat << endl;

    cout << " ==== Camera 1 ====\n";
    cout << camera1mat << endl;
    cout << distortion1mat << endl;

    vector<Point3f> cornersReal;
    vector<Point2f> cornersImage;

    Mat relativeRot,relativeTrans;

    //cout << " ==== Computing positions... ===\n";

    for(unsigned int i=0;i<NUM_IMAGES;i++){
       // cout << tvecs0[i] << "\n";
        cornersReal.push_back(Point3f(tvecs0.at(i).at<double>(0),
                                      tvecs0.at(i).at<double>(1),
                                      tvecs0.at(i).at<double>(2)));
        cornersImage.push_back(imagePoints1[i][0]);
    }

    solvePnP(cornersReal,
             cornersImage,
             camera1mat,
             distortion1mat,
             relativeRot,
             relativeTrans);

    cout << " ==== Relative positions of cameras: ==== \n"
         << relativeTrans << "\n" << relativeRot << "\n";

    return 0;*/
}
<commit_msg>finished attributions<commit_after>#include <QtGui/QApplication>
#include "mainwindow.h"

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

#include <stdio.h>
#include <iostream>
#include <vector>

#include "geom/chessgen.h"
#include "hardware/camera/camera.h"
#include "hardware/camera/opencvcamera.h"
#include "hardware/standards/calibrationstandard.h"
#include "hardware/standards/chessboardstandard.h"
#include "hardware/projector/projectionscreen.h"
/*!
\mainpage Scan Studio

Scan Studio allows users to quickly and easily scan 3D objects into the
industry-standard STL format.

\section Attribution

\subsection Oxygen icon set

Oxygen icon set used under the
terms of the
CC BY-SA 3.0 license.

\subsection Qt

Qt application framework used under the
terms of the
GNU Lesser General Public License.

\subsection OpenCV

OpenCV computer vision library used under the
terms of the BSD 2-Clause
License.

\section License

\legalese
Copyright © 2013, Ryan Muller and Chris Thomas.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
\list
\li Redistributions of source code must retain the above copyright notice,
this list of conditions and the following disclaimer.
\li Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
\endlist

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

\endlegalese
*/

int main(int argc, char** argv)
{
//*
    QApplication a(argc, argv);
    //MainWindow w;
    ProjectionScreen w;
    w.showMaximized();
    w.projectOnDisplay(0);
    return a.exec();
//*/
    // desired number of images; eventually an argument?
    unsigned int n = 12;

    // the two cameras we'll be using
    Camera *cam1;
    Camera *cam2;

    // our calibration standard
    CalibrationStandard *standard =
            new ChessboardStandard(cv::Size(9,12),
                                   25.4);

    // keep track of how many images remain
    unsigned int counter = n;

    // list of snapshots
    std::vector<cv::Mat> images1;
    std::vector<cv::Mat> images2;

    // snapshot holders
    cv::Mat snap1, snap2;

    // initialize the cameras however you like
    // they will probably be arguments in the future
    cam1 = new OpenCVCamera(0);
    cam2 = new OpenCVCamera(1);

    // if we're having trouble, abort abort abort
    if(!cam1->isOpen() || !cam2->isOpen())
        return -1;

    cam1->setResolution(800,600);
    cam2->setResolution(800,600);

    cv::namedWindow("Camera 1",1);
    cv::namedWindow("Camera 2",1);

    for(;;){
        snap1 = cam1->getFrame();
        snap2 = cam2->getFrame();

        cv::imshow("Camera 1",snap1);
        cv::imshow("Camera 2",snap2);

        if(cv::waitKey(2)>1) break;

    }

    return 0;

    /*

    unsigned int i;
    Mat edges1, edges0;
    Size size(4,11);

    int counter = NUM_IMAGES;

    vector<Point2f> corners1,corners0;
    bool found1,found0;

    vector<Point3f> chess = fr::ChessGen::getBoard(size,10.16,true);

    vector<vector<Point3f> > objectPoints;
    vector<vector<Point2f> > imagePoints1,imagePoints0;

    Mat camera0mat = Mat::eye(3,3,CV_64F);
    Mat distortion0mat = Mat::zeros(8, 1, CV_64F);
    Mat camera1mat = Mat::eye(3,3,CV_64F);
    Mat distortion1mat = Mat::zeros(8, 1, CV_64F);
    vector<Mat > rvecs0, rvecs1;
    vector<Mat > tvecs0, tvecs1;

    namedWindow("CAMERA 0",1);
    namedWindow("CAMERA 1",1);

    found0 = false;
    found1 = false;

    Mat frame0, frame1;

    for(;;)
    {
        cap1 >> frame1; // get a new frame from camera
        cvtColor(frame1, edges1, CV_BGR2GRAY);

        cap0 >> frame0;
        cvtColor(frame0,edges0,CV_BGR2GRAY);

        for(i=0;i<imagePoints1.size();i++){
            drawChessboardCorners(frame1,size,imagePoints1[i],true);
            drawChessboardCorners(frame0,size,imagePoints0[i],true);
        }

        imshow("CAMERA 0", frame0);
        imshow("CAMERA 1", frame1);

        if(waitKey(200)>=0){
            //found = findChessboardCorners(edges,size,corners);
            //
            found0 = findCirclesGrid(edges0,size,corners0
                                    ,CALIB_CB_ASYMMETRIC_GRID
                                    );//
            found1 = findCirclesGrid(edges1,size,corners1
                                    ,CALIB_CB_ASYMMETRIC_GRID
                                    );//
            if(found0&&found1){
                objectPoints.push_back(chess);
                imagePoints0.push_back(corners0);
                imagePoints1.push_back(corners1);
                if(--counter<= 0)
                    break;
            }
        }
        //else waitKey(30);
        //if(waitKey(30)>1) break;
    }

    double rpe0 = calibrateCamera(objectPoints,imagePoints0,
                                 Size(edges0.size[0],edges0.size[1]),
                                 camera0mat,distortion0mat,rvecs0,tvecs0,
                                 CV_CALIB_FIX_ASPECT_RATIO|
                                 CV_CALIB_FIX_PRINCIPAL_POINT);
    double rpe1 = calibrateCamera(objectPoints,imagePoints1,
                                 Size(edges1.size[0],edges1.size[1]),
                                 camera1mat,distortion1mat,rvecs1,tvecs1,
                                 CV_CALIB_FIX_ASPECT_RATIO|
                                 CV_CALIB_FIX_PRINCIPAL_POINT);

    cout << " ==== Camera 0 ====\n";
    cout << camera0mat << endl;
    cout << distortion0mat << endl;

    cout << " ==== Camera 1 ====\n";
    cout << camera1mat << endl;
    cout << distortion1mat << endl;

    vector<Point3f> cornersReal;
    vector<Point2f> cornersImage;

    Mat relativeRot,relativeTrans;

    //cout << " ==== Computing positions... ===\n";

    for(unsigned int i=0;i<NUM_IMAGES;i++){
       // cout << tvecs0[i] << "\n";
        cornersReal.push_back(Point3f(tvecs0.at(i).at<double>(0),
                                      tvecs0.at(i).at<double>(1),
                                      tvecs0.at(i).at<double>(2)));
        cornersImage.push_back(imagePoints1[i][0]);
    }

    solvePnP(cornersReal,
             cornersImage,
             camera1mat,
             distortion1mat,
             relativeRot,
             relativeTrans);

    cout << " ==== Relative positions of cameras: ==== \n"
         << relativeTrans << "\n" << relativeRot << "\n";

    return 0;*/
}
<|endoftext|>


<commit_before>b0f93f94-4b02-11e5-a8f4-28cfe9171a43<commit_msg>lets try again<commit_after>b106bd75-4b02-11e5-8c65-28cfe9171a43<|endoftext|>