<commit_before>#include <cctype>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "linearizer.hpp"
#include "parser.hpp"
#include "utils.hpp"

using namespace std;

void output_vector_to_file(vector<double> vec_write, ofstream &myfile) {
    for (auto i = 0; i < int(vec_write.size()) - 1; ++i) {
        myfile << vec_write[i] << ',';
    }
    myfile << vec_write[int(vec_write.size()) - 1] << endl;
    return;
}

int main() {
    string user_input =
        //"f(x)=-1.3*Ln[x]+5+3.5*x^2-2.6*Exp[x]-35,Range=0.0:10.0,Mesh=20";
        //"f(x)=Exp[x],Range=0.0:10.0,Mesh=20";
        "f(x)=x,Range=0.0:10.0,Mesh=20";

    size_t pos = user_input.find(",");
    string f = user_input.substr(0, int(pos));  // first string, function
    cout << "Function: " << f << endl;

    vector<elementaryFunctionLib> terms;
    vector<double> coeff;
    parser(f, terms, coeff);
    for (int i = 0; i < int(terms.size()); ++i) {
        cout << coeff[i] << ' ' << terms[i] << endl;
    }

    string str2 = user_input.substr(int(pos) + 1);
    pos = str2.find(",");
    string range = str2.substr(0, int(pos));  // second useful string, range
    string mesh = str2.substr(int(pos) + 1);  // third useful string, mesh
    vector<double> range_vec = Range_vec(range);
    cout << "range " << range_vec[0] << ':' << range_vec[1] << endl;
    int Mesh_val = get_Mesh(mesh);
    cout << "Mesh: " << Mesh_val << endl;

    // aAll, bAll of size mesh intervals are accumulated 0th and 1st moments.
    int meshPts = Mesh_val;
    vector<double> aAll(meshPts, 0.0);
    vector<double> bAll(meshPts, 0.0);
    vector<double> aCurrent(meshPts, 0.0);
    vector<double> bCurrent(meshPts, 0.0);

    double lb = range_vec[0];
    double ub = range_vec[1];

    for (int iTerm = 0; iTerm < int(terms.size()); iTerm++) {
        linearizeCurrent(terms[iTerm], lb, ub, meshPts, aCurrent, bCurrent);
        for (int iMesh = 0; iMesh < meshPts; iMesh++) {
            aAll[iMesh] += aCurrent[iMesh] * coeff[iTerm];
            bAll[iMesh] += bCurrent[iMesh] * coeff[iTerm];
        }
    }

    // Output aAll & bAll for debugging purposes
    std::cout << "first moments of the linearization" << std::endl;
    for(auto &i:aAll) {
        std::cout << i << std::endl;
    }
    std::cout << std::endl;
    std::cout << "zeroth moments of the linearization" << std::endl;
    for(auto &i:bAll) {
        std::cout << i << std::endl;
    }

    // Output test.txt for use in a python plotter script
    ofstream myfile;
    myfile.open("test.txt");
    myfile << user_input << endl;
    output_vector_to_file(aAll, myfile);
    output_vector_to_file(bAll, myfile);
    myfile.close();

    return 0;
}
<commit_msg>exhcanged aAll bAll<commit_after>#include <cctype>
#include <cmath>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include "linearizer.hpp"
#include "parser.hpp"
#include "utils.hpp"

using namespace std;

void output_vector_to_file(vector<double> vec_write, ofstream &myfile) {
    for (auto i = 0; i < int(vec_write.size()) - 1; ++i) {
        myfile << vec_write[i] << ',';
    }
    myfile << vec_write[int(vec_write.size()) - 1] << endl;
    return;
}

int main() {
    string user_input =
        //"f(x)=-1.3*Ln[x]+5+3.5*x^2-2.6*Exp[x]-35,Range=0.0:10.0,Mesh=20"
        //"f(x)=Exp[x],Range=0.0:10.0,Mesh=20"
        //"f(x)=x,Range=0.0:10.0,Mesh=20"
        //"f(x)=x^2,Range=0.0:10.0,Mesh=20"
        "f(x)=Sin(x),Range=0.0:10.0,Mesh=20"
        ;

    size_t pos = user_input.find(",");
    string f = user_input.substr(0, int(pos));  // first string, function
    cout << "Function: " << f << endl;

    vector<elementaryFunctionLib> terms;
    vector<double> coeff;
    parser(f, terms, coeff);
    for (int i = 0; i < int(terms.size()); ++i) {
        cout << coeff[i] << ' ' << terms[i] << endl;
    }

    string str2 = user_input.substr(int(pos) + 1);
    pos = str2.find(",");
    string range = str2.substr(0, int(pos));  // second useful string, range
    string mesh = str2.substr(int(pos) + 1);  // third useful string, mesh
    vector<double> range_vec = Range_vec(range);
    cout << "range " << range_vec[0] << ':' << range_vec[1] << endl;
    int Mesh_val = get_Mesh(mesh);
    cout << "Mesh: " << Mesh_val << endl;

    // aAll, bAll of size mesh intervals are accumulated 0th and 1st moments.
    int meshPts = Mesh_val;
    vector<double> aAll(meshPts, 0.0);
    vector<double> bAll(meshPts, 0.0);
    vector<double> aCurrent(meshPts, 0.0);
    vector<double> bCurrent(meshPts, 0.0);

    double lb = range_vec[0];
    double ub = range_vec[1];

    for (int iTerm = 0; iTerm < int(terms.size()); iTerm++) {
        linearizeCurrent(terms[iTerm], lb, ub, meshPts, aCurrent, bCurrent);
        for (int iMesh = 0; iMesh < meshPts; iMesh++) {
            aAll[iMesh] += aCurrent[iMesh] * coeff[iTerm];
            bAll[iMesh] += bCurrent[iMesh] * coeff[iTerm];
        }
    }

    // Output aAll & bAll for debugging purposes
    std::cout << "first moments of the linearization" << std::endl;
    for(auto &i:aAll) {
        std::cout << i << std::endl;
    }
    std::cout << std::endl;
    std::cout << "zeroth moments of the linearization" << std::endl;
    for(auto &i:bAll) {
        std::cout << i << std::endl;
    }

    // Output test.txt for use in a python plotter script
    ofstream myfile;
    myfile.open("test.txt");
    myfile << user_input << endl;
    output_vector_to_file(bAll, myfile);
    output_vector_to_file(aAll, myfile);
    myfile.close();

    return 0;
}
<|endoftext|>


<commit_before>#include <string>

#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>

#include "shared.h"
#include "run.h"

#define OPTION_NOT  (1<<16)
#define OPTION_FS_ALLOW 0x101
static const char optionstring[] = "+hd";

#define OPTION_BOOL(longopt, value) \
  { longopt, 0, 0, value }, \
  { "no-" longopt, 0, 0, value|OPTION_NOT }

static const struct option options[] = {
  { "help", 0, 0, 'h' },
  { "debug", 0, 0, 'd' },
  { "none", 0, 0, 'N' },
  { "fs-allow", 1, 0, OPTION_FS_ALLOW },
  OPTION_BOOL("net", 'n'),
  OPTION_BOOL("pid", 'p'),
  OPTION_BOOL("ipc", 'i'),
  OPTION_BOOL("mount", 'm'),
  OPTION_BOOL("fs", 'f'),
  { 0, 0, 0, 0 }
};

void usage(FILE* stream, int exitcode)
{
  fprintf(stream,
"Usage: sandbox [options] [--] command [args]\n\n"
"Run a command in a sandbox.\n\n"
"Options:\n"
"  --help, -h        Show this message\n"
"  --debug, -d       Enable debugging messages\n"
"\n"
"Sandbox features:\n"
"  All of the following sandbox features are enabled by default.\n"
"  `--no-<feature>' disables a feature.\n"
"\n"
"  --none\n"
"        Disable all sandbox features.\n"
"        May be followed by additional options to turn on selected features.\n"
"\n"
"  --net, --no-net\n"
"        Network isolation; prevents connections to any host (including\n"
"        localhost).\n"
"\n"
"  --pid, --no-pid\n"
"        PID isolation; prevents sending signals to any process outside of\n"
"        the sandbox.\n"
"\n"
"  --mount, --no-mount\n"
"        Mount isolation; prevents mounting or unmounting any mounts outside\n"
"        of the sandbox.\n"
"\n"
"  --ipc, --no-ipc\n"
"        IPC isolation; prevents access to any SysV IPC resources outside of\n"
"        the sandbox.\n"
"\n"
"  --fs, --no-fs\n"
"        Filesystem isolation; prevents modification of files outside of the\n"
"        sandbox.\n"
"\n"
"Filesystem options:\n"
"\n"
"  --fs-allow <PATH> [ --fs-allow <PATH2> ... ]\n"
"        Allow writes to the specified path(s).\n"
"        <PATH> may contain a single relative or absolute path, or\n"
"        several paths separated with the : character.\n"
	  );
  exit(exitcode);
}

std::string realpath(std::string const& path)
{
  char* resolved = realpath(path.c_str(), 0);
  if (!resolved) {
    fprintf(stderr, "Could not resolve %s: %s\n", path.c_str(),
	    strerror(errno));
    exit(4);
  }
  std::string out{resolved};
  free(resolved);
  return out;
}

void parse_fs_allow(Context* ctx, const char* arg)
{
  int backslash = 0;
  std::string current_arg;
  while (*arg) {
    if (backslash) {
      current_arg.append(1, *arg);
      backslash = 0;
    } else if (*arg == '\\') {
      backslash = 1;
    } else if (*arg == ':') {
      ctx->fuse_writable_paths.push_back(realpath(current_arg));
      current_arg.clear();
    } else {
      current_arg.append(1, *arg);
    }
    ++arg;
  }
  ctx->fuse_writable_paths.push_back(realpath(current_arg));
}

void parse_arguments(Context* ctx, int argc, char** argv)
{
  int gotopt;
  while ((gotopt = getopt_long(argc, argv,
			       optionstring, options, 0))) {
    if (gotopt == -1) {
      break;
    }

    debug("gotopt 0x%x\n", gotopt);

    int enable = !(gotopt&OPTION_NOT);

    gotopt &= 0xffff;

    switch (gotopt) {

    case 'h':
      usage(stdout, 0);

    case '?':
      usage(stderr, 3);

    case 'd':
      ++Global::debug_mode;
      break;

    case 'N':
      ctx->netns = 0;
      ctx->pidns = 0;
      ctx->mountns = 0;
      ctx->ipcns = 0;
      ctx->fs = 0;
      break;

    case 'n':
      ctx->netns = enable;
      break;

    case 'p':
      ctx->pidns = enable;
      break;

    case 'i':
      ctx->ipcns = enable;
      break;

    case 'm':
      ctx->mountns = enable;
      break;

    case 'f':
      ctx->fs = enable;
      break;

    case OPTION_FS_ALLOW:
      parse_fs_allow(ctx, optarg);
      break;
    }
  }

  debug("optind %d\n", optind);

  ctx->child_argv = &argv[optind];
  if (!ctx->child_argv[0]) {
    fprintf(stderr, "Not enough arguments\n");
    usage(stderr, 3);
  }

  if (ctx->fs && !ctx->mountns) {
    fprintf(stderr, "error: filesystem sandbox requires mount sandbox.\n"
	    "Try adding --mount to the sandbox arguments.\n");
    exit(3);
  }

  ctx->mount_proc = ctx->mountns && ctx->pidns;

  /*
    If using fuse and pidns, create a pid namespace and mount namespace
    for the fuse layer only; this ensures the sandbox fuse process won't
    be visible within the sandbox, and killing the top-level sandbox
    process is guaranteed to kill the fuse process.
  */
  ctx->clone_for_fuse = ctx->fs && ctx->pidns;
}

static char* mountpoint = 0;
void remove_mountpoint()
{
  if (rmdir(mountpoint)) {
    if (errno != ENOENT) {
      fprintf(stderr, "warning: could not remove sandbox fuse mount point %s: "
	      "%s\n", mountpoint, strerror(errno));
    }
  }
}

void setup_fuse_context(Context* ctx)
{
  const char* tempdir = getenv("TMPDIR");
  if (!tempdir) {
    tempdir = "/tmp";
  }

  std::string tmpl(tempdir);
  tmpl += "/sandbox-fuse-XXXXXX";
  char* c_mountpoint = strdup(tmpl.c_str());

  if (!mkdtemp(c_mountpoint)) {
    perror("Can't create mount point for FUSE");
    exit(3);
  }
  ctx->fuse_mountpoint = c_mountpoint;
  mountpoint = c_mountpoint;
  atexit(remove_mountpoint);
}

int main(int argc, char** argv)
{
  Context ctx = {
    .netns = 1,
    .pidns = 1,
    .mountns = 1,
    .ipcns = 1,
    .fs = 1
  };
  parse_arguments(&ctx, argc, argv);
  if (ctx.fs) {
    setup_fuse_context(&ctx);
  }
  return run(&ctx);
}
<commit_msg>Add note about --net and unix domain sockets<commit_after>#include <string>

#include <errno.h>
#include <getopt.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <limits.h>
#include <stdlib.h>

#include "shared.h"
#include "run.h"

#define OPTION_NOT  (1<<16)
#define OPTION_FS_ALLOW 0x101
static const char optionstring[] = "+hd";

#define OPTION_BOOL(longopt, value) \
  { longopt, 0, 0, value }, \
  { "no-" longopt, 0, 0, value|OPTION_NOT }

static const struct option options[] = {
  { "help", 0, 0, 'h' },
  { "debug", 0, 0, 'd' },
  { "none", 0, 0, 'N' },
  { "fs-allow", 1, 0, OPTION_FS_ALLOW },
  OPTION_BOOL("net", 'n'),
  OPTION_BOOL("pid", 'p'),
  OPTION_BOOL("ipc", 'i'),
  OPTION_BOOL("mount", 'm'),
  OPTION_BOOL("fs", 'f'),
  { 0, 0, 0, 0 }
};

void usage(FILE* stream, int exitcode)
{
  fprintf(stream,
"Usage: sandbox [options] [--] command [args]\n\n"
"Run a command in a sandbox.\n\n"
"Options:\n"
"  --help, -h        Show this message\n"
"  --debug, -d       Enable debugging messages\n"
"\n"
"Sandbox features:\n"
"  All of the following sandbox features are enabled by default.\n"
"  `--no-<feature>' disables a feature.\n"
"\n"
"  --none\n"
"        Disable all sandbox features.\n"
"        May be followed by additional options to turn on selected features.\n"
"\n"
"  --net, --no-net\n"
"        Network isolation; prevents connections to any host (including\n"
"        localhost). This includes Unix domain socket connections.\n"
"\n"
"  --pid, --no-pid\n"
"        PID isolation; prevents sending signals to any process outside of\n"
"        the sandbox.\n"
"\n"
"  --mount, --no-mount\n"
"        Mount isolation; prevents mounting or unmounting any mounts outside\n"
"        of the sandbox.\n"
"\n"
"  --ipc, --no-ipc\n"
"        IPC isolation; prevents access to any SysV IPC resources outside of\n"
"        the sandbox.\n"
"\n"
"  --fs, --no-fs\n"
"        Filesystem isolation; prevents modification of files outside of the\n"
"        sandbox.\n"
"\n"
"Filesystem options:\n"
"\n"
"  --fs-allow <PATH> [ --fs-allow <PATH2> ... ]\n"
"        Allow writes to the specified path(s).\n"
"        <PATH> may contain a single relative or absolute path, or\n"
"        several paths separated with the : character.\n"
	  );
  exit(exitcode);
}

std::string realpath(std::string const& path)
{
  char* resolved = realpath(path.c_str(), 0);
  if (!resolved) {
    fprintf(stderr, "Could not resolve %s: %s\n", path.c_str(),
	    strerror(errno));
    exit(4);
  }
  std::string out{resolved};
  free(resolved);
  return out;
}

void parse_fs_allow(Context* ctx, const char* arg)
{
  int backslash = 0;
  std::string current_arg;
  while (*arg) {
    if (backslash) {
      current_arg.append(1, *arg);
      backslash = 0;
    } else if (*arg == '\\') {
      backslash = 1;
    } else if (*arg == ':') {
      ctx->fuse_writable_paths.push_back(realpath(current_arg));
      current_arg.clear();
    } else {
      current_arg.append(1, *arg);
    }
    ++arg;
  }
  ctx->fuse_writable_paths.push_back(realpath(current_arg));
}

void parse_arguments(Context* ctx, int argc, char** argv)
{
  int gotopt;
  while ((gotopt = getopt_long(argc, argv,
			       optionstring, options, 0))) {
    if (gotopt == -1) {
      break;
    }

    debug("gotopt 0x%x\n", gotopt);

    int enable = !(gotopt&OPTION_NOT);

    gotopt &= 0xffff;

    switch (gotopt) {

    case 'h':
      usage(stdout, 0);

    case '?':
      usage(stderr, 3);

    case 'd':
      ++Global::debug_mode;
      break;

    case 'N':
      ctx->netns = 0;
      ctx->pidns = 0;
      ctx->mountns = 0;
      ctx->ipcns = 0;
      ctx->fs = 0;
      break;

    case 'n':
      ctx->netns = enable;
      break;

    case 'p':
      ctx->pidns = enable;
      break;

    case 'i':
      ctx->ipcns = enable;
      break;

    case 'm':
      ctx->mountns = enable;
      break;

    case 'f':
      ctx->fs = enable;
      break;

    case OPTION_FS_ALLOW:
      parse_fs_allow(ctx, optarg);
      break;
    }
  }

  debug("optind %d\n", optind);

  ctx->child_argv = &argv[optind];
  if (!ctx->child_argv[0]) {
    fprintf(stderr, "Not enough arguments\n");
    usage(stderr, 3);
  }

  if (ctx->fs && !ctx->mountns) {
    fprintf(stderr, "error: filesystem sandbox requires mount sandbox.\n"
	    "Try adding --mount to the sandbox arguments.\n");
    exit(3);
  }

  ctx->mount_proc = ctx->mountns && ctx->pidns;

  /*
    If using fuse and pidns, create a pid namespace and mount namespace
    for the fuse layer only; this ensures the sandbox fuse process won't
    be visible within the sandbox, and killing the top-level sandbox
    process is guaranteed to kill the fuse process.
  */
  ctx->clone_for_fuse = ctx->fs && ctx->pidns;
}

static char* mountpoint = 0;
void remove_mountpoint()
{
  if (rmdir(mountpoint)) {
    if (errno != ENOENT) {
      fprintf(stderr, "warning: could not remove sandbox fuse mount point %s: "
	      "%s\n", mountpoint, strerror(errno));
    }
  }
}

void setup_fuse_context(Context* ctx)
{
  const char* tempdir = getenv("TMPDIR");
  if (!tempdir) {
    tempdir = "/tmp";
  }

  std::string tmpl(tempdir);
  tmpl += "/sandbox-fuse-XXXXXX";
  char* c_mountpoint = strdup(tmpl.c_str());

  if (!mkdtemp(c_mountpoint)) {
    perror("Can't create mount point for FUSE");
    exit(3);
  }
  ctx->fuse_mountpoint = c_mountpoint;
  mountpoint = c_mountpoint;
  atexit(remove_mountpoint);
}

int main(int argc, char** argv)
{
  Context ctx = {
    .netns = 1,
    .pidns = 1,
    .mountns = 1,
    .ipcns = 1,
    .fs = 1
  };
  parse_arguments(&ctx, argc, argv);
  if (ctx.fs) {
    setup_fuse_context(&ctx);
  }
  return run(&ctx);
}
<|endoftext|>


<commit_before>#include "gameloop.hpp"
#include "glhead.hpp"
#include "input.hpp"
#include "glresource.hpp"
#include "spinner/vector.hpp"
#include "gpu.hpp"
#include "glx.hpp"
#include "camera.hpp"
#include "font.hpp"
#include "updator.hpp"
#include "scene.hpp"
#include "sound.hpp"

using namespace rs;
using namespace spn;
// MainThread と DrawThread 間のデータ置き場
// リソースハンドルはメインスレッド
struct Mth_DthData {
	rs::HLInput hlIk,
				hlIm;
	rs::HLAct actQuit,
			actButton,
			actLeft,
			actRight,
			actUp,
			actDown,
			actMoveX,
			actMoveY,
			actPress;
	rs::HLCam hlCam;
	rs::SPWindow spWin;
};
#define shared (Mth_Dth::_ref())
class Mth_Dth : public spn::Singleton<Mth_Dth>, public rs::SpinLock<Mth_DthData> {};

class MyDraw : public rs::IDrawProc {
	rs::HLFx	_hlFx;
	rs::HLVb 	_hlVb;
	rs::HLIb 	_hlIb;
	rs::HLTex 	_hlTex;
	rs::HLText	_hlText;

	spn::Size	_size;
	bool		_bPress;
	GLint		_passView, _passText;
	public:
		MyDraw() {
			_bPress = false;
			struct TmpV {
				spn::Vec3 pos;
				spn::Vec4 tex;
			};
			TmpV tmpV[] = {
				{
					spn::Vec3{-1,-1,0},
					spn::Vec4{0,1,0,0}
				},
				{
					spn::Vec3{-1,1,0},
					spn::Vec4{0,0,0,0}
				},
				{
					spn::Vec3{1,1,0},
					spn::Vec4{1,0,0,0}
				},
				{
					spn::Vec3{1,-1,0},
					spn::Vec4{1,1,0,0}
				}
			};
			// インデックス定義
			GLubyte tmpI[] = {
				0,1,2,
				2,3,0
			};
			mgr_rw.addUriHandler(rs::SPUriHandler(new rs::UriH_File(u8"/")));
			_hlVb = mgr_gl.makeVBuffer(GL_STATIC_DRAW);
			_hlVb.ref()->use()->initData(tmpV, countof(tmpV), sizeof(TmpV));
			_hlIb = mgr_gl.makeIBuffer(GL_STATIC_DRAW);
			_hlIb.ref()->use()->initData(tmpI, countof(tmpI));
			_hlTex = mgr_gl.loadTexture(spn::URI("file:///home/slice/test.png"));
			_hlTex.ref()->use()->setFilter(rs::IGLTexture::MipmapLinear, true,true);

			rs::CCoreID cid = mgr_text.makeCoreID("MS Gothic", rs::CCoreID(0, 15, CCoreID::CharFlag_AA, false, 1, CCoreID::SizeType_Point));
			_hlText = mgr_text.createText(cid, U"おお_ゆうしゃよ\nなんということじゃ\nつるぎの　もちかたが　ちがうぞ");

			rs::GPUInfo info;
			info.onDeviceReset();
			std::cout << info;

			_hlFx = mgr_gl.loadEffect(spn::URI("file:///home/slice/test.glx"));
			auto& pFx = *_hlFx.ref();
			GLint techID = pFx.getTechID("TheTech");
			pFx.setTechnique(techID, true);

			_passView = pFx.getPassID("P0");
			_passText = pFx.getPassID("P1");
// 			pFx.setUniform(spn::Vec4{1,2,3,4}, pFx.getUniformID("lowVal"));
			rs::SetSwapInterval(1);

			_size *= 0;
			auto lk = shared.lock();
			auto& cd = lk->hlCam.ref();
			cd.setFOV(spn::DEGtoRAD(60));
			cd.setZPlane(0.01f, 500.f);
		}
		bool runU(uint64_t accum) override {
			glClearColor(0,0,1,1);
			glClearDepth(1.0f);
			glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

			auto lk = shared.lock();
			auto& cd = lk->hlCam.ref();
			auto sz = lk->spWin->getSize();
			if(sz != _size) {
				_size = sz;
				cd.setAspect(float(_size.width)/_size.height);
				glViewport(0,0,_size.width, _size.height);
			}
			auto& fx = *_hlFx.ref();
			fx.setPass(_passView);
			GLint id = fx.getUniformID("mTrans");

			auto btn = mgr_input.isKeyPressing(lk->actPress);
			if(btn ^ _bPress) {
				lk->hlIm.ref()->setMouseMode((!_bPress) ? rs::MouseMode::Relative : rs::MouseMode::Absolute);
				_bPress = btn;
			}

			constexpr float speed = 0.25f;
			float mvF=0, mvS=0;
			if(mgr_input.isKeyPressing(lk->actUp))
				mvF += speed;
			if(mgr_input.isKeyPressing(lk->actDown))
				mvF -= speed;
			if(mgr_input.isKeyPressing(lk->actLeft))
				mvS -= speed;
			if(mgr_input.isKeyPressing(lk->actRight))
				mvS += speed;
			cd.moveFwd3D(mvF);
			cd.moveSide3D(mvS);
			if(_bPress) {
				float xv = mgr_input.getKeyValue(lk->actMoveX)/4.f,
					yv = mgr_input.getKeyValue(lk->actMoveY)/4.f;
				cd.addRot(spn::Quat::RotationY(spn::DEGtoRAD(-xv)));
				cd.addRot(spn::Quat::RotationX(spn::DEGtoRAD(-yv)));
			}

			fx.setUniform(cd.getViewProjMatrix().convert44(), id);
			id = fx.getUniformID("tDiffuse");
			fx.setUniform(_hlTex, id);

			// 頂点フォーマット定義
			rs::SPVDecl decl(new rs::VDecl{
				{0,0, GL_FLOAT, GL_FALSE, 3, (GLuint)rs::VSem::POSITION},
				{0,12, GL_FLOAT, GL_FALSE, 4, (GLuint)rs::VSem::TEXCOORD0}
			});
			fx.setVDecl(std::move(decl));
			fx.setVStream(_hlVb.get(), 0);
			fx.setIStream(_hlIb.get());
			fx.drawIndexed(GL_TRIANGLES, 6, 0);

			fx.setPass(_passText);
			id = fx.getUniformID("mText");

			auto fn = [](int x, int y, float r) {
				float rx = Rcp22Bit(512),
					ry = Rcp22Bit(384);
				return Mat33(rx*r,		0,			0,
							0,			ry*r, 		0,
							-1.f+x*rx,	1.f-y*ry,	1);
			};
			fx.setUniform(fn(0,0,1), id);
 			_hlText.ref().draw(&fx);
			return true;
		}
};
class TestObj : public ObjectT<TestObj> {
	class MySt : public State {
		public:
			MySt(StateID id): State(id) {}
			void onUpdate(TestObj& self) {
// 				self.destroy();
			}
	};
	public:
		TestObj() {
			LogOutput("TestObj::ctor");
			setStateNew<MySt>(128);
		}
		~TestObj() {
			LogOutput("TestObj::dtor");
		}
		void onDestroy() override {
			LogOutput("TestObj::onDestroy");
		}
};
class TScene2 : public Scene<TScene2> {
	class MySt : public State {
		public:
			MySt(): State(0) {}
			void onUpdate(TScene2& self) override {
				auto lk = shared.lock();
				if(mgr_input.isKeyPressed(lk->actRight))
					mgr_scene.setPopScene(1);
			}
	};
	public:
		TScene2() {
			setStateNew<MySt>();
			LogOutput("TScene2::ctor");
		}
		~TScene2() {
			LogOutput("TScene2::dtor");
		}
};
class TScene : public Scene<TScene> {
	HLAb _hlAb;
	HLSs _hlSs;
	class MySt : public State {
		public:
			MySt(StateID id): State(id) {}
			void onEnter(TScene& self, StateID prevID) override {
				self._hlAb = mgr_sound.loadOggStream(mgr_rw.fromFile("/home/slice/test.ogg", RWops::Read, false));
				self._hlSs = mgr_sound.createSource();
				self._hlSs.ref().setBuffer(self._hlAb, 0);
			}
			void onUpdate(TScene& self) override {
				HGbj hGbj(rep_gobj.getObj(c_id));
				if(!hGbj.valid())
					self.destroy();
				auto lk = shared.lock();
				if(mgr_input.isKeyPressed(lk->actLeft))
					mgr_scene.setPushScene(mgr_gobj.emplace(new TScene2()));
				if(mgr_input.isKeyPressed(lk->actQuit))
					mgr_scene.setPopScene(1);
			}
			void onDown(TScene& self, ObjTypeID prevID, const Variant& arg) override {
				LogOutput("TScene::onDown");
				auto& s = self._hlSs.ref();
				s.stop();
				s.setFadeOut(std::chrono::seconds(5));
				s.play();
			}
			void onPause(TScene& self) override {
				LogOutput("TScene::onPause");
			}
			void onResume(TScene& self) override {
				LogOutput("TScene::onResume");
			}
			void onStop(TScene& self) override {
				LogOutput("TScene::onStop");
			}
			void onReStart(TScene& self) override {
				LogOutput("TScene::onReStart");
			}
	};
	public:
		const static ObjID c_id;
		TScene(): Scene(0) {
			setStateNew<MySt>(256);
			LogOutput("TScene::ctor");
			HLGbj hg = mgr_gobj.emplace(new TestObj());
			rep_gobj.setObj(c_id, hg.weak());
			_update.addObj(0, hg);
			hg.release();
		}
		void onDestroy() override {
			LogOutput("TScene::onDestroy");
		}
		~TScene() {
			LogOutput("TScene::dtor");
		}
};
const ObjID TScene::c_id = rep_gobj.RegID("Player");

class MyMain : public rs::IMainProc {
	Mth_Dth _mth;
	public:
		MyMain(const rs::SPWindow& sp) {
			auto lk = shared.lock();
			lk->hlIk = rs::Keyboard::OpenKeyboard();
			lk->spWin = sp;

			lk->actQuit = mgr_input.addAction("quit");
			mgr_input.link(lk->actQuit, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_ESCAPE));
			lk->actButton = mgr_input.addAction("button");
			mgr_input.link(lk->actButton, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_LSHIFT));

			lk->actLeft = mgr_input.addAction("left");
			lk->actRight = mgr_input.addAction("right");
			lk->actUp = mgr_input.addAction("up");
			lk->actDown = mgr_input.addAction("down");
			lk->actMoveX = mgr_input.addAction("moveX");
			lk->actMoveY = mgr_input.addAction("moveY");
			lk->actPress = mgr_input.addAction("press");
			mgr_input.link(lk->actLeft, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_A));
			mgr_input.link(lk->actRight, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_D));
			mgr_input.link(lk->actUp, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_W));
			mgr_input.link(lk->actDown, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_S));

			lk->hlIm = rs::Mouse::OpenMouse(0);
			lk->hlIm.ref()->setMouseMode(rs::MouseMode::Absolute);
			lk->hlIm.ref()->setDeadZone(0, 1.f, 0.f);
			lk->hlIm.ref()->setDeadZone(1, 1.f, 0.f);
			mgr_input.link(lk->actMoveX, rs::InF::AsAxis(lk->hlIm, 0));
			mgr_input.link(lk->actMoveY, rs::InF::AsAxis(lk->hlIm, 1));
			mgr_input.link(lk->actPress, rs::InF::AsButton(lk->hlIm, 0));

			lk->hlCam = mgr_cam.emplace();
			rs::CamData& cd = lk->hlCam.ref();
			cd.setOfs(0,0,-3);

			mgr_scene.setPushScene(mgr_gobj.emplace(new TScene()));
		}
		bool runU() override {
			mgr_sound.update();
			return !mgr_scene.onUpdate();
		}
		void onPause() override {
			mgr_scene.onPause(); }
		void onResume() override {
			mgr_scene.onResume(); }
		void onStop() override {
			mgr_scene.onStop(); }
		void onReStart() override {
			mgr_scene.onReStart(); }
		rs::IDrawProc* initDraw() override {
			return new MyDraw;
		}
};
int main(int argc, char **argv) {
	GameLoop gloop([](const rs::SPWindow& sp){ return new MyMain(sp); });
	return gloop.run("HelloSDL2", 1024, 768, SDL_WINDOW_SHOWN, 2,0,24);
}
<commit_msg>テストコード: AGroup<commit_after>#include "gameloop.hpp"
#include "glhead.hpp"
#include "input.hpp"
#include "glresource.hpp"
#include "spinner/vector.hpp"
#include "gpu.hpp"
#include "glx.hpp"
#include "camera.hpp"
#include "font.hpp"
#include "updator.hpp"
#include "scene.hpp"
#include "sound.hpp"

using namespace rs;
using namespace spn;
// MainThread と DrawThread 間のデータ置き場
// リソースハンドルはメインスレッド
struct Mth_DthData {
	rs::HLInput hlIk,
				hlIm;
	rs::HLAct actQuit,
			actButton,
			actLeft,
			actRight,
			actUp,
			actDown,
			actMoveX,
			actMoveY,
			actPress;
	rs::HLCam hlCam;
	rs::SPWindow spWin;
};
#define shared (Mth_Dth::_ref())
class Mth_Dth : public spn::Singleton<Mth_Dth>, public rs::SpinLock<Mth_DthData> {};

class MyDraw : public rs::IDrawProc {
	rs::HLFx	_hlFx;
	rs::HLVb 	_hlVb;
	rs::HLIb 	_hlIb;
	rs::HLTex 	_hlTex;
	rs::HLText	_hlText;

	spn::Size	_size;
	bool		_bPress;
	GLint		_passView, _passText;
	public:
		MyDraw() {
			_bPress = false;
			struct TmpV {
				spn::Vec3 pos;
				spn::Vec4 tex;
			};
			TmpV tmpV[] = {
				{
					spn::Vec3{-1,-1,0},
					spn::Vec4{0,1,0,0}
				},
				{
					spn::Vec3{-1,1,0},
					spn::Vec4{0,0,0,0}
				},
				{
					spn::Vec3{1,1,0},
					spn::Vec4{1,0,0,0}
				},
				{
					spn::Vec3{1,-1,0},
					spn::Vec4{1,1,0,0}
				}
			};
			// インデックス定義
			GLubyte tmpI[] = {
				0,1,2,
				2,3,0
			};
			mgr_rw.addUriHandler(rs::SPUriHandler(new rs::UriH_File(u8"/")));
			_hlVb = mgr_gl.makeVBuffer(GL_STATIC_DRAW);
			_hlVb.ref()->use()->initData(tmpV, countof(tmpV), sizeof(TmpV));
			_hlIb = mgr_gl.makeIBuffer(GL_STATIC_DRAW);
			_hlIb.ref()->use()->initData(tmpI, countof(tmpI));
			_hlTex = mgr_gl.loadTexture(spn::URI("file:///home/slice/test.png"));
			_hlTex.ref()->use()->setFilter(rs::IGLTexture::MipmapLinear, true,true);

			rs::CCoreID cid = mgr_text.makeCoreID("MS Gothic", rs::CCoreID(0, 15, CCoreID::CharFlag_AA, false, 1, CCoreID::SizeType_Point));
			_hlText = mgr_text.createText(cid, U"おお_ゆうしゃよ\nなんということじゃ\nつるぎの　もちかたが　ちがうぞ");

			rs::GPUInfo info;
			info.onDeviceReset();
			std::cout << info;

			_hlFx = mgr_gl.loadEffect(spn::URI("file:///home/slice/test.glx"));
			auto& pFx = *_hlFx.ref();
			GLint techID = pFx.getTechID("TheTech");
			pFx.setTechnique(techID, true);

			_passView = pFx.getPassID("P0");
			_passText = pFx.getPassID("P1");
// 			pFx.setUniform(spn::Vec4{1,2,3,4}, pFx.getUniformID("lowVal"));
			rs::SetSwapInterval(1);

			_size *= 0;
			auto lk = shared.lock();
			auto& cd = lk->hlCam.ref();
			cd.setFOV(spn::DEGtoRAD(60));
			cd.setZPlane(0.01f, 500.f);
		}
		bool runU(uint64_t accum) override {
			glClearColor(0,0,1,1);
			glClearDepth(1.0f);
			glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);

			auto lk = shared.lock();
			auto& cd = lk->hlCam.ref();
			auto sz = lk->spWin->getSize();
			if(sz != _size) {
				_size = sz;
				cd.setAspect(float(_size.width)/_size.height);
				glViewport(0,0,_size.width, _size.height);
			}
			auto& fx = *_hlFx.ref();
			fx.setPass(_passView);
			GLint id = fx.getUniformID("mTrans");

			auto btn = mgr_input.isKeyPressing(lk->actPress);
			if(btn ^ _bPress) {
				lk->hlIm.ref()->setMouseMode((!_bPress) ? rs::MouseMode::Relative : rs::MouseMode::Absolute);
				_bPress = btn;
			}

			constexpr float speed = 0.25f;
			float mvF=0, mvS=0;
			if(mgr_input.isKeyPressing(lk->actUp))
				mvF += speed;
			if(mgr_input.isKeyPressing(lk->actDown))
				mvF -= speed;
			if(mgr_input.isKeyPressing(lk->actLeft))
				mvS -= speed;
			if(mgr_input.isKeyPressing(lk->actRight))
				mvS += speed;
			cd.moveFwd3D(mvF);
			cd.moveSide3D(mvS);
			if(_bPress) {
				float xv = mgr_input.getKeyValue(lk->actMoveX)/4.f,
					yv = mgr_input.getKeyValue(lk->actMoveY)/4.f;
				cd.addRot(spn::Quat::RotationY(spn::DEGtoRAD(-xv)));
				cd.addRot(spn::Quat::RotationX(spn::DEGtoRAD(-yv)));
			}

			fx.setUniform(cd.getViewProjMatrix().convert44(), id);
			id = fx.getUniformID("tDiffuse");
			fx.setUniform(_hlTex, id);

			// 頂点フォーマット定義
			rs::SPVDecl decl(new rs::VDecl{
				{0,0, GL_FLOAT, GL_FALSE, 3, (GLuint)rs::VSem::POSITION},
				{0,12, GL_FLOAT, GL_FALSE, 4, (GLuint)rs::VSem::TEXCOORD0}
			});
			fx.setVDecl(std::move(decl));
			fx.setVStream(_hlVb.get(), 0);
			fx.setIStream(_hlIb.get());
			fx.drawIndexed(GL_TRIANGLES, 6, 0);

			fx.setPass(_passText);
			id = fx.getUniformID("mText");

			auto fn = [](int x, int y, float r) {
				float rx = Rcp22Bit(512),
					ry = Rcp22Bit(384);
				return Mat33(rx*r,		0,			0,
							0,			ry*r, 		0,
							-1.f+x*rx,	1.f-y*ry,	1);
			};
			fx.setUniform(fn(0,0,1), id);
 			_hlText.ref().draw(&fx);
			return true;
		}
};
class TestObj : public ObjectT<TestObj> {
	class MySt : public State {
		public:
			MySt(StateID id): State(id) {}
			void onUpdate(TestObj& self) {
// 				self.destroy();
			}
	};
	public:
		TestObj() {
			LogOutput("TestObj::ctor");
			setStateNew<MySt>(128);
		}
		~TestObj() {
			LogOutput("TestObj::dtor");
		}
		void onDestroy() override {
			LogOutput("TestObj::onDestroy");
		}
};
class TScene2 : public Scene<TScene2> {
	class MySt : public State {
		public:
			MySt(): State(0) {}
			void onUpdate(TScene2& self) override {
				auto lk = shared.lock();
				if(mgr_input.isKeyPressed(lk->actRight))
					mgr_scene.setPopScene(1);
			}
	};
	public:
		TScene2() {
			setStateNew<MySt>();
			LogOutput("TScene2::ctor");
		}
		~TScene2() {
			LogOutput("TScene2::dtor");
		}
};
class TScene : public Scene<TScene> {
	HLAb _hlAb;
	HLSg _hlSg;
	class MySt : public State {
		public:
			MySt(StateID id): State(id) {}
			void onEnter(TScene& self, StateID prevID) override {
				self._hlAb = mgr_sound.loadOggStream(mgr_rw.fromFile("/home/slice/test.ogg", RWops::Read, false));
				self._hlSg = mgr_sound.createSourceGroup(1);
			}
			void onUpdate(TScene& self) override {
				HGbj hGbj(rep_gobj.getObj(c_id));
				if(!hGbj.valid())
					self.destroy();
				auto lk = shared.lock();
				if(mgr_input.isKeyPressed(lk->actLeft))
					mgr_scene.setPushScene(mgr_gobj.emplace(new TScene2()));
				if(mgr_input.isKeyPressed(lk->actQuit))
					mgr_scene.setPopScene(1);
			}
			void onDown(TScene& self, ObjTypeID prevID, const Variant& arg) override {
				LogOutput("TScene::onDown");
				auto& s = self._hlSg.ref();
				s.clear();
				s.play(self._hlAb, 0);
			}
			void onPause(TScene& self) override {
				LogOutput("TScene::onPause");
			}
			void onResume(TScene& self) override {
				LogOutput("TScene::onResume");
			}
			void onStop(TScene& self) override {
				LogOutput("TScene::onStop");
			}
			void onReStart(TScene& self) override {
				LogOutput("TScene::onReStart");
			}
	};
	public:
		const static ObjID c_id;
		TScene(): Scene(0) {
			setStateNew<MySt>(256);
			LogOutput("TScene::ctor");
			HLGbj hg = mgr_gobj.emplace(new TestObj());
			rep_gobj.setObj(c_id, hg.weak());
			_update.addObj(0, hg);
			hg.release();
		}
		void onDestroy() override {
			LogOutput("TScene::onDestroy");
		}
		~TScene() {
			LogOutput("TScene::dtor");
		}
};
const ObjID TScene::c_id = rep_gobj.RegID("Player");

class MyMain : public rs::IMainProc {
	Mth_Dth _mth;
	public:
		MyMain(const rs::SPWindow& sp) {
			auto lk = shared.lock();
			lk->hlIk = rs::Keyboard::OpenKeyboard();
			lk->spWin = sp;

			lk->actQuit = mgr_input.addAction("quit");
			mgr_input.link(lk->actQuit, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_ESCAPE));
			lk->actButton = mgr_input.addAction("button");
			mgr_input.link(lk->actButton, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_LSHIFT));

			lk->actLeft = mgr_input.addAction("left");
			lk->actRight = mgr_input.addAction("right");
			lk->actUp = mgr_input.addAction("up");
			lk->actDown = mgr_input.addAction("down");
			lk->actMoveX = mgr_input.addAction("moveX");
			lk->actMoveY = mgr_input.addAction("moveY");
			lk->actPress = mgr_input.addAction("press");
			mgr_input.link(lk->actLeft, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_A));
			mgr_input.link(lk->actRight, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_D));
			mgr_input.link(lk->actUp, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_W));
			mgr_input.link(lk->actDown, rs::InF::AsButton(lk->hlIk, SDL_SCANCODE_S));

			lk->hlIm = rs::Mouse::OpenMouse(0);
			lk->hlIm.ref()->setMouseMode(rs::MouseMode::Absolute);
			lk->hlIm.ref()->setDeadZone(0, 1.f, 0.f);
			lk->hlIm.ref()->setDeadZone(1, 1.f, 0.f);
			mgr_input.link(lk->actMoveX, rs::InF::AsAxis(lk->hlIm, 0));
			mgr_input.link(lk->actMoveY, rs::InF::AsAxis(lk->hlIm, 1));
			mgr_input.link(lk->actPress, rs::InF::AsButton(lk->hlIm, 0));

			lk->hlCam = mgr_cam.emplace();
			rs::CamData& cd = lk->hlCam.ref();
			cd.setOfs(0,0,-3);

			mgr_scene.setPushScene(mgr_gobj.emplace(new TScene()));
		}
		bool runU() override {
			mgr_sound.update();
			return !mgr_scene.onUpdate();
		}
		void onPause() override {
			mgr_scene.onPause(); }
		void onResume() override {
			mgr_scene.onResume(); }
		void onStop() override {
			mgr_scene.onStop(); }
		void onReStart() override {
			mgr_scene.onReStart(); }
		rs::IDrawProc* initDraw() override {
			return new MyDraw;
		}
};
int main(int argc, char **argv) {
	GameLoop gloop([](const rs::SPWindow& sp){ return new MyMain(sp); });
	return gloop.run("HelloSDL2", 1024, 768, SDL_WINDOW_SHOWN, 2,0,24);
}
<|endoftext|>


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

#include <QApplication>
#include <QTranslator>
#include <QLocale>
#include "mainwindow.h"
#include <unistd.h>

int main( int argc, char ** argv ) {
    QApplication app(argc, argv);
    app.setWindowIcon(QIcon::fromTheme("mx-user"));

    QTranslator qtTran;
    qtTran.load(QString("qt_") + QLocale::system().name());
    app.installTranslator(&qtTran);
    QTranslator appTran;
    appTran.load(QString("mx-user_") + QLocale::system().name(), "/usr/share/mx-user/locale");
    app.installTranslator(&appTran);

    if (getuid() == 0) {
        MainWindow mw;
        mw.show();
        return app.exec();
    } else {
        QApplication::beep();
        QMessageBox::critical(nullptr, QString::null,
                              QApplication::tr("You must run this program as root."));
        return EXIT_FAILURE;
    }
}

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

#include <QApplication>
#include <QTranslator>
#include <QLocale>
#include "mainwindow.h"
#include <unistd.h>

int main( int argc, char ** argv ) {
    QApplication app(argc, argv);
    app.setWindowIcon(QIcon::fromTheme("mx-user"));

    QTranslator qtTran;
    qtTran.load(QString("qt_") + QLocale::system().name());
    app.installTranslator(&qtTran);
    QTranslator appTran;
    appTran.load(QString("mx-user_") + QLocale::system().name(), "/usr/share/mx-user/locale");
    app.installTranslator(&appTran);

    if (getuid() == 0) {
        MainWindow mw;
        mw.show();
        return app.exec();
    } else {
        system("su-to-root -X -c " + QCoreApplication::applicationFilePath().toUtf8() + "&");
//        QApplication::beep();
//        QMessageBox::critical(nullptr, QString::null,
//                              QApplication::tr("You must run this program as root."));
//        return EXIT_FAILURE;
    }
}

<|endoftext|>


<commit_before>#include "base.h"
#include "camera_list.h"
#include "camera.h"

using namespace dslr;

#if 0
EdsError GetCurrentDevice(EdsCameraRef camera, EdsUInt32* device)
{
  // Get current device setting
  return EdsGetPropertyData(camera,
                           kEdsPropID_Evf_OutputDevice,
                           0,
                           sizeof(*device),
                           device);
}

EdsError SetDevice(EdsCameraRef camera, EdsUInt32 device)
{
  return SetProperty<kEdsPropID_Evf_OutputDevice>(camera, device);
}

EdsError StartLiveView(EdsCameraRef camera)
{
#if 0
  EdsError err;
  EdsUInt32 device;
  err = GetCurrentDevice(camera, &device);
  if (EDS_ERR_OK != err) {
    return err;
  }
  std::cout << "Device = " << device << std::endl;
  device |= kEdsEvfOutputDevice_PC;
#endif
  return SetDevice(camera, kEdsEvfOutputDevice_PC);
}

EdsError EndLiveView(EdsCameraRef camera)
{
#if 0
  EdsError err;
  EdsUInt32 device;
  err = GetCurrentDevice(camera, &device);
  if (EDS_ERR_OK != err) {
    return err;
  }

  device &= ~kEdsEvfOutputDevice_TFT;
#endif
  return SetDevice(camera, 0);
}
#endif

int main()
{
  EdsError err;

  err = EdsInitializeSDK();
  if (EDS_ERR_OK != err) {
    throw err;
  }

  CameraList cameraList;

  std::cout << "There are " << cameraList.Count() << " cameras connected.\n";

  if (cameraList.Count() > 0) {
    Camera camera = cameraList.get(0);
    camera.SetProperty(kEdsPropID_SaveTo, kEdsSaveTo_Host);
  }

  EdsTerminateSDK();
  return 0;
}

<commit_msg>Removing old live view stuff.<commit_after>#include "base.h"
#include "camera_list.h"
#include "camera.h"

using namespace dslr;

int main()
{
  EdsError err;

  err = EdsInitializeSDK();
  if (EDS_ERR_OK != err) {
    throw err;
  }

  CameraList cameraList;

  std::cout << "There are " << cameraList.Count() << " cameras connected.\n";

  if (cameraList.Count() > 0) {
    Camera camera = cameraList.get(0);
    camera.SetProperty(kEdsPropID_SaveTo, kEdsSaveTo_Host);
  }

  EdsTerminateSDK();
  return 0;
}

<|endoftext|>


<commit_before>#include <vector>
#include <tuple>
#include <fstream>
#include "Windows.h"
#include <psapi.h>

using namespace std;

namespace {
  typedef void(*callable)(void*);
  typedef tuple<void*, size_t> MyTuple;
  constexpr DWORD invocation_interval_ms = 15 * 1000;
  constexpr size_t stack_size = 0x10000;

  struct SetupConfiguration {
    uint32_t initialized;
    void* setup_address;
    uint32_t setup_length;
    void* VirtualProtectEx;
    void* WaitForSingleObjectEx;
    void* CreateWaitableTimer;
    void* SetWaitableTimer;
    void* MessageBox;
    void* tramp_addr;
    void* sleep_handle;
    uint32_t interval;
    void* target;
    uint8_t shadow[8];
  };

  struct StackTrampoline {
    void* VirtualProtectEx;
    void* return_address;
    void* current_process;
    void* address;
    uint32_t size;
    uint32_t protections;
    void* old_protections_ptr;
    uint32_t old_protections;
    void* setup_config;
  };

  struct Workspace {
    SetupConfiguration config;
    uint8_t stack[stack_size];
    StackTrampoline tramp;
  };
}

Workspace& allocate_workspace() {
  auto result = VirtualAllocEx(GetCurrentProcess(), nullptr, sizeof(Workspace), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
  if (!result) throw runtime_error("[-] Couldn't VirtualAllocEx: " + GetLastError());
  RtlSecureZeroMemory(result, sizeof(Workspace));
  return *static_cast<Workspace*>(result);
}

MyTuple allocate_pic(const string& filename) {

  fstream file_stream{ filename, fstream::in | fstream::ate | fstream::binary };
  if (!file_stream) throw runtime_error("[-] Couldn't open " + filename);
  auto pic_size = static_cast<size_t>(file_stream.tellg());
  file_stream.seekg(0, fstream::beg);
  auto pic = VirtualAllocEx(GetCurrentProcess(), nullptr, pic_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  if (!pic) throw runtime_error("[-] Couldn't VirtualAllocEx: " + GetLastError());
  file_stream.read(static_cast<char*>(pic), pic_size);
  file_stream.close();
  DWORD old_protection;
  auto prot_result = VirtualProtectEx(GetCurrentProcess(), pic, pic_size, PAGE_EXECUTE_READ, &old_protection);
  if (!prot_result) throw runtime_error("[-] Couldn't VirtualProtectEx: " + GetLastError());
  return MyTuple((void*) pic, (size_t) pic_size);
}

void* get_gadget(bool use_mshtml, const string& gadget_pic_path) {
  if (use_mshtml) {
    printf("[ ] Loading mshtml.dll.\n");
    auto mshtml_base = reinterpret_cast<uint8_t*>(LoadLibraryA("mshtml.dll"));
    printf("[+] Loaded mshtml.dll into memory at 0x%p.\n", mshtml_base);
    return mshtml_base + 7165405;
  } else {
    printf("[ ] Allocating memory for %s.\n", gadget_pic_path.c_str());
    void* memory; size_t size;
    tie(memory, size) = allocate_pic(gadget_pic_path);
    printf("[ ] Allocated %u bytes for gadget PIC.\n", size);
    return memory;
  }
}

void launch(const string& setup_pic_path, const string& gadget_pic_path) {
  printf("[ ] Allocating executable memory for %s.\n", setup_pic_path.c_str());
  void* setup_memory; size_t setup_size;
  tie(setup_memory, setup_size) = allocate_pic(setup_pic_path);
  printf("[+] Allocated %d bytes for PIC.\n", setup_size);

  auto use_mshtml{ true };
  printf("[ ] Configuring ROP gadget.\n");
  auto gadget_memory = get_gadget(use_mshtml, gadget_pic_path);
  printf("[+] ROP gadget configured.\n");

  printf("[ ] Allocating read/write memory for config, stack, and trampoline.\n");
  auto& scratch_memory = allocate_workspace();
  auto& config = scratch_memory.config;
  auto& tramp = scratch_memory.tramp;
  printf("[+] Allocated %u bytes for scratch memory.\n", sizeof(scratch_memory));

  printf("[ ] Building stack trampoline.\n");
  tramp.old_protections_ptr = &tramp.old_protections;
  tramp.protections = PAGE_EXECUTE_READ;
  tramp.current_process = GetCurrentProcess();
  tramp.VirtualProtectEx = VirtualProtectEx;
  tramp.size = static_cast<uint32_t>(setup_size);
  tramp.address = setup_memory;
  tramp.return_address = setup_memory;
  tramp.setup_config = &config;
  printf("[+] Stack trampoline built.\n");

  printf("[ ] Building configuration.\n");
  config.setup_address = setup_memory;
  config.setup_length = static_cast<uint32_t>(setup_size);
  config.VirtualProtectEx = VirtualProtectEx;
  config.WaitForSingleObjectEx = WaitForSingleObjectEx;
  config.CreateWaitableTimer = CreateWaitableTimerW;
  config.SetWaitableTimer = SetWaitableTimer;
  config.MessageBox = MessageBoxA;
  config.tramp_addr = &tramp;
  config.interval = invocation_interval_ms;
  config.target = gadget_memory;
  printf("[+] Configuration built.\n");

  printf("[+] Success!\n");
  printf("    ================================\n");
  printf("    Gargoyle PIC @ -----> 0x%p\n", setup_memory);
  printf("    ROP gadget @ -------> 0x%p\n", gadget_memory);
  printf("    Configuration @ ----> 0x%p\n", &scratch_memory.config);
  printf("    Top of stack @ -----> 0x%p\n", &scratch_memory.stack);
  printf("    Bottom of stack @ --> 0x%p\n", &scratch_memory.stack[stack_size-1]);
  printf("    Stack trampoline @ -> 0x%p\n", &scratch_memory.tramp);

  reinterpret_cast<callable>(setup_memory)(&config);
}

int main() {
  try {
    launch("setup.pic", "gadget.pic");
  } catch (exception& e) {
    printf("%s\n", e.what());
  }
}
<commit_msg>removing unnecessary c-style casts<commit_after>#include <vector>
#include <tuple>
#include <fstream>
#include "Windows.h"
#include <psapi.h>

using namespace std;

namespace {
  typedef void(*callable)(void*);
  typedef tuple<void*, size_t> MyTuple;
  constexpr DWORD invocation_interval_ms = 15 * 1000;
  constexpr size_t stack_size = 0x10000;

  struct SetupConfiguration {
    uint32_t initialized;
    void* setup_address;
    uint32_t setup_length;
    void* VirtualProtectEx;
    void* WaitForSingleObjectEx;
    void* CreateWaitableTimer;
    void* SetWaitableTimer;
    void* MessageBox;
    void* tramp_addr;
    void* sleep_handle;
    uint32_t interval;
    void* target;
    uint8_t shadow[8];
  };

  struct StackTrampoline {
    void* VirtualProtectEx;
    void* return_address;
    void* current_process;
    void* address;
    uint32_t size;
    uint32_t protections;
    void* old_protections_ptr;
    uint32_t old_protections;
    void* setup_config;
  };

  struct Workspace {
    SetupConfiguration config;
    uint8_t stack[stack_size];
    StackTrampoline tramp;
  };
}

Workspace& allocate_workspace() {
  auto result = VirtualAllocEx(GetCurrentProcess(), nullptr, sizeof(Workspace), MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
  if (!result) throw runtime_error("[-] Couldn't VirtualAllocEx: " + GetLastError());
  RtlSecureZeroMemory(result, sizeof(Workspace));
  return *static_cast<Workspace*>(result);
}

MyTuple allocate_pic(const string& filename) {

  fstream file_stream{ filename, fstream::in | fstream::ate | fstream::binary };
  if (!file_stream) throw runtime_error("[-] Couldn't open " + filename);
  auto pic_size = static_cast<size_t>(file_stream.tellg());
  file_stream.seekg(0, fstream::beg);
  auto pic = VirtualAllocEx(GetCurrentProcess(), nullptr, pic_size, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE);
  if (!pic) throw runtime_error("[-] Couldn't VirtualAllocEx: " + GetLastError());
  file_stream.read(static_cast<char*>(pic), pic_size);
  file_stream.close();
  DWORD old_protection;
  auto prot_result = VirtualProtectEx(GetCurrentProcess(), pic, pic_size, PAGE_EXECUTE_READ, &old_protection);
  if (!prot_result) throw runtime_error("[-] Couldn't VirtualProtectEx: " + GetLastError());
  return MyTuple(pic, pic_size);
}

void* get_gadget(bool use_mshtml, const string& gadget_pic_path) {
  if (use_mshtml) {
    printf("[ ] Loading mshtml.dll.\n");
    auto mshtml_base = reinterpret_cast<uint8_t*>(LoadLibraryA("mshtml.dll"));
    printf("[+] Loaded mshtml.dll into memory at 0x%p.\n", mshtml_base);
    return mshtml_base + 7165405;
  } else {
    printf("[ ] Allocating memory for %s.\n", gadget_pic_path.c_str());
    void* memory; size_t size;
    tie(memory, size) = allocate_pic(gadget_pic_path);
    printf("[ ] Allocated %u bytes for gadget PIC.\n", size);
    return memory;
  }
}

void launch(const string& setup_pic_path, const string& gadget_pic_path) {
  printf("[ ] Allocating executable memory for %s.\n", setup_pic_path.c_str());
  void* setup_memory; size_t setup_size;
  tie(setup_memory, setup_size) = allocate_pic(setup_pic_path);
  printf("[+] Allocated %d bytes for PIC.\n", setup_size);

  auto use_mshtml{ true };
  printf("[ ] Configuring ROP gadget.\n");
  auto gadget_memory = get_gadget(use_mshtml, gadget_pic_path);
  printf("[+] ROP gadget configured.\n");

  printf("[ ] Allocating read/write memory for config, stack, and trampoline.\n");
  auto& scratch_memory = allocate_workspace();
  auto& config = scratch_memory.config;
  auto& tramp = scratch_memory.tramp;
  printf("[+] Allocated %u bytes for scratch memory.\n", sizeof(scratch_memory));

  printf("[ ] Building stack trampoline.\n");
  tramp.old_protections_ptr = &tramp.old_protections;
  tramp.protections = PAGE_EXECUTE_READ;
  tramp.current_process = GetCurrentProcess();
  tramp.VirtualProtectEx = VirtualProtectEx;
  tramp.size = static_cast<uint32_t>(setup_size);
  tramp.address = setup_memory;
  tramp.return_address = setup_memory;
  tramp.setup_config = &config;
  printf("[+] Stack trampoline built.\n");

  printf("[ ] Building configuration.\n");
  config.setup_address = setup_memory;
  config.setup_length = static_cast<uint32_t>(setup_size);
  config.VirtualProtectEx = VirtualProtectEx;
  config.WaitForSingleObjectEx = WaitForSingleObjectEx;
  config.CreateWaitableTimer = CreateWaitableTimerW;
  config.SetWaitableTimer = SetWaitableTimer;
  config.MessageBox = MessageBoxA;
  config.tramp_addr = &tramp;
  config.interval = invocation_interval_ms;
  config.target = gadget_memory;
  printf("[+] Configuration built.\n");

  printf("[+] Success!\n");
  printf("    ================================\n");
  printf("    Gargoyle PIC @ -----> 0x%p\n", setup_memory);
  printf("    ROP gadget @ -------> 0x%p\n", gadget_memory);
  printf("    Configuration @ ----> 0x%p\n", &scratch_memory.config);
  printf("    Top of stack @ -----> 0x%p\n", &scratch_memory.stack);
  printf("    Bottom of stack @ --> 0x%p\n", &scratch_memory.stack[stack_size-1]);
  printf("    Stack trampoline @ -> 0x%p\n", &scratch_memory.tramp);

  reinterpret_cast<callable>(setup_memory)(&config);
}

int main() {
  try {
    launch("setup.pic", "gadget.pic");
  } catch (exception& e) {
    printf("%s\n", e.what());
  }
}
<|endoftext|>


<commit_before>4c5459b5-ad5b-11e7-a7b4-ac87a332f658<commit_msg>Did ANOTHER thing<commit_after>4cd53763-ad5b-11e7-ba58-ac87a332f658<|endoftext|>


<commit_before>86b92d1c-ad5a-11e7-aeb1-ac87a332f658<commit_msg>Added that feature we discussed on... Was it monday?<commit_after>873d4fdc-ad5a-11e7-8db2-ac87a332f658<|endoftext|>


<commit_before>d2710438-4b02-11e5-b413-28cfe9171a43<commit_msg>I finished programming, there is nothing left to program<commit_after>d28015fd-4b02-11e5-a789-28cfe9171a43<|endoftext|>


<commit_before>bb5d957a-4b02-11e5-bfc1-28cfe9171a43<commit_msg>more bug fix<commit_after>bb685f3d-4b02-11e5-8821-28cfe9171a43<|endoftext|>


<commit_before>08de11f5-2748-11e6-bc87-e0f84713e7b8<commit_msg>I'm done<commit_after>08e9adc2-2748-11e6-b464-e0f84713e7b8<|endoftext|>


<commit_before>#include <iostream>
#include <chrono>
#include <random>
#include <vector>
#include <cmath>

#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>

std::mt19937 generator;
std::uniform_real_distribution<double> heightDist(0, 1);
std::uniform_int_distribution<int> startDist(-10000, 10000);

sf::Vector2u size;
std::vector<double> heights;
void divideSquare(unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4);

int main(int argc, char** argv)
{
	if(argc != 3)
	{
		std::cerr << "Incorrect # of args, must be 2.\n";
		return 1;
	}

	size = {static_cast<unsigned>(std::stoi(argv[1])), static_cast<unsigned>(std::stoi(argv[2]))};

	// resize vector to correct size
	heights.resize(size.x * size.y);

	// seed generator
	generator.seed(std::chrono::system_clock::now().time_since_epoch().count());

	// begin the recursive algo!
	divideSquare(0, 0, size.x, size.y, -1, -1, -1, -1);

	// make the image
	sf::Image heightMap;
	heightMap.create(size.x, size.y, {255, 255, 255});

	// fill the image
	for(unsigned i = 0; i < size.x * size.y; i++)
	{
		double heightVal = heights[i];

		int r = 255.d * heightVal;
		int g = 255.d * heightVal;
		int b = 255.d * heightVal;

		heightMap.setPixel(i % size.x, i / size.y, {r, g, b});
	}

	heightMap.saveToFile("img" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count()) + ".png");

	return 0;
}

void divideSquare(unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4)
{
	// get corners
	double topLeft, topRight, botLeft, botRight;

	if(c1 == -1 && c2 == -1 && c3 == -1 && c4 == -1)
	{
		topLeft = heightDist(generator);
		topRight = heightDist(generator);
		botLeft = heightDist(generator);
		botRight = heightDist(generator);
	}
	else
	{
		topLeft = c1;
		topRight = c2;
		botLeft = c3;
		botRight = c4;
	}

	// get midpoints on edges
	double topEdge, leftEdge, rightEdge, botEdge;

	topEdge = (topLeft + topRight) / 2;
	leftEdge = (topLeft + botLeft) / 2;
	rightEdge = (topRight + botRight) / 2;
	botEdge = (botLeft + botRight) / 2;

	// middle point of the square
	double middle = (topLeft + topRight + botLeft + botRight) / 4;

	// assign values
	// corners
	heights[x % size.x + y / size.y] = topLeft;
	heights[x % size.x + (w - 1) + y / size.y] = topRight;
	heights[x % size.x + y / size.y + (h - 1)] = botLeft;
	heights[x % size.x + (w - 1) + y / size.y + (h - 1)] = botRight;

	// midpoints
	heights[x % size.x + ((w - 1) / 2) + y / size.y] = topEdge;
	heights[x % size.x + y / size.y + ((h - 1) / 2)] = leftEdge;
	heights[x % size.x + (w - 1) + y / size.y + ((h - 1) / 2)] = rightEdge;
	heights[x % size.x + ((w - 1) / 2) + y / size.y + (h - 1)] = botEdge;
	heights[x % size.x + ((w - 1) / 2) + y / size.y + ((h - 1) / 2)] = middle;

	// if we're too small to continue
	if(!(w > 2 || h > 2))
		return;

	divideSquare(x, y, w / 2, h / 2, topLeft, topEdge, leftEdge, middle);	// top left quad
	divideSquare(x + w / 2, y, w / 2, h / 2, topEdge, topRight, middle, rightEdge);	// top right quad
	divideSquare(x, y + h / 2, w / 2, h / 2, leftEdge, middle, botLeft, botEdge);	// bot left quad
	divideSquare(x + w / 2, y + h / 2, w / 2, h / 2, middle, rightEdge, botEdge, botRight);	// bot right quad
}<commit_msg>Fixed algo to pick the right pixel to color.<commit_after>#include <iostream>
#include <chrono>
#include <random>
#include <vector>

#include <SFML/System/Vector2.hpp>
#include <SFML/Graphics/Image.hpp>

bool done = false;

std::mt19937 generator;
std::uniform_real_distribution<double> heightDist(0, 1);
std::uniform_int_distribution<int> startDist(-10000, 10000);

sf::Vector2u size;
std::vector<double> heights;
void divideSquare(bool first, unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4);

int main(int argc, char** argv)
{
	if(argc != 3)
	{
		std::cerr << "Incorrect # of args, must be 2.\n";
		return 1;
	}

	size = {static_cast<unsigned>(std::stoi(argv[1])), static_cast<unsigned>(std::stoi(argv[2]))};
	// resize vector to correct size
	heights.resize(size.x * size.y, 0);

	// seed generator
	generator.seed(std::chrono::system_clock::now().time_since_epoch().count());

	// make the image
	sf::Image heightMap;
	heightMap.create(size.x, size.y);

	// begin the recursive algo!
	divideSquare(true, 0, 0, size.x, size.y, -1, -1, -1, -1);

	// fill the image
	for(unsigned i = 0; i < size.x * size.y; i++)
	{
		sf::Uint8 r = 255.0 * heights[i];
		sf::Uint8 g = 255.0 * heights[i];
		sf::Uint8 b = 255.0 * heights[i];

		heightMap.setPixel(i % size.x, i / size.y, {r, g, b});
	}

	heightMap.saveToFile("img" + std::to_string(std::chrono::system_clock::now().time_since_epoch().count()) + ".png");

	return 0;
}

void divideSquare(bool first, unsigned x, unsigned y, unsigned w, unsigned h, double c1, double c2, double c3, double c4)
{
	// get corners
	double topLeft, topRight, botLeft, botRight;

	if((c1 == -1 && c2 == -1 && c3 == -1 && c4 == -1) || first)
	{
		topLeft = heightDist(generator);
		topRight = heightDist(generator);
		botLeft = heightDist(generator);
		botRight = heightDist(generator);
	}
	else
	{
		topLeft = c1;
		topRight = c2;
		botLeft = c3;
		botRight = c4;
	}

	// get midpoints on edges
	double topEdge, leftEdge, rightEdge, botEdge;

	if(first)
	{
		topEdge = heightDist(generator);
		leftEdge = heightDist(generator);
		rightEdge = heightDist(generator);
		botEdge = heightDist(generator);
	}
	else
	{
		topEdge = (topLeft + topRight) / 2.0;
		leftEdge = (topLeft + botLeft) / 2.0;
		rightEdge = (topRight + botRight) / 2.0;
		botEdge = (botLeft + botRight) / 2.0;
	}

	// middle point of the square, add a random amount to keep the map less uniform
	double middle;

	if(first)
		middle = heightDist(generator);
	else
		middle = (topLeft + topRight + botLeft + botRight + heightDist(generator)) / 5.0;

	// assign values
	// corners
	heights[(x % size.x) + (y % size.y) * size.x] = topLeft;
	heights[(x + w) % size.x + (y % size.y) * size.x] = topRight;
	heights[(x % size.x) + ((y + h) % size.y) * size.x] = botLeft;
	heights[(x + w) % size.x + ((y + h) % size.y) * size.x] = botRight;

	// midpoints
	heights[(x + (w / 2)) % size.x + (y % size.y) * size.x] = topEdge;
	heights[(x % size.x) + ((y + (h / 2)) % size.y) * size.x] = leftEdge;
	heights[(x + w) % size.x + ((y + (h / 2)) % size.y) * size.x] = rightEdge;
	heights[(x + (w / 2)) % size.x + ((y + h) % size.y) * size.x] = botEdge;
	heights[(x + (w / 2)) % size.x + ((y + (h / 2)) % size.y) * size.x] = middle;

	// if we're too small to continue
	if(!(w > 1 || h > 1))
		return;

	divideSquare(false, x, y, w / 2.0, h / 2.0, topLeft, topEdge, leftEdge, middle);	// top left quad
	divideSquare(false, x + w / 2.0, y, w / 2.0, h / 2.0, topEdge, topRight, middle, rightEdge);	// top right quad
	divideSquare(false, x, y + h / 2.0, w / 2.0, h / 2.0, leftEdge, middle, botLeft, botEdge);	// bot left quad
	divideSquare(false, x + w / 2.0, y + h / 2.0, w / 2.0, h / 2.0, middle, rightEdge, botEdge, botRight);	// bot right quad
}
<|endoftext|>


<commit_before>#include "include/input/input.hpp"
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <iostream>

int main() {
	cv::Mat image;

	cv::namedWindow("BGR Feed", cv::WINDOW_AUTOSIZE);
	cv::namedWindow("Depth Feed", cv::WINDOW_AUTOSIZE);
	cv::namedWindow("IR Feed", cv::WINDOW_AUTOSIZE);

	Input *input = new Input();

	input->getBGR(image);
	cv::imshow("BGR Feed", image);

	input->getDepth(image);
	cv::imshow("Depth Feed", image);

	input->getIR(image);
	cv::imshow("IR Feed", image);

	return 0;
}
<commit_msg>Delete main.cpp<commit_after><|endoftext|>


<commit_before>#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>

using namespace std;

//function to convert a vector of char * to a
//char * [] for use as an execvp argument
char ** conv_vec(vector<char*> v)
{
    //create a char * [] of proper size
    char ** t = new char* [v.size() + 1];

    //counter to keep track of the position
    //for entering char*
    unsigned i = 0;

    for (; i < v.size(); ++i)
    {
        //first make char[] entry of the right length
        t[i] = new char[strlen(v.at(i))];
        //then copy the entire string from the vector
        //into the char *[]
        strcpy(t[i], v.at(i));
    }

    //set the last position to a null character
    t[i] = '\0';

    return t;
}

char ** get_command(string& a, int& flag)
{
    //first make a copy of the command string
    //so that we can check what delimiter strtok
    //stopped at
    char * copy = new char [a.length() + 1];
    strcpy(copy, a.c_str());

    //create a vector because we do not know
    //how many tokens are in the command entered
    vector<char *> temp;

    //create an empty char * [] to return. It can
    //either be empty if there is no input or
    //filled later when we convert the vector
    //into an array
    char ** vec = NULL;

    //bool done = false;
    //set a starting position to reference when
    //finding the position of the delimiter found
    char * begin = copy;

    //take the first token
    char * token = strtok(copy, " ;|&");

    //for position of delimiter
    unsigned int pos;

    while (token != 0)
    {
//        cout << token << endl;

        //the position of the delimiter with respect
        //to the beginning of the array
        pos = token - begin + strlen(token);

        //put the token at the end of the vector
        temp.push_back(token);

        //to find out which delimiter was found
        //if it was the end, it will not go through this
        if (pos < a.size())
        {
            //store delimiter character found
            char delim = a.at(pos);
//            cout << delim << endl;

            if (delim != ' ' || (pos + 1 < a.size() && (a.at(pos + 1) == '&' ||
                a.at(pos + 1) == '|')))
            {
                //if it was not ' ' then we have reached a
                //delimiter that indicates the end of the
                //command so we are done. Convert
                //the vector into the proper char * []
                vec = conv_vec(temp);

//                for (unsigned i = 0; vec[i] != 0; ++i)
//                {
//                    cout << i << endl;
//                    cout << vec[i] <<  endl;
//                }

                //remember to get rid of the dynamically allocated
                delete copy;

                if (delim == '|' || (pos + 1 < a.size() && a.at(pos + 1) == '|'))
                {
                    //set flag bit
                    flag = 1;
                }
                else if (delim == '&' || (pos + 1 < a.size() && a.at(pos + 1)
                    == '&'))
                {
                    //set flag bit to 2
                    flag = 2;
                }
                else
                {
                    //then it was ; so set flag bit to 0
                    flag = 0;
                }

                cout << flag << endl;
                a = a.substr(pos + 1, a.size() - pos + 1);

                return vec;
            }

        }

        token = strtok(NULL, " ;|&");
    }

    a = "";

    vec = conv_vec(temp);

    delete copy;

    flag = 0;

    return vec;
}

void display_prompt()
{
    char host[15];

    int host_flag = gethostname(host, sizeof host);
    if(host_flag == -1)
    {
        perror("gethostname");
    }
    char *login = getlogin();
    if (login == 0)
    {
        perror("getlogin");
    }

    cout << login << '@' << host << "$ ";
}

int main()
{
    int flag = 0;
    while (1)
    {

        display_prompt();
        string command;
        getline(cin, command);
        while(flag != 0 || command != "")
        {
            char ** argv = get_command(command, flag);

            cout << command << endl;
            cout << flag << endl;

            if (strcmp(argv[0], "exit") == 0)
            {
                return 0;
            }

            for (int i = 0; argv[i] != 0; ++i)
            {
                cout << argv[i] << endl;
            }

            int fork_flag = fork();
            if (fork_flag == -1)
            {
                perror("fork");

                return 1;
            }
            else if (fork_flag == 0)
            {
                int execvp_flag = execvp(argv[0], argv);
                if (execvp_flag == -1)
                {
                    perror("execvp");
//                    return 1;
                }
            }

            int wait_flag = wait(NULL);
            if (wait_flag == -1)
            {
                perror("wait");
                if (flag == 2)
                {
                    break;
                }
//                return 1;
            }
            if (flag == 1)
            {
                break;
            }
        }
    }

    return 0;
}
<commit_msg>uncommented the return 1 to see if there was any error<commit_after>#include <iostream>
#include <vector>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>

using namespace std;

//function to convert a vector of char * to a
//char * [] for use as an execvp argument
char ** conv_vec(vector<char*> v)
{
    //create a char * [] of proper size
    char ** t = new char* [v.size() + 1];

    //counter to keep track of the position
    //for entering char*
    unsigned i = 0;

    for (; i < v.size(); ++i)
    {
        //first make char[] entry of the right length
        t[i] = new char[strlen(v.at(i))];
        //then copy the entire string from the vector
        //into the char *[]
        strcpy(t[i], v.at(i));
    }

    //set the last position to a null character
    t[i] = '\0';

    return t;
}

char ** get_command(string& a, int& flag)
{
    //first make a copy of the command string
    //so that we can check what delimiter strtok
    //stopped at
    char * copy = new char [a.length() + 1];
    strcpy(copy, a.c_str());

    //create a vector because we do not know
    //how many tokens are in the command entered
    vector<char *> temp;

    //create an empty char * [] to return. It can
    //either be empty if there is no input or
    //filled later when we convert the vector
    //into an array
    char ** vec = NULL;

    //bool done = false;
    //set a starting position to reference when
    //finding the position of the delimiter found
    char * begin = copy;

    //take the first token
    char * token = strtok(copy, " ;|&");

    //for position of delimiter
    unsigned int pos;

    while (token != 0)
    {
//        cout << token << endl;

        //the position of the delimiter with respect
        //to the beginning of the array
        pos = token - begin + strlen(token);

        //put the token at the end of the vector
        temp.push_back(token);

        //to find out which delimiter was found
        //if it was the end, it will not go through this
        if (pos < a.size())
        {
            //store delimiter character found
            char delim = a.at(pos);
//            cout << delim << endl;

            if (delim != ' ' || (pos + 1 < a.size() && (a.at(pos + 1) == '&' ||
                a.at(pos + 1) == '|')))
            {
                //if it was not ' ' then we have reached a
                //delimiter that indicates the end of the
                //command so we are done. Convert
                //the vector into the proper char * []
                vec = conv_vec(temp);

//                for (unsigned i = 0; vec[i] != 0; ++i)
//                {
//                    cout << i << endl;
//                    cout << vec[i] <<  endl;
//                }

                //remember to get rid of the dynamically allocated
                delete copy;

                if (delim == '|' || (pos + 1 < a.size() && a.at(pos + 1) == '|'))
                {
                    //set flag bit
                    flag = 1;
                }
                else if (delim == '&' || (pos + 1 < a.size() && a.at(pos + 1)
                    == '&'))
                {
                    //set flag bit to 2
                    flag = 2;
                }
                else
                {
                    //then it was ; so set flag bit to 0
                    flag = 0;
                }

                cout << flag << endl;
                a = a.substr(pos + 1, a.size() - pos + 1);

                return vec;
            }

        }

        token = strtok(NULL, " ;|&");
    }

    a = "";

    vec = conv_vec(temp);

    delete copy;

    flag = 0;

    return vec;
}

void display_prompt()
{
    char host[15];

    int host_flag = gethostname(host, sizeof host);
    if(host_flag == -1)
    {
        perror("gethostname");
    }
    char *login = getlogin();
    if (login == 0)
    {
        perror("getlogin");
    }

    cout << login << '@' << host << "$ ";
}

int main()
{
    int flag = 0;
    while (1)
    {

        display_prompt();
        string command;
        getline(cin, command);
        while(flag != 0 || command != "")
        {
            char ** argv = get_command(command, flag);

            cout << command << endl;
            cout << flag << endl;

            if (strcmp(argv[0], "exit") == 0)
            {
                return 0;
            }

            for (int i = 0; argv[i] != 0; ++i)
            {
                cout << argv[i] << endl;
            }

            int fork_flag = fork();
            if (fork_flag == -1)
            {
                perror("fork");

                return 1;
            }
            else if (fork_flag == 0)
            {
                int execvp_flag = execvp(argv[0], argv);
                if (execvp_flag == -1)
                {
                    perror("execvp");
                    return 1;
                }
            }

            int wait_flag = wait(NULL);
            if (wait_flag == -1)
            {
                perror("wait");
                if (flag == 2)
                {
                    break;
                }
//                return 1;
            }
            if (flag == 1)
            {
                break;
            }
        }
    }

    return 0;
}
<|endoftext|>


<commit_before><commit_msg>Main socket-forking<commit_after>/*Main*/

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <string.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <netdb.h>

#define BUFFER_SIZE 1024

using namespace std;

int main() {
	//Create a listener socket
	int sock = socket(PF_INET, SOCK_STREAM, 0);
	if (sock < 0) {
		cerr << "Failed to create a listener socket. Exiting..." << endl;
		exit(EXIT_FAILURE);
	}
	//Socket address struct
	struct sockaddr_in server;
	server.sin_family = PF_INET;
	server.sin_addr.s_addr = INADDR_ANY;
	//Assign port
	unsigned short port = 8765;
	server.sin_port = htons(port);
	//Bind socket to address
	int serverSize = sizeof(server);
	if (bind(sock, (struct sockaddr *)&server, serverSize) < 0) {
		cerr << "Failed to bind socket. Exiting..." << endl;
		exit(EXIT_FAILURE);
	}
	//Listen for up to SOMAXCONN clients
	listen(sock, 128);
	cout << "Listening on port " << port << endl;

	struct sockaddr_in client;
	int clientSize = sizeof(client);

	int pid;
	char buffer[BUFFER_SIZE];

	while (1) {
		int newsock = accept(sock, (struct sockaddr *)&client, (socklen_t*)&clientSize);
		//Get hostname
		char hostName[NI_MAXHOST];
		struct in_addr ipv4addr;
		inet_pton(AF_INET, inet_ntoa(client.sin_addr), &ipv4addr);
		if (getnameinfo(client, clientSize, hostName, sizeof(hostName), NULL, 0, NI_NAMEREQD) != 0) {
			cout << "Received incoming connection from unresolved host" << endl;
		}
		else {
			cout << "Received incoming connection from " << hostName << endl;
		}
		//Fork the new socket
		pid = fork();
		//Client fork doesn't exist
		if (pid < 0) {
			cerr << "Could not fork client socket. Exiting..." << endl;
			exit(EXIT_FAILURE);
		}
		//Client thread
		else if (pid == 0) {
			int n;
			do {
				n = 0; //***TEMP***
			} while (n > 0);
			cout << "Client closed its socket....terminating" << endl;
		}
		//Server
		else {
			close(newsock);
		}
	}
	close(sock);
	return EXIT_SUCCESS;
}<|endoftext|>


<commit_before>#include <iostream>
#include <string>
#include <vector>
#include <list>

#include "opencv.hpp"

using namespace cv;
using namespace std;
using namespace flann;

static const double PI = 3.1415926536;

struct Options
{
	int threshold;
	double subsample; // 0..1 -> size on load
	float minLineLength;
	float relativeLengthTolerance;
	int percentStarsRequired;
	float starDistCutoff;
};

struct Star
{
	double x, y;
	double r;

	Star(double x, double y, double r)
	{
		this->x = x;
		this->y = y;
		this->r = r;
	}

	Star(const Star &s)
		: x(s.x), y(s.y), r(s.r)
	{
	}
};

struct Blob
{
	double x, y;
	double S;
};

Blob operator+(const Blob & l, const Blob & r)
{
	Blob q;
	q.S = l.S + r.S;
	q.x = (l.S*l.x + r.S*r.x) / q.S;

	q.y = (l.S*l.y + r.S*r.y) / q.S;
}

Blob & operator+=(Blob & blob, const Blob & x)
{
	double S = blob.S + x.S;
	blob.x = (blob.S*blob.x + x.S*x.x) / S;
	blob.y = (blob.S*blob.y + x.S*x.y) / S;
	blob.S = S;
}

bool operator<(const Star & l, const Star & r)
{
	if (l.r < r.r)
		return true;
	if (l.r > r.r)
		return false;

	return (l.x < r.x);
}

typedef vector<Star> Stars;
typedef vector<Blob> Blobs;

void die(const string & msg)
{
	cerr << "Error: " << msg << endl;
	exit(1);
}

inline double sqr(double x)
{
	return x*x;
}

Point2f controlPoint(const Point2f & u, const Point2f & v)
{
	double dx = v.x - u.x;
	double dy = v.y - u.y;

	return Point2f(u.x - dy, u.y + dx);
}

struct Line
{
	Star a, b;
	double length;

	Line(const Star & a_, const Star & b_)
		: a(a_), b(b_)
	{
		length = sqrt(sqr(a.x-b.x) + sqr(a.y - b.y));
	}

	Line(const Line& x)
		: a(x.a), b(x.b), length(x.length)
	{
	}
};

bool operator<(const Line & l, const Line & r)
{
	return (l.length < r.length);
}

void getLines(const Stars & stars, vector<Line> & lines)
{
	for (int i = 0; i < stars.size(); ++i)
	{
		for (int j = i+1; j < stars.size(); ++j)
		{
			lines.push_back(Line(stars[i], stars[j]));
		}
	}
}

Mat getLineTransform(const Line & a, const Line & b)
{
	Point2f xp[3], yp[3];
	xp[0] = Point2f(a.a.x, a.a.y);
	xp[1] = Point2f(a.b.x, a.b.y);
	xp[2] = controlPoint(xp[0], xp[1]);

	yp[0] = Point2f(b.a.x, b.a.y);
	yp[1] = Point2f(b.b.x, b.b.y);
	yp[2] = controlPoint(yp[0], yp[1]);

	return getAffineTransform(xp, yp);
}

struct ScanItem
{
	Blob blob;
	int l, r;

	ScanItem(int _l, int _r, const Blob & _b)
		: l(_l), r(_r), blob(_b)
	{}
};

double evaluate(const Mat & trans, const Stars & xs, Index_<double> & yindex, const Options & opt)
{
	Mat q(3, xs.size(), CV_64F);
	for (int x = 0; x < xs.size(); ++x)
	{
		q.at<double>(0, x) = xs[x].x;
		q.at<double>(1, x) = xs[x].y;
		q.at<double>(2, x) = 1;
	}
	Mat query = trans * q;

	Mat indices(xs.size(), 1, CV_32S), dists(xs.size(), 1, CV_32F);
	yindex.knnSearch(query.t(), indices, dists, 1, SearchParams());

	int cnt = 0;
	double sum = 0;
	for (int i = 0; i < dists.rows; ++i)
	{
		float dist = dists.at<float>(i, 0);
		if (dist < opt.starDistCutoff) {
			++cnt;
			sum += dist;
		}
	}

	if (cnt < opt.percentStarsRequired * xs.size() / 100)
	{
		// cout << "Not enough stars: " << cnt << endl;
		return 0;
	}

	return opt.starDistCutoff - sum/cnt;
}

bool getTransform(const Stars & xs, const Stars & ys, Mat & bestTrans, const Options & opt)
{
	// precompute NN search index
	Mat ymat(ys.size(), 2, CV_64F);
	for (int y = 0; y < ys.size(); ++y)
	{
		ymat.at<double>(y, 0) = ys[y].x;
		ymat.at<double>(y, 1) = ys[y].y;
	}
	Index_<double> yindex(ymat, AutotunedIndexParams());

	// find all lines
	vector<Line> xl, yl;
	getLines(xs, xl);
	getLines(ys, yl);

	// sort the lines
	sort(xl.rbegin(), xl.rend());
	sort(yl.begin(), yl.end());

	// cout << "X lines: " << xl.size() << ", Y lines: " << yl.size() << endl;

	bestTrans = Mat::eye(2, 3, CV_64F);
	double bestScore = 0;
	int bestOfs = 0;

	for (int i = 0; i < xl.size(); ++i)
	{
		const Line & xline = xl[i];
		double xlen = xline.length;

		if (xlen < opt.minLineLength)
			break;

		// bisect -> find estimate
		int lo = 0;
		int hi = yl.size() - 1;
		while (lo < hi)
		{
			int mid = (lo + hi) / 2;
			if (xlen < yl[mid].length)
				hi = mid;
			else
				lo = mid+1;
		}

		// find upper && lower bound
		int estimate = lo;
		int estlo = estimate, esthi = estimate;
		double tolerance = xlen * opt.relativeLengthTolerance;
		while (estlo >= 0 && yl[estlo].length + tolerance >= xlen)
			--estlo;
		while (esthi < yl.size() && yl[esthi].length - tolerance <= xlen)
			++esthi;

		hi = lo+1;
		// cout << " within (" << estlo-estimate << "," << esthi-estimate << ")" << endl;
		while (lo > estlo || hi < esthi)
		{
			if (lo > estlo)
			{
				Mat trans = getLineTransform(xline, yl[lo]);
				double score = evaluate(trans, xs, yindex, opt);
				if (score > bestScore)
				{
					bestScore = score;
					bestTrans = trans;
					bestOfs = lo - estimate;
				}
			}

			if (hi < esthi)
			{
				Mat trans = getLineTransform(xline, yl[hi]);
				double score = evaluate(trans, xs, yindex, opt);
				if (score > bestScore)
				{
					bestScore = score;
					bestTrans = trans;
					bestOfs = hi - estimate;
				}
			}

			--lo;
			++hi;
		}
	}

	cout << "Best score is " << opt.starDistCutoff-bestScore << " at offset " << bestOfs << endl;
	return (bestScore > 0);
};

void findBlobs(const Mat & mat, Blobs & blobs)
{
	/*
	namedWindow("foo");
	imshow("foo", mat);
	waitKey(1000);
	*/

	//cout << "depth: " << mat.depth() << ", type: " << mat.type() << ", chans: " << mat.channels() << endl;
	list<ScanItem> scan, newscan;
	for (int y = 0; y < mat.rows; ++y)
	{
		const uint8_t * row = mat.ptr<uint8_t>(y);
		list<ScanItem>::iterator it = scan.begin();
		int l = 0;
		for (int x = 0; x < mat.cols; ++x)
		{
			// skip blanks
			while (it != scan.end() && it->r < x)
			{
				blobs.push_back(it->blob);
				++it;
			}

			// find the end of the white segment
			while (x < mat.cols && row[x])
				++x;

			// if white segment found
			if (row[l])
			{
				//cout << "rowscan at " << l << ".." << x << "," << y << endl;
				Blob cur = {(x+l-1)/2.0, y, x-l};
				while (it != scan.end() && it->l < x)
				{
					cur += it->blob;
					++it;
				}
				newscan.push_back(ScanItem(l,x-1,cur));
			}

			l = ++x;
		}
		scan = newscan;
		newscan.clear();
	}

	for (list<ScanItem>::const_iterator it = scan.begin(); it != scan.end(); ++it)

	{
		blobs.push_back(it->blob);
	}
}

void findStars(const Mat & srcimg, Stars & stars, int thresh)
{
	// threshold the image
	Mat image;
	threshold(srcimg, image, thresh, 255, THRESH_BINARY);

	// find the blobs
	Blobs blobs;
	findBlobs(image, blobs);

	// traverse the blobs
	stars.clear();
	for (Blobs::const_iterator it = blobs.begin(); it != blobs.end(); ++it)
	{
		stars.push_back(Star(it->x, it->y, sqrt(it->S / PI)));
	}
}

inline uint8_t clamp(int x)
{
	return (x < 0) ? 0 : ((x > 255) ? 255 : x);
}

#define FOREACH(st) \
	for (int y = 0; y < mat.rows; ++y) 			\
	{							\
		uint8_t * row = mat.ptr<uint8_t>(y);	\
		const uint8_t * end = row + mat.cols;		\
		while (row < end) {				\
			st;				\
			++row;					\
		}						\
	}
void normalize(Mat & mat)
{
	int sum = 0;
	FOREACH(sum += *row);

	int N = mat.rows * mat.cols;
	int avg = sum / N;
	int sqdiff = 0;
	FOREACH(sqdiff += (avg-*row) * (avg-*row));

	int var = sqdiff / N;
	int sigma = lround(sqrt(var));

	FOREACH(*row = clamp(255 * ((int) *row - (int) avg) / (16 * sigma)));
}

Mat merge(const vector<string> & fn, int a, int b, const Options & opt)
{
	if (a+1 >= b)
	{
		cout << "Loading " << fn[a] << endl;
		Mat full = imread(fn[a], CV_LOAD_IMAGE_GRAYSCALE);
		Mat subsampled;
		resize(full, subsampled, Size(0,0), opt.subsample, opt.subsample);
		normalize(subsampled);
		return subsampled;
	}

	// merge recursively
	int mid = (a + b) / 2;
	Mat l = merge(fn, a, mid, opt);
	Mat r = merge(fn, mid, b, opt);

	// align the images
	Stars lstars, rstars;
	findStars(l, lstars, opt.threshold);
	findStars(r, rstars, opt.threshold);
	Mat trans;
	bool ret = getTransform(lstars, rstars, trans, opt);
	if (!ret) {
		cout << "Could not align images!" << endl;
		return l; // no transform could be found -> return (arbitrarily) the left child
	}

	// remap
	Mat lremap;
	warpAffine(l, lremap, trans, r.size());

	// merge
	return (0.5*lremap + 0.5*r);
}

int main(int argc, char ** argv)
{
	char ** end =  argv + argc;
	++argv; // skip the name of the executable

	// some default options
	Options opt;
	opt.threshold = 128;
	opt.subsample = 0.3;
	opt.minLineLength = 100;
	opt.percentStarsRequired = 50;
	opt.relativeLengthTolerance = 0.05;
	opt.starDistCutoff = 100;

	// get the options
	while (argv < end)
	{
		// end of options
		if (**argv != '-')
			break;

		string opt = *argv++;

		// no options will follow
		if (opt == "--")
			break;

		die("unknown option " + opt);
	}

	// get the list of images
	vector<string> imgNames;
	while (argv < end)
		imgNames.push_back(*argv++);

	// perform some sanity checks
	if (imgNames.size() < 2)
		die("no point in aligning less than two images");

	// stack the images
	Mat stack = merge(imgNames, 0, imgNames.size(), opt);

	namedWindow("preview");
	imshow("preview", stack);
	waitKey(0);

	return 0;
}
<commit_msg>Threshold autodetection.<commit_after>#include <iostream>
#include <string>
#include <vector>
#include <list>

#include "opencv.hpp"

using namespace cv;
using namespace std;
using namespace flann;

static const double PI = 3.1415926536;

struct Options
{
	int threshold;
	double subsample; // 0..1 -> size on load
	float minLineLength;
	float relativeLengthTolerance;
	int percentStarsRequired;
	float starDistCutoff;
	int starCount;
};

struct Star
{
	double x, y;
	double r;

	Star(double x, double y, double r)
	{
		this->x = x;
		this->y = y;
		this->r = r;
	}

	Star(const Star &s)
		: x(s.x), y(s.y), r(s.r)
	{
	}
};

struct Blob
{
	double x, y;
	double S;
};

Blob operator+(const Blob & l, const Blob & r)
{
	Blob q;
	q.S = l.S + r.S;
	q.x = (l.S*l.x + r.S*r.x) / q.S;

	q.y = (l.S*l.y + r.S*r.y) / q.S;
}

Blob & operator+=(Blob & blob, const Blob & x)
{
	double S = blob.S + x.S;
	blob.x = (blob.S*blob.x + x.S*x.x) / S;
	blob.y = (blob.S*blob.y + x.S*x.y) / S;
	blob.S = S;
}

bool operator<(const Star & l, const Star & r)
{
	if (l.r < r.r)
		return true;
	if (l.r > r.r)
		return false;

	return (l.x < r.x);
}

typedef vector<Star> Stars;
typedef vector<Blob> Blobs;

void die(const string & msg)
{
	cerr << "Error: " << msg << endl;
	exit(1);
}

inline double sqr(double x)
{
	return x*x;
}

Point2f controlPoint(const Point2f & u, const Point2f & v)
{
	double dx = v.x - u.x;
	double dy = v.y - u.y;

	return Point2f(u.x - dy, u.y + dx);
}

struct Line
{
	Star a, b;
	double length;

	Line(const Star & a_, const Star & b_)
		: a(a_), b(b_)
	{
		length = sqrt(sqr(a.x-b.x) + sqr(a.y - b.y));
	}

	Line(const Line& x)
		: a(x.a), b(x.b), length(x.length)
	{
	}
};

bool operator<(const Line & l, const Line & r)
{
	return (l.length < r.length);
}

void getLines(const Stars & stars, vector<Line> & lines)
{
	for (int i = 0; i < stars.size(); ++i)
	{
		for (int j = i+1; j < stars.size(); ++j)
		{
			lines.push_back(Line(stars[i], stars[j]));
		}
	}
}

Mat getLineTransform(const Line & a, const Line & b)
{
	Point2f xp[3], yp[3];
	xp[0] = Point2f(a.a.x, a.a.y);
	xp[1] = Point2f(a.b.x, a.b.y);
	xp[2] = controlPoint(xp[0], xp[1]);

	yp[0] = Point2f(b.a.x, b.a.y);
	yp[1] = Point2f(b.b.x, b.b.y);
	yp[2] = controlPoint(yp[0], yp[1]);

	return getAffineTransform(xp, yp);
}

struct ScanItem
{
	Blob blob;
	int l, r;

	ScanItem(int _l, int _r, const Blob & _b)
		: l(_l), r(_r), blob(_b)
	{}
};

double evaluate(const Mat & trans, const Stars & xs, Index_<double> & yindex, const Options & opt)
{
	Mat q(3, xs.size(), CV_64F);
	for (int x = 0; x < xs.size(); ++x)
	{
		q.at<double>(0, x) = xs[x].x;
		q.at<double>(1, x) = xs[x].y;
		q.at<double>(2, x) = 1;
	}
	Mat query = trans * q;

	Mat indices(xs.size(), 1, CV_32S), dists(xs.size(), 1, CV_32F);
	yindex.knnSearch(query.t(), indices, dists, 1, SearchParams());

	int cnt = 0;
	double sum = 0;
	for (int i = 0; i < dists.rows; ++i)
	{
		float dist = dists.at<float>(i, 0);
		if (dist < opt.starDistCutoff) {
			++cnt;
			sum += dist;
		}
	}

	if (cnt < opt.percentStarsRequired * xs.size() / 100)
	{
		// cout << "Not enough stars: " << cnt << endl;
		return 0;
	}

	return opt.starDistCutoff - sum/cnt;
}

bool getTransform(const Stars & xs, const Stars & ys, Mat & bestTrans, const Options & opt)
{
	// precompute NN search index
	Mat ymat(ys.size(), 2, CV_64F);
	for (int y = 0; y < ys.size(); ++y)
	{
		ymat.at<double>(y, 0) = ys[y].x;
		ymat.at<double>(y, 1) = ys[y].y;
	}
	Index_<double> yindex(ymat, AutotunedIndexParams());

	// find all lines
	vector<Line> xl, yl;
	getLines(xs, xl);
	getLines(ys, yl);

	// sort the lines
	sort(xl.rbegin(), xl.rend());
	sort(yl.begin(), yl.end());

	// cout << "X lines: " << xl.size() << ", Y lines: " << yl.size() << endl;

	bestTrans = Mat::eye(2, 3, CV_64F);
	double bestScore = 0;
	int bestOfs = 0;

	for (int i = 0; i < xl.size(); ++i)
	{
		const Line & xline = xl[i];
		double xlen = xline.length;

		if (xlen < opt.minLineLength)
			break;

		// bisect -> find estimate
		int lo = 0;
		int hi = yl.size() - 1;
		while (lo < hi)
		{
			int mid = (lo + hi) / 2;
			if (xlen < yl[mid].length)
				hi = mid;
			else
				lo = mid+1;
		}

		// find upper && lower bound
		int estimate = lo;
		int estlo = estimate, esthi = estimate;
		double tolerance = xlen * opt.relativeLengthTolerance;
		while (estlo >= 0 && yl[estlo].length + tolerance >= xlen)
			--estlo;
		while (esthi < yl.size() && yl[esthi].length - tolerance <= xlen)
			++esthi;

		hi = lo+1;
		// cout << " within (" << estlo-estimate << "," << esthi-estimate << ")" << endl;
		while (lo > estlo || hi < esthi)
		{
			if (lo > estlo)
			{
				Mat trans = getLineTransform(xline, yl[lo]);
				double score = evaluate(trans, xs, yindex, opt);
				if (score > bestScore)
				{
					bestScore = score;
					bestTrans = trans;
					bestOfs = lo - estimate;
				}
			}

			if (hi < esthi)
			{
				Mat trans = getLineTransform(xline, yl[hi]);
				double score = evaluate(trans, xs, yindex, opt);
				if (score > bestScore)
				{
					bestScore = score;
					bestTrans = trans;
					bestOfs = hi - estimate;
				}
			}

			--lo;
			++hi;
		}
	}

	cout << "Best score is " << opt.starDistCutoff-bestScore << " at offset " << bestOfs << endl;
	return (bestScore > 0);
};

void findBlobs(const Mat & mat, Blobs & blobs)
{
	/*
	namedWindow("foo");
	imshow("foo", mat);
	waitKey(1000);
	*/

	//cout << "depth: " << mat.depth() << ", type: " << mat.type() << ", chans: " << mat.channels() << endl;
	list<ScanItem> scan, newscan;
	for (int y = 0; y < mat.rows; ++y)
	{
		const uint8_t * row = mat.ptr<uint8_t>(y);
		list<ScanItem>::iterator it = scan.begin();
		int l = 0;
		for (int x = 0; x < mat.cols; ++x)
		{
			// skip blanks
			while (it != scan.end() && it->r < x)
			{
				blobs.push_back(it->blob);
				++it;
			}

			// find the end of the white segment
			while (x < mat.cols && row[x])
				++x;

			// if white segment found
			if (row[l])
			{
				//cout << "rowscan at " << l << ".." << x << "," << y << endl;
				Blob cur = {(x+l-1)/2.0, y, x-l};
				while (it != scan.end() && it->l < x)
				{
					cur += it->blob;
					++it;
				}
				newscan.push_back(ScanItem(l,x-1,cur));
			}

			l = ++x;
		}
		scan = newscan;
		newscan.clear();
	}

	for (list<ScanItem>::const_iterator it = scan.begin(); it != scan.end(); ++it)

	{
		blobs.push_back(it->blob);
	}
}

void findStars(const Mat & srcimg, Stars & stars, int thresh)
{
	// threshold the image
	Mat image;
	threshold(srcimg, image, thresh, 255, THRESH_BINARY);

	// find the blobs
	Blobs blobs;
	findBlobs(image, blobs);

	// traverse the blobs
	stars.clear();
	for (Blobs::const_iterator it = blobs.begin(); it != blobs.end(); ++it)
	{
		stars.push_back(Star(it->x, it->y, sqrt(it->S / PI)));
	}
}

inline uint8_t clamp(int x)
{
	return (x < 0) ? 0 : ((x > 255) ? 255 : x);
}

#define FOREACH(st) \
	for (int y = 0; y < mat.rows; ++y) 			\
	{							\
		uint8_t * row = mat.ptr<uint8_t>(y);	\
		const uint8_t * end = row + mat.cols;		\
		while (row < end) {				\
			st;				\
			++row;					\
		}						\
	}
void normalize(Mat & mat)
{
	int sum = 0;
	FOREACH(sum += *row);

	int N = mat.rows * mat.cols;
	int avg = sum / N;
	int sqdiff = 0;
	FOREACH(sqdiff += (avg-*row) * (avg-*row));

	int var = sqdiff / N;
	int sigma = lround(sqrt(var));

	FOREACH(*row = clamp(255 * ((int) *row - (int) avg) / (16 * sigma)));
}

Mat merge(const vector<string> & fn, int a, int b, Options & opt)
{
	if (a+1 >= b)
	{
		cout << "Loading " << fn[a] << endl;
		Mat full = imread(fn[a], CV_LOAD_IMAGE_GRAYSCALE);
		Mat subsampled;
		resize(full, subsampled, Size(0,0), opt.subsample, opt.subsample);
		normalize(subsampled);
		return subsampled;
	}

	// merge recursively
	int mid = (a + b) / 2;
	Mat l = merge(fn, a, mid, opt);
	Mat r = merge(fn, mid, b, opt);

	// align the images
	Stars lstars, rstars;

	if (opt.threshold == -1)
	{ // autodetect threshold
		lstars.clear();
		int thresh = 128;
		int cnt = 0;
		while (true) {
			findStars(l, lstars, thresh);
			cnt = lstars.size();
			if (abs(cnt - opt.starCount) < opt.starCount/5)
				break;
			else if (cnt < opt.starCount)
				thresh = thresh / 2;
			else
				thresh = (thresh + 255) / 2;

			if (opt.threshold == thresh)
			{
				cerr << "Warning: could not estimate threshold." << endl;
				break;
			}
			else
			{
				opt.threshold = thresh;
			}
		}
		cout << "Threshold auto-estimated at " << opt.threshold << endl;
	}
	else
	{
		findStars(l, lstars, opt.threshold);
	}
	findStars(r, rstars, opt.threshold);
	Mat trans;
	bool ret = getTransform(lstars, rstars, trans, opt);
	if (!ret) {
		cout << "Could not align images!" << endl;
		return l; // no transform could be found -> return (arbitrarily) the left child
	}

	// remap
	Mat lremap;
	warpAffine(l, lremap, trans, r.size());

	// merge
	return (0.5*lremap + 0.5*r);
}

int main(int argc, char ** argv)
{
	char ** end =  argv + argc;
	++argv; // skip the name of the executable

	// some default options
	Options opt;
	opt.threshold = -1; // autodetect
	opt.subsample = 0.5;
	opt.minLineLength = 100;
	opt.percentStarsRequired = 50;
	opt.relativeLengthTolerance = 0.05;
	opt.starDistCutoff = 100;
	opt.starCount = 15;

	// get the options
	while (argv < end)
	{
		// end of options
		if (**argv != '-')
			break;

		string opt = *argv++;

		// no options will follow
		if (opt == "--")
			break;

		die("unknown option " + opt);
	}

	// get the list of images
	vector<string> imgNames;
	while (argv < end)
		imgNames.push_back(*argv++);

	// perform some sanity checks
	if (imgNames.size() < 2)
		die("no point in aligning less than two images");

	// stack the images
	Mat stack = merge(imgNames, 0, imgNames.size(), opt);

	namedWindow("preview");
	imshow("preview", stack);
	waitKey(0);

	return 0;
}
<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

void rasterize_triangle_fixed16_8(
    uint32_t* fb, uint32_t fb_width,
    uint32_t x0, uint32_t y0, uint32_t z0,
    uint32_t x1, uint32_t y1, uint32_t z1,
    uint32_t x2, uint32_t y2, uint32_t z2)
{
    // window coordinates' bounding box
    uint32_t x_min = x0, x_max = x0;
    if (x1 < x_min) x_min = x1;
    if (x2 < x_min) x_min = x2;
    if (x1 > x_max) x_max = x1;
    if (x2 > x_max) x_max = x2;

    uint32_t y_min = y0, y_max = y0;
    if (y1 < y_min) y_min = y1;
    if (y2 < y_min) y_min = y2;
    if (y1 > y_max) y_max = y1;
    if (y2 > y_max) y_max = y2;

    // barycentric coordinates of top left corner coordinate
    // | x  y  z |
    // | vx vy 0 |
    // | ux uy 0 |
    // = z(vx*uy - vy*ux)
    int32_t min_bary0 = ((int64_t)(x2 - x1) * (y_min - y1) - (int64_t)(y2 - y1) * (x_min - x1)) >> 8;
    int32_t min_bary1 = ((int64_t)(x0 - x2) * (y_min - y2) - (int64_t)(y0 - y2) * (x_min - x2)) >> 8;
    int32_t min_bary2 = ((int64_t)(x1 - x0) * (y_min - y0) - (int64_t)(y1 - y0) * (x_min - x0)) >> 8;

    // derivative of barycentric coordinates in x and y
    int32_t dbary0dx = y1 - y2;
    int32_t dbary0dy = x2 - x1;
    int32_t dbary1dx = y2 - y0;
    int32_t dbary1dy = x0 - x2;
    int32_t dbary2dx = y0 - y1;
    int32_t dbary2dy = x1 - x0;

    // minimum/maximum pixel coordinates
    uint32_t x_min_px = x_min >> 8;
    uint32_t x_max_px = x_max >> 8;
    uint32_t y_min_px = y_min >> 8;
    uint32_t y_max_px = y_max >> 8;

    // these variables move forward with every y
    int32_t curr_bary0_row = min_bary0;
    int32_t curr_bary1_row = min_bary1;
    int32_t curr_bary2_row = min_bary2;
    uint32_t* curr_px_row = fb;

    // fill pixels inside the window coordinate bounding box that are inside all three edges' half-planes
    for (uint32_t y_px = y_min_px; y_px <= y_max_px; y_px++)
    {
        // these variables move forward with every x
        int32_t curr_bary0 = curr_bary0_row;
        int32_t curr_bary1 = curr_bary1_row;
        int32_t curr_bary2 = curr_bary2_row;
        uint32_t* curr_px = curr_px_row;

        // fill pixels in this row
        for (uint32_t x_px = x_min_px; x_px <= x_max_px; x_px++)
        {
            // TODO: Handle top-left rule
            if (curr_bary0 < 0 && curr_bary1 < 0 && curr_bary2 < 0)
            {
                *curr_px = 0xFFFFFF00;
            }

            // move to next pixel in x direction
            curr_px += 1;
            curr_bary0 += dbary0dx;
            curr_bary1 += dbary1dx;
            curr_bary2 += dbary2dx;
        }

        // move to the start of the next row
        curr_px_row += fb_width;
        curr_bary0_row += dbary0dy;
        curr_bary1_row += dbary1dy;
        curr_bary2_row += dbary2dy;
    }
}

int main()
{
    int fbwidth = 640;
    int fbheight = 480;

    uint32_t* fb = (uint32_t*)malloc(fbwidth * fbheight * sizeof(uint32_t));

    // fill with background color
    for (int i = 0; i < fbwidth * fbheight; i++)
    {
        fb[i] = 0x00000000;
    }

    // rasterize a triangle
    rasterize_triangle_fixed16_8(
        fb, fbwidth,
        0 << 8, 0 << 8, 0 << 8,
        0 << 8, 100 << 8, 0 << 8,
        100 << 8, 100 << 8, 0 << 8);

    // convert framebuffer from bgra to rgba for stbi_image_write
    for (int i = 0; i < fbwidth * fbheight; i++)
    {
        uint32_t src = fb[i];
        uint8_t* dst = (uint8_t*)fb + i * 4;
        dst[0] = (uint8_t)((src & 0x00FF0000) >> 16);
        dst[1] = (uint8_t)((src & 0x0000FF00) >> 8);
        dst[2] = (uint8_t)((src & 0x000000FF) >> 0);
        dst[3] = (uint8_t)((src & 0xFF000000) >> 24);
    }

    if (!stbi_write_png("output.png", fbwidth, fbheight, 4, fb, fbwidth * 4))
    {
        fprintf(stderr, "Failed to write image\n");
        exit(1);
    }

    system("output.png");

    free(fb);

    return 0;
}<commit_msg>handle top-left edges<commit_after>#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"

uint32_t g_Color;

void rasterize_triangle_fixed16_8(
    uint32_t* fb, uint32_t fb_width,
    uint32_t x0, uint32_t y0, uint32_t z0,
    uint32_t x1, uint32_t y1, uint32_t z1,
    uint32_t x2, uint32_t y2, uint32_t z2)
{
    // window coordinates' bounding box
    uint32_t x_min = x0, x_max = x0;
    if (x1 < x_min) x_min = x1;
    if (x2 < x_min) x_min = x2;
    if (x1 > x_max) x_max = x1;
    if (x2 > x_max) x_max = x2;

    uint32_t y_min = y0, y_max = y0;
    if (y1 < y_min) y_min = y1;
    if (y2 < y_min) y_min = y2;
    if (y1 > y_max) y_max = y1;
    if (y2 > y_max) y_max = y2;

    // barycentric coordinates of top left corner coordinate
    // | x  y  z |
    // | vx vy 0 |
    // | ux uy 0 |
    // = z(vx*uy - vy*ux)
    int32_t min_bary0 = ((int64_t)(x2 - x1) * (y_min - y1) - (int64_t)(y2 - y1) * (x_min - x1)) >> 8;
    int32_t min_bary1 = ((int64_t)(x0 - x2) * (y_min - y2) - (int64_t)(y0 - y2) * (x_min - x2)) >> 8;
    int32_t min_bary2 = ((int64_t)(x1 - x0) * (y_min - y0) - (int64_t)(y1 - y0) * (x_min - x0)) >> 8;

    // offset barycentrics of non top-left edges, which ever so slightly removes them from the rasterization
    if ((y1 != y2 || x1 > x2) && (y1 < y2)) min_bary0 -= 1;
    if ((y2 != y0 || x2 > x0) && (y2 < y0)) min_bary1 -= 1;
    if ((y0 != y1 || x0 > x1) && (y0 < y1)) min_bary2 -= 1;

    // derivative of barycentric coordinates in x and y
    int32_t dbary0dx = y1 - y2;
    int32_t dbary0dy = x2 - x1;
    int32_t dbary1dx = y2 - y0;
    int32_t dbary1dy = x0 - x2;
    int32_t dbary2dx = y0 - y1;
    int32_t dbary2dy = x1 - x0;

    // minimum/maximum pixel center coordinates (center sample locations)
    uint32_t x_min_center = (x_min & 0xFFFFFF00) | 0x7F;
    uint32_t x_max_center = (x_max & 0xFFFFFF00) | 0x7F;
    uint32_t y_min_center = (y_min & 0xFFFFFF00) | 0x7F;
    uint32_t y_max_center = (y_max & 0xFFFFFF00) | 0x7F;

    // these variables move forward with every y
    int32_t curr_bary0_row = min_bary0;
    int32_t curr_bary1_row = min_bary1;
    int32_t curr_bary2_row = min_bary2;
    uint32_t* curr_px_row = fb;

    // fill pixels inside the window coordinate bounding box that are inside all three edges' half-planes
    for (uint32_t y_px = y_min_center; y_px <= y_max_center; y_px += 0x100)
    {
        // these variables move forward with every x
        int32_t curr_bary0 = curr_bary0_row;
        int32_t curr_bary1 = curr_bary1_row;
        int32_t curr_bary2 = curr_bary2_row;
        uint32_t* curr_px = curr_px_row;

        // fill pixels in this row
        for (uint32_t x_px = x_min_center; x_px <= x_max_center; x_px += 0x100)
        {
            if (curr_bary0 >= 0 && curr_bary1 >= 0 && curr_bary2 >= 0)
            {
                *curr_px += g_Color;
            }

            // move to next pixel in x direction
            curr_bary0 += dbary0dx;
            curr_bary1 += dbary1dx;
            curr_bary2 += dbary2dx;
            curr_px += 1;
        }

        // move to the start of the next row
        curr_bary0_row += dbary0dy;
        curr_bary1_row += dbary1dy;
        curr_bary2_row += dbary2dy;
        curr_px_row += fb_width;
    }
}

int main()
{
    int fbwidth = 256;
    int fbheight = 256;

    uint32_t* fb = (uint32_t*)malloc(fbwidth * fbheight * sizeof(uint32_t));

    // fill with background color
    for (int i = 0; i < fbwidth * fbheight; i++)
    {
        fb[i] = 0x00000000;
    }

    // rasterize triangles
    g_Color = 0xFFFFFF00;
    rasterize_triangle_fixed16_8(
        fb, fbwidth,
        0 << 8, 0 << 8, 0,
        100 << 8, 100 << 8, 0,
        0 << 8, 100 << 8, 0);

    g_Color = 0xFFFF00FF;
    rasterize_triangle_fixed16_8(
        fb, fbwidth,
        0 << 8, 0 << 8, 0,
        100 << 8, 0 << 8, 0,
        100 << 8, 100 << 8, 0);

    // convert framebuffer from bgra to rgba for stbi_image_write
    for (int i = 0; i < fbwidth * fbheight; i++)
    {
        uint32_t src = fb[i];
        uint8_t* dst = (uint8_t*)fb + i * 4;
        dst[0] = (uint8_t)((src & 0x00FF0000) >> 16);
        dst[1] = (uint8_t)((src & 0x0000FF00) >> 8);
        dst[2] = (uint8_t)((src & 0x000000FF) >> 0);
        dst[3] = (uint8_t)((src & 0xFF000000) >> 24);
    }

    if (!stbi_write_png("output.png", fbwidth, fbheight, 4, fb, fbwidth * 4))
    {
        fprintf(stderr, "Failed to write image\n");
        exit(1);
    }

    system("output.png");

    free(fb);

    return 0;
}<|endoftext|>