Exemplo n.º 1
0
 ImageDataBase(const Dim& dim, const Point& offset) {
   m_size = (dim.nrows() * dim.ncols());
   m_stride = dim.ncols();
   m_page_offset_x = offset.x();
   m_page_offset_y = offset.y();
   m_user_data = 0;
 }
Exemplo n.º 2
0
void TestDim::index() {
	Dim sca;
	Dim row2(Dim::row_vec(2));
	Dim row3(Dim::row_vec(3));
	Dim col2(Dim::col_vec(2));
	Dim col3(Dim::col_vec(3));
	Dim mat22(Dim::matrix(2,2));
	Dim mat32(Dim::matrix(3,2));
	Dim mat23(Dim::matrix(2,3));
	Dim mat33(Dim::matrix(3,3));

	CPPUNIT_ASSERT      (sca.index_dim(DoubleIndex::one_elt(sca,0,0))==sca);

	CPPUNIT_ASSERT      (row3.index_dim(DoubleIndex::one_elt(row3,0,0))==sca);
	CPPUNIT_ASSERT      (row3.index_dim(DoubleIndex::one_row(row3,0))==row3);
	CPPUNIT_ASSERT      (row3.index_dim(DoubleIndex::cols(row3,0,1))==row2);

	CPPUNIT_ASSERT      (col3.index_dim(DoubleIndex::one_elt(col3,0,0))==sca);
	CPPUNIT_ASSERT      (col3.index_dim(DoubleIndex::one_col(col3,0))==col3);
	CPPUNIT_ASSERT      (col3.index_dim(DoubleIndex::rows(col3,0,1))==col2);

	CPPUNIT_ASSERT      (mat23.index_dim(DoubleIndex::one_elt(mat23,0,0))==sca);
	CPPUNIT_ASSERT      (mat23.index_dim(DoubleIndex::one_row(mat23,0))==row3);
	CPPUNIT_ASSERT      (mat23.index_dim(DoubleIndex::one_col(mat23,0))==col2);
	CPPUNIT_ASSERT      (mat23.index_dim(DoubleIndex::cols(mat23,0,1))==mat22);
	CPPUNIT_ASSERT      (mat23.index_dim(DoubleIndex::subrow(mat23,0,0,1))==row2);
	CPPUNIT_ASSERT      (mat23.index_dim(DoubleIndex::all(mat23))==mat23);

	CPPUNIT_ASSERT      (mat32.index_dim(DoubleIndex::subcol(mat32,0,1,0))==col2);

	CPPUNIT_ASSERT      (mat33.index_dim(DoubleIndex::rows(mat33,0,1))==mat23);
	CPPUNIT_ASSERT      (mat33.index_dim(DoubleIndex::cols(mat33,0,1))==mat32);
}
Exemplo n.º 3
0
Arquivo: xetp.cpp Projeto: toppk/xevil
void XETP::send_world_room(OutStreamP out,WorldP world,
                           const RoomIndex &idx,int worldVersion) {
  u_int len = sizeof(int) +             // version
    Rooms::get_write_length() +       // rooms
    RoomIndex::get_write_length() +   // roomIndex
    Dim::get_write_length() +         // dim
    world->get_write_length(idx);     // world room data

  if (out->get_protocol() == GenericStream::UDP) {
    ((UDPOutStreamP)out)->prepare_packet(XETP::add_header(len));
  }

  send_header(out,WORLD_ROOM,len);
  out->write_int(worldVersion);
  Rooms rooms = world->get_rooms();
  rooms.write(out);
  idx.write(out);
  Dim dim = world->get_dim();
  dim.write(out);
  world->write(out,idx); // write one room

  if (out->get_protocol() == GenericStream::UDP) {
    ((UDPOutStreamP)out)->done_packet();
  }
}
Exemplo n.º 4
0
void utl::ProfilePass::run()
{
	//size_t j = 0;

	auto compare = _countUp ?
				[](const Dim& lhs, const Dim& rhs){ return (lhs < 1) == 0 && lhs <= rhs; } :
	[](const Dim& lhs, const Dim& rhs){ return (lhs < 1) == 0 && lhs >= rhs; };

	auto advance = _countUp ?
				[](Dim& lhs, const Dim& rhs){ lhs += rhs; } :
	[](Dim& lhs, const Dim& rhs){ lhs -= rhs; } ;

	for(Dim i = _start; compare(i, _end); advance(i,_step))
	{
		//			TRUE_COMMENT("start : " << this->_start.toString() << ", _end : " << this->_end.toString() << ", _step = " << this->_step.toString() << ", i " << i.toString() << ", comp = "  << compare(i,_end));

		Seconds time = this->prof(i);
		double op = this->ops(i);
		double perf = double(op)  / double(time.count());

		this->_elems.push_back(i.prod());
		this->_times.push_back(time) ;
		this->_ops.push_back(op) ; // 2 * n^2 + n
		this->_perf.push_back(perf);
	}

}
Exemplo n.º 5
0
 ImageDataBase(const Dim& dim) {
   m_size = (dim.nrows() * dim.ncols());
   m_stride = dim.ncols();
   m_page_offset_x = 0;
   m_page_offset_y = 0;
   m_user_data = 0;
 }
Exemplo n.º 6
0
Texture::Texture(const Dim& dim, const int samples, const GLenum iformat, const GLenum format, const GLenum type)
	: size(dim), samples(samples), iformat(iformat), format(format), type(type)
{
	assert(samples > 0);
	assert(samples == 1 || (dim.GetHeight() >= 1 && dim.GetDepth() == 1));

	InitResource(0, false, nullptr);
}
Exemplo n.º 7
0
void bi::ParticleMCMCNetCDFBuffer::map(const long P, const long T) {
  std::string name;
  int id, i;
  VarType type;
  Var* var;
  Dim* dim;

  /* dimensions */
  BI_ERROR_MSG(hasDim("nr"), "File must have nr dimension");
  nrDim = mapDim("nr", T);
  for (i = 0; i < m.getNumDims(); ++i) {
    dim = m.getDim(i);
    BI_ERROR_MSG(hasDim(dim->getName().c_str()), "File must have " <<
        dim->getName() << " dimension");
    nDims.push_back(mapDim(dim->getName().c_str(), dim->getSize()));
  }
  BI_ERROR_MSG(hasDim("np"), "File must have np dimension");
  npDim = mapDim("np", P);

  /* time variable */
  tVar = ncFile->get_var("time");
  BI_ERROR_MSG(tVar != NULL && tVar->is_valid(),
      "File does not contain variable time");
  BI_ERROR_MSG(tVar->num_dims() == 1, "Variable time has " << tVar->num_dims() <<
      " dimensions, should have 1");
  BI_ERROR_MSG(tVar->get_dim(0) == nrDim, "Dimension 0 of variable time should be nr");

  /* other variables */
  for (i = 0; i < NUM_VAR_TYPES; ++i) {
    type = static_cast<VarType>(i);
    if (type == D_VAR || type == R_VAR || type == P_VAR) {
      vars[type].resize(m.getNumVars(type), NULL);
      for (id = 0; id < m.getNumVars(type); ++id) {
        var = m.getVar(type, id);
        if (hasVar(var->getOutputName().c_str())) {
          vars[type][id] = mapVar(m.getVar(type, id));
        }
      }
    }
  }

  llVar = ncFile->get_var("loglikelihood");
  BI_ERROR_MSG(llVar != NULL && llVar->is_valid(),
      "File does not contain variable loglikelihood");
  BI_ERROR_MSG(llVar->num_dims() == 1, "Variable loglikelihood has " <<
      llVar->num_dims() << " dimensions, should have 1");
  BI_ERROR_MSG(llVar->get_dim(0) == npDim,
      "Dimension 0 of variable loglikelihood should be np");

  lpVar = ncFile->get_var("logprior");
  BI_ERROR_MSG(lpVar != NULL && lpVar->is_valid(),
      "File does not contain variable logprior");
  BI_ERROR_MSG(lpVar->num_dims() == 1, "Variable logprior has " <<
      lpVar->num_dims() << " dimensions, should have 1");
  BI_ERROR_MSG(lpVar->get_dim(0) == npDim,
      "Dimension 0 of variable logprior should be np");

}
Exemplo n.º 8
0
Texture::Texture(const Dim& dim, const int samples, const GLenum autoformat)
	: size(dim), samples(samples), iformat(autoformat)
{
	assert(samples > 0);
	assert(samples == 1 || (dim.GetHeight() >= 1 && dim.GetDepth() == 1));

	assert(DetectFormat());
	InitResource(0, false, nullptr);
}
Exemplo n.º 9
0
void TestDim::test01() {
	Dim d;
	TEST_ASSERT(d.dim1==1);
	TEST_ASSERT(d.dim2==1);
	TEST_ASSERT(d.dim3==1);
	TEST_ASSERT(d==Dim::scalar());
	TEST_ASSERT(d.is_scalar());
	TEST_ASSERT(d.type()==Dim::SCALAR);
	TEST_ASSERT(Dim(d)==d);
	TEST_ASSERT((Dim::scalar()=d)==d);

}
Exemplo n.º 10
0
TDV_NAMESPACE_BEGIN

Dim Dim::minDim(const Dim &d1, const Dim &d2)
{
    size_t dm[3] = {0, 0, 0};
    const size_t N = std::min(d1.N(), d2.N());
    for (size_t i=0; i<N; i++)
    {
        dm[i] = std::min(d1.dim[i], d2.dim[i]);
    }
    
    return Dim(dm, N);
}
Exemplo n.º 11
0
void bi::ParticleMCMCNetCDFBuffer::create(const long P, const long T) {
  int id, i;
  VarType type;
  Var* var;
  Dim* dim;

  ncFile->add_att(PACKAGE_TARNAME "_schema", "ParticleMCMC");
  ncFile->add_att(PACKAGE_TARNAME "_schema_version", 1);
  ncFile->add_att(PACKAGE_TARNAME "_version", PACKAGE_VERSION);

  /* dimensions */
  nrDim = createDim("nr", T);
  for (i = 0; i < m.getNumDims(); ++i) {
    dim = m.getDim(i);
    nDims.push_back(createDim(dim->getName().c_str(), dim->getSize()));
  }
  npDim = createDim("np", P);

  /* time variable */
  tVar = ncFile->add_var("time", netcdf_real, nrDim);
  BI_ERROR_MSG(tVar != NULL && tVar->is_valid(), "Could not create time variable");

  /* other variables */
  for (i = 0; i < NUM_VAR_TYPES; ++i) {
    type = static_cast<VarType>(i);
    vars[type].resize(m.getNumVars(type), NULL);

    if (type == D_VAR || type == R_VAR || type == P_VAR) {
      for (id = 0; id < (int)vars[type].size(); ++id) {
        var = m.getVar(type, id);
        if (var->hasOutput()) {
          if (type == P_VAR) {
            vars[type][id] = createVar(var, false, true);
          } else {
            vars[type][id] = createVar(var, !var->getOutputOnce(), true);
          }
        }
      }
    }
  }

  llVar = ncFile->add_var("loglikelihood", netcdf_real, npDim);
  BI_ERROR_MSG(llVar != NULL && llVar->is_valid(),
      "Could not create loglikelihood variable");

  lpVar = ncFile->add_var("logprior", netcdf_real, npDim);
  BI_ERROR_MSG(lpVar != NULL && lpVar->is_valid(),
      "Could not create logprior variable");

}
Exemplo n.º 12
0
Dim mul_dim(const Dim& l, const Dim& r) {
	if (l.dim1!=1 || r.dim1!=1)
		throw DimException("cannot multiply a matrix array");

	if (l.type()==Dim::SCALAR) // scalar multiplication.
		return r;
	else {
		if (l.dim3!=r.dim2) {
			if (l.dim2==r.dim2) {
				if (r.dim3==1) // dot product
					return Dim::scalar();
				else // vector-matrix product
					return Dim::row_vec(r.dim3);
			}
			throw DimException("mismatched dimensions in matrix multiplication");
		} else {
			if (l.dim2==1)
				if (r.dim3==1) return Dim::scalar();
				else return Dim::row_vec(r.dim3);
			else
				if (r.dim3==1) return Dim::col_vec(l.dim2);
				else return Dim::matrix(l.dim2,r.dim3);
		}
	}
}
Exemplo n.º 13
0
void GridGLMesh::resize(const Dim &dim)
{
    if ( m_dim != dim )
    {
        m_dim = dim;
        m_vertices.bind(GL_ARRAY_BUFFER, GL_STREAM_DRAW, 
                        dim.size()*sizeof(ud::Vec3f));
        m_colors.bind(GL_ARRAY_BUFFER, GL_STREAM_DRAW, 
                      dim.size()*sizeof(ud::Vec3f));
        m_indices.bind(GL_ELEMENT_ARRAY_BUFFER, GL_STREAM_DRAW, 
                       (dim.height()*2*(dim.width() - 1))*sizeof(GLuint));
        
        GLuint *indices = m_indices.map<GLuint>();
        GLuint count = 0;
        for (size_t c=0; c<dim.width() - 1; c++)
        {
            for (size_t r=0; r<dim.height(); r++)
            {
                indices[count++] = r*dim.width() + c;
                indices[count++] = r*dim.width() + c + 1;
            }
        }
        m_indices.unmap();
    }
}
Exemplo n.º 14
0
void Texture::Generate(const Dim& dim, std::function<vec4(unsigned int, unsigned int)> generator, const GLenum type)
{
	ILuint image;
	ilGenImages(1, &image);
	ilBindImage(image);

	const unsigned int numBytes = dim.GetWidth() * dim.GetHeight();
	vec4* pixels = new vec4[numBytes];
	for(unsigned int y=0; y<dim.GetHeight(); y++) {
		for(unsigned int x=0; x<dim.GetWidth(); x++) {
			pixels[y*dim.GetWidth() + x] = generator(x, y);
		}
	}
	ilTexImage(dim.GetWidth(), dim.GetHeight(), 1, 4, IL_RGBA, IL_FLOAT, reinterpret_cast<void*>(pixels));
	delete[] pixels;

	if(type == GL_UNSIGNED_BYTE) {
		this->iformat = GL_RGBA8;
		this->type    = GL_UNSIGNED_BYTE;
		ilConvertImage(IL_RGBA, IL_UNSIGNED_BYTE);
	}
	else {
		this->iformat = GL_RGBA32F;
		this->type    = GL_FLOAT;
	}
	this->format = GL_RGBA;

	size.Width  = ilGetInteger(IL_IMAGE_WIDTH);
	size.Height = ilGetInteger(IL_IMAGE_HEIGHT);
	size.Depth  = ilGetInteger(IL_IMAGE_DEPTH);

	InitResource(4, false, ilGetData());
	ilDeleteImages(1, &image);
}
Exemplo n.º 15
0
void TestDim::scalar() {
	Dim d;
	CPPUNIT_ASSERT(d.nb_rows()==1);
	CPPUNIT_ASSERT(d.nb_cols()==1);
	CPPUNIT_ASSERT(d.size()==1);
	CPPUNIT_ASSERT(d==Dim::scalar());
	CPPUNIT_ASSERT(d.is_scalar());
	CPPUNIT_ASSERT(!d.is_vector());
	CPPUNIT_ASSERT(!d.is_matrix());
	CPPUNIT_ASSERT(d.type()==Dim::SCALAR);
	CPPUNIT_ASSERT(Dim(d)==d);
	CPPUNIT_ASSERT((Dim::scalar()=d)==d);

}
Exemplo n.º 16
0
void    ZoomAnimation::OnRender()
{
    std::auto_ptr<Surface> pSurface( getSurface()->ZoomSurface( m_curZoom ) );
    if(pSurface.get() == 0) {
    	return;
    }

    Dim destDim = pSurface->GetDim();
    Dim srcDim = getSurface()->GetDim();
    Coord srcCoord = getCoord();
    
    // 그림이 확대, 축소되면 이미지 위치로 확대 축소된 값에 따라 변한다.
    int x = srcCoord.getX() + (srcDim.getW() - destDim.getW() ) / 2;
    int y = srcCoord.getY() + (srcDim.getH() - destDim.getH() ) / 2;
    
    pSurface->SetColorKey();
    pSurface->Blit( x, y );
    pSurface->Free();
}
Exemplo n.º 17
0
 virtual void dim(const Dim& dim) {
   m_stride = dim.ncols(); do_resize(dim.nrows() * dim.ncols()); }
Exemplo n.º 18
0
std::pair<int,int> bi::InputNetCDFBuffer::mapVarDim(const Var* var) {
  /* pre-condition */
  BI_ASSERT(var != NULL);

  const VarType type = var->getType();
  Dim* dim;
  int ncVar, ncDim, i, j = 0, k = -1;
  std::vector<int> dimids;
  BI_UNUSED bool canHaveTime, canHaveP;

  canHaveTime = type == D_VAR || type == R_VAR || type == F_VAR
      || type == O_VAR;

  ncVar = nc_inq_varid(ncid, var->getInputName());
  if (ncVar >= 0) {
    dimids = nc_inq_vardimid(ncid, ncVar);

    /* check for ns-dimension */
    if (nsDim >= 0 && j < static_cast<int>(dimids.size())
        && dimids[j] == nsDim) {
      ++j;
    }

    /* check for record dimension */
    if (j < static_cast<int>(dimids.size())) {
      BOOST_AUTO(iter, std::find(recDims.begin(), recDims.end(), dimids[j]));
      if (iter != recDims.end()) {
        k = std::distance(recDims.begin(), iter);
        ++j;
      }
    }

    /* check for np-dimension */
    if (npDim >= 0 && j < static_cast<int>(dimids.size())
        && dimids[j] == npDim) {
      ++j;
    } else if (j < static_cast<int>(dimids.size())) {
      /* check for model dimensions */
      for (i = var->getNumDims() - 1;
          i >= 0 && j < static_cast<int>(dimids.size()); --i, ++j) {
        dim = var->getDim(i);
        ncDim = dimids[j];

        BI_ERROR_MSG(dim->getName().compare(nc_inq_dimname(ncid, ncDim)) == 0,
            "Dimension " << j << " of variable " << var->getName() << " should be " << dim->getName() << " not " << nc_inq_dimname(ncid, ncDim) << ", in file " << file);
        BI_ERROR_MSG(k < 0 || coordVars[k] < 0,
            "Variable " << nc_inq_varname(ncid, ncVar) << " has both dense and sparse definitions, in file " << file);
      }
      BI_ERROR_MSG(i == -1,
          "Variable " << nc_inq_varname(ncid, ncVar) << " is missing one or more dimensions, in file " << file);

      /* check again for np dimension */
      if (npDim >= 0 && j < static_cast<int>(dimids.size())
          && dimids[j] == npDim) {
        ++j;
      }
    }
    BI_ERROR_MSG(j == static_cast<int>(dimids.size()),
        "Variable " << nc_inq_varname(ncid, ncVar) << " has extra dimensions, in file " << file);
  }

  return std::make_pair(k, ncVar);
}
Exemplo n.º 19
0
int main(int argc, char *args[]) {
	HANDLE hCon = GetStdHandle(STD_OUTPUT_HANDLE);
	CONSOLE_SCREEN_BUFFER_INFO conInfo;
	GetConsoleScreenBufferInfo(hCon, &conInfo);
	int screenChars = (conInfo.srWindow.Bottom + 1) * (conInfo.srWindow.Right + 1);

	bool paused = false;

    // Data for testing (load from png)
    //auto testData = getTestPng("normalTestImg");

    // Buffered output
    stringstream log;
    stringstream message;

    // Projector stats
    const float projectorFovY = 27.5f;
    const float projectorFovX = 48.9f;
    const Dim projectorDim = { 845, 480 };

    try
    {
        // Kinect and main window
        KinectDevice kinect;
        GLWindow dispWindow, projectorWindow;

        // Initialize the gui and kinect
        GLWindow::InitGUI();
        kinect.connect(kinect.DEPTH_STREAM);

        int frame_w = kinect.depthFrameInfo.w;
        int frame_h = kinect.depthFrameInfo.h;

        Dim fullSize = { frame_w, frame_h };
        Dim window = { 1280, 720 };

        // Current tracking point
        Pt2i centre = { fullSize.width / 2, fullSize.height / 2 };
        Pt2i trackPt = centre;

        // Create the GL contexts for separate windows (displaying the windows)
        dispWindow.showWindow("Kinecting - freelook", window);
        projectorWindow.showWindow("Kinecting - projector", window);
        projectorWindow.nextMonitor();
        projectorWindow.setFullscreen(true);

        // Setup on free-look context (camera)
        dispWindow.activate();
		auto &scene = dispWindow.scene;
		scene.camera.set(false, window, 60.0f);
        scene.readCameraSettings("camera.cfg");
        //

        // Setup on projector context (camera)
        // Note the offset viewport, important for the short-throw projector
        projectorWindow.activate();
        auto &projScene = projectorWindow.scene;
        projScene.camera.set(true, window, projectorFovY);
        projScene.readCameraSettings("projector.cfg");
        //

		// Storage for raw camera output
		auto rawData = unique_ptr<uint16_t>(new uint16_t[fullSize.area()]);
		auto floatData = unique_ptr<float>(new float[fullSize.area()]);

        // Image processing platform
        NormDepthImage img(fullSize);


        // Generate the main window's objects *****
        dispWindow.activate();
		
        // -- Kinect frustrum
        auto kinectFrustrum = scene.newObject("solidcolor.glsl", "object_vert.glsl");
        kinectFrustrum->genFrustrum(0.5f, 4.5f, { kinect.depthFrameInfo.xFov, kinect.depthFrameInfo.yFov });

        // -- Projector frustrum
        auto projFrustrum = scene.newObject("solidcolor.glsl", "object_vert.glsl");
        projFrustrum->genFrustrum(0.0f, 4.0f, { projectorFovX, projectorFovY }, Colors::red, true);

		//--  Camera output surface
		auto surf = scene.newObject("rgb_frag.glsl", "normal_vertex.glsl");
		surf->renderMode = GLObject::RenderMode::POINTS;
		surf->genQuad(fullSize);
        surf->pointSize = 2.0f;
		
		Texture normalTex, depthTex;
		normalTex.init(Texture::BGR, fullSize);
		depthTex.init(Texture::DEPTH_FLOAT, fullSize);

		surf->shaders.bindTexture(normalTex, "UInputImg");
		surf->shaders.bindTexture(depthTex, "UInputDepth");

		// -- Cube (test)
		auto obj = scene.newObject("object_frag.glsl", "object_vert.glsl");
		obj->genCuboid(0.1f, 0.1f, 0.1f);
        //obj->hide();

        // -- Tracking line
        auto trackLine0 = scene.newObject("solidcolor.glsl", "object_vert.glsl");
        trackLine0->renderMode = GLObject::RenderMode::LINE_STRIP;
		auto trackLine1 = scene.newObject("solidcolor.glsl", "object_vert.glsl");
		trackLine1->renderMode = GLObject::RenderMode::LINE_STRIP;
		auto trackLine2 = scene.newObject("solidcolor.glsl", "object_vert.glsl");
		trackLine2->renderMode = GLObject::RenderMode::LINE_STRIP;

		// -- Tracked cloud
		PointCloud pointCloud;
		auto frangibleCloud = scene.newObject("solidcolor.glsl", "object_vert.glsl");
		frangibleCloud->renderMode = GLObject::RenderMode::POINTS;
		frangibleCloud->pointSize = 3.0f;

		// TEMP
		// hide surface
		//surf->hide();


        // Generate the projector window's objects ****
        projectorWindow.activate();

        // -- Tracked cloud
        auto baseCloud = projScene.newObject("solidcolor.glsl", "object_vert.glsl");
        baseCloud->renderMode = GLObject::RenderMode::POINTS;
        baseCloud->pointSize = 2.0f;

        //--  Second depth/normals output surface
        auto surf2 = projScene.newObject("rgb_frag.glsl", "normal_vertex.glsl");
        surf2->renderMode = GLObject::RenderMode::POINTS;
        surf2->genQuad(fullSize);

        Texture normalTex2, depthTex2;
        normalTex2.init(Texture::BGR, fullSize);
        depthTex2.init(Texture::DEPTH_FLOAT, fullSize);

        surf2->shaders.bindTexture(normalTex2, "UInputImg");
        surf2->shaders.bindTexture(depthTex2, "UInputDepth");


        // Begin reading in frames...
        kinect.asyncListen();
        // ... and run the main loop
        SDL_Event e;
        bool quit = false;
        while (!quit) {
            while (SDL_PollEvent(&e) != 0) {
                // Handle all waiting events
                projectorWindow.handleEvent(e);
                dispWindow.handleEvent(e);

                // General (shared) application control
                if (e.type == SDL_KEYDOWN) {
                    switch (e.key.keysym.scancode) {
                        // Tracking reset
                    case SDL_SCANCODE_R:
                        trackPt = centre;
                        break;

                        // Pause
                    case SDL_SCANCODE_P:
                        paused = !paused;
                        if (paused) {
                            message.str("Paused");
                        }
                        else {
                            message.str("Running");
                        }
                        break;

                        // Cloud save/load
                    case SDL_SCANCODE_RETURN:
                        pointCloud.saveToFile("cloud.txt");
                        message.str("Saved pointcloud to 'cloud.txt'");
                        break;
                    case SDL_SCANCODE_O:
                        pointCloud.loadFromFile("cloud.txt");
                        paused = true;
                        message.str("Loaded pointcloud 'cloud.txt'");
                        break;
                    }
                }

                // Closing either window quits the application
                if (e.type == SDL_QUIT || (e.type == SDL_WINDOWEVENT && e.window.event == SDL_WINDOWEVENT_CLOSE)) {
                    quit = true;
                }
            }


            {
                // Exception-proof lock for depth read
				lock_guard<decltype(kinect.frameLock)> lck(kinect.frameLock);
                memcpy(rawData.get(), kinect.depthData.get(), fullSize.area()*sizeof(uint16_t));
            }
            
            // Processing on active incoming stream
			if (!paused) {
				// Convert depth to float-32 (and mm to m)
				const int count = frame_w * frame_h;
				auto fd = floatData.get();
				auto rd = rawData.get();

				for (int i = 0; i < count; i++) {
					fd[i] = float(rd[i]) / 1.0f;
				}

				// Pass to image processor and gui
				img.setDepth(floatData.get());

                projectorWindow.activate();
                depthTex2.setImage(floatData.get());

				dispWindow.activate();
				depthTex.setImage(floatData.get());

				// **************************************************
				// *** Image Processing

				// Smooth depth
				//img.threshold_meanDepthBlur(4, 0.001f);

				// Smooth and flood-fill the normals
				img.calcNormals(kinectXZ, kinectYZ);
				img.OPT_threshold_gaussNormalBlur(12, 0.8f, 0.01f);
				img.threshold_normalFlood(trackPt, 0.1f, 0.01f);

                // Now we can generate the stress map and normals
                img.masked_holeFill();
                img.masked_laplaceSmooth(30); // heavy smoothing
                img.masked_stressMap();
                pointCloud.generateFromImage(img, kinectXZ, kinectYZ);
                //pointCloud.innerEdge();
			}

            // Display the point cloud (convert to object mesh data)
			frangibleCloud->genPointCloud(pointCloud);
            baseCloud->genPointCloud(Colors::white, pointCloud);

            // Tracking
            auto medPos = pointCloud.medianPoint();
            trackPt.x = int(medPos.screen.x); trackPt.y = int(medPos.screen.y);
            trackLine0->genLine(medPos.pos, vec3(0));
            obj->setPosition(medPos.pos);

            // Pull out a formatted uint32 image
            auto pixels = img.getFormattedImg();

			// Principal component analysis
			if (pointCloud.cloud.size() > 100) {
                mat3 pcaMat = pca(pointCloud);

                vec3 pos = pointCloud.meanPosition();
                trackLine0->genLine(pos, pos + pcaMat[0], Colors::red);
                trackLine1->genLine(pos, pos + pcaMat[1], Colors::green);
                trackLine2->genLine(pos, pos + pcaMat[2], Colors::blue);

                // Transform frangible cloud into calculated local space
                auto invMeanPos = translate(mat4(), -pointCloud.meanPosition());
                frangibleCloud->applyTransform(invMeanPos);
                frangibleCloud->applyTransform(inverse(pcaMat));
			}


            // Text display
            scene.getTextOverlay()->drawText({ 20, 20 }, message.str());

            // Projector frustrum
            projFrustrum->setPosition(projScene.camera.eye);
            projFrustrum->setRotation(vec3(projScene.camera.angle.y, 0.0f, M_PI/2 - projScene.camera.angle.x));

            // Display
            // TODO: change
            GLObject::projectorVP = projScene.camera.calcProjection() * projScene.camera.calcView();
			normalTex.setImage(pixels.get());
            dispWindow.render();

            // Projector display
            projectorWindow.activate();
            normalTex2.setImage(pixels.get());
            projectorWindow.render();
        }
    }
    catch (exception e) {
        SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Runtime error", e.what(), nullptr);
    }
	catch (char* e) {
		SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Runtime error", e, nullptr);
	}
	catch (string e) {
		SDL_ShowSimpleMessageBox(SDL_MESSAGEBOX_ERROR, "Runtime error", e.c_str(), nullptr);
	}

    // Explicit cleanup (mainly for SDL subsystems)
    GLWindow::ReleaseGUI();
	#ifdef _DEBUG
		_CrtDumpMemoryLeaks();
	#endif
    return 0;
}