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

#include <htool/cluster.hpp>
#include <htool/lrmat.hpp>
#include <htool/partialACA.hpp>

using namespace std;
using namespace htool;

class MyMatrix: public IMatrix<double>{
	const vector<R3>& p1;
	const vector<R3>& p2;

public:
	MyMatrix(const vector<R3>& p10,const vector<R3>& p20 ):IMatrix<double>(p10.size(),p20.size()),p1(p10),p2(p20) {}
	 double get_coef(const int& i, const int& j)const {return 1./(4*M_PI*norm2(p1[i]-p2[j]));}
	 std::vector<double> operator*(std::vector<double> a){
		std::vector<double> result(p1.size(),0);
		for (int i=0;i<p1.size();i++){
			for (int k=0;k<p2.size();k++){
				result[i]+=this->get_coef(i,k)*a[k];
			}
		}
		return result;
	 }
};

int main(){
	const int ndistance = 4;
	double distance[ndistance];
	distance[0] = 10; distance[1] = 20; distance[2] = 30; distance[3] = 40;
	SetNdofPerElt(1);
	bool test = 0;
	for(int idist=0; idist<ndistance; idist++)
	{
		cout << "Distance between the clusters: " << distance[idist] << endl;
		SetEpsilon(0.0001);
		srand (1);
		// we set a constant seed for rand because we want always the same result if we run the check many times
		// (two different initializations with the same seed will generate the same succession of results in the subsequent calls to rand)

		int nr = 500;
		int nc = 100;
		vector<int> Ir(nr); // row indices for the lrmatrix
		vector<int> Ic(nc); // column indices for the lrmatrix

		double z1 = 1;
		vector<R3>     p1(nr);
		vector<int>  tab1(nr);
		for(int j=0; j<nr; j++){
			Ir[j] = j;
			double rho = ((double) rand() / (double)(RAND_MAX)); // (double) otherwise integer division!
			double theta = ((double) rand() / (double)(RAND_MAX));
			p1[j][0] = sqrt(rho)*cos(2*M_PI*theta); p1[j][1] = sqrt(rho)*sin(2*M_PI*theta); p1[j][2] = z1;
			// sqrt(rho) otherwise the points would be concentrated in the center of the disk
			tab1[j]=j;
		}
		// p2: points in a unit disk of the plane z=z2
		double z2 = 1+distance[idist];
		vector<R3> p2(nc);
		vector<int> tab2(nc);
		for(int j=0; j<nc; j++){
            Ic[j] = j;
			double rho = ((double) rand() / (RAND_MAX)); // (double) otherwise integer division!
			double theta = ((double) rand() / (RAND_MAX));
			p2[j][0] = sqrt(rho)*cos(2*M_PI*theta); p2[j][1] = sqrt(rho)*sin(2*M_PI*theta); p2[j][2] = z2;
			tab2[j]=j;
		}

		Cluster t(p1,tab1); Cluster s(p2,tab2);
		MyMatrix A(p1,p2);

		// ACA with fixed rank
		int reqrank_max = 10;
		partialACA<double> A_partialACA_fixed(Ir,Ic,reqrank_max);
		A_partialACA_fixed.build(A,t,s);
		std::vector<double> partialACA_fixed_errors;
		for (int k = 0 ; k < A_partialACA_fixed.rank_of()+1 ; k++){
			partialACA_fixed_errors.push_back(Frobenius_absolute_error(A_partialACA_fixed,A,k));
		}

		cout << "Partial ACA with fixed rank" << endl;
		// Test rank
		cout << "rank : "<<A_partialACA_fixed.rank_of() << endl;
		test = test || !(A_partialACA_fixed.rank_of()==reqrank_max);

		// Test Frobenius errors
		test = test || !(partialACA_fixed_errors[partialACA_fixed_errors.size()-1]<1e-6);
		cout << "Errors with Frobenius norm : "<<partialACA_fixed_errors<<endl;

		// Test compression
		test = test || !(0.87<A_partialACA_fixed.compression() && A_partialACA_fixed.compression()<0.89);
		cout << "Compression rate : "<<A_partialACA_fixed.compression()<<endl;

		// Test mat vec prod
		std::vector<double> f(nc,1);
		double error=norm2(A*f-A_partialACA_fixed*f);
		test = test || !(error<1e-6);
		cout << "Errors on a mat vec prod : "<< error<<endl<<endl;

		// ACA automatic building
		partialACA<double> A_partialACA(Ir,Ic);
		A_partialACA.build(A,t,s);
		std::vector<double> partialACA_errors;
		for (int k = 0 ; k < A_partialACA.rank_of()+1 ; k++){
			partialACA_errors.push_back(Frobenius_absolute_error(A_partialACA,A,k));
		}

		cout << "Partial ACA" << endl;
		// Test Frobenius error
		test = test || !(partialACA_errors[A_partialACA.rank_of()]<GetEpsilon());
		cout << "Errors with Frobenius norm: "<<partialACA_errors<<endl;

		// Test compression rate
		test = test || !(0.93<A_partialACA.compression() && A_partialACA.compression()<0.96);
		cout << "Compression rate : "<<A_partialACA.compression()<<endl;

		// Test mat vec prod
		error = norm2(A*f-A_partialACA*f);
		test = test || !(error<GetEpsilon());
		cout << "Errors on a mat vec prod : "<< error<<endl<<endl<<endl;
	}

	return test;
}
<commit_msg>Too much constraint on a test, fixed<commit_after>#include <iostream>
#include <complex>
#include <vector>

#include <htool/cluster.hpp>
#include <htool/lrmat.hpp>
#include <htool/partialACA.hpp>

using namespace std;
using namespace htool;

class MyMatrix: public IMatrix<double>{
	const vector<R3>& p1;
	const vector<R3>& p2;

public:
	MyMatrix(const vector<R3>& p10,const vector<R3>& p20 ):IMatrix<double>(p10.size(),p20.size()),p1(p10),p2(p20) {}
	 double get_coef(const int& i, const int& j)const {return 1./(4*M_PI*norm2(p1[i]-p2[j]));}
	 std::vector<double> operator*(std::vector<double> a){
		std::vector<double> result(p1.size(),0);
		for (int i=0;i<p1.size();i++){
			for (int k=0;k<p2.size();k++){
				result[i]+=this->get_coef(i,k)*a[k];
			}
		}
		return result;
	 }
};

int main(){
	const int ndistance = 4;
	double distance[ndistance];
	distance[0] = 10; distance[1] = 20; distance[2] = 30; distance[3] = 40;
	SetNdofPerElt(1);
	bool test = 0;
	for(int idist=0; idist<ndistance; idist++)
	{
		cout << "Distance between the clusters: " << distance[idist] << endl;
		SetEpsilon(0.0001);
		srand (1);
		// we set a constant seed for rand because we want always the same result if we run the check many times
		// (two different initializations with the same seed will generate the same succession of results in the subsequent calls to rand)

		int nr = 500;
		int nc = 100;
		vector<int> Ir(nr); // row indices for the lrmatrix
		vector<int> Ic(nc); // column indices for the lrmatrix

		double z1 = 1;
		vector<R3>     p1(nr);
		vector<int>  tab1(nr);
		for(int j=0; j<nr; j++){
			Ir[j] = j;
			double rho = ((double) rand() / (double)(RAND_MAX)); // (double) otherwise integer division!
			double theta = ((double) rand() / (double)(RAND_MAX));
			p1[j][0] = sqrt(rho)*cos(2*M_PI*theta); p1[j][1] = sqrt(rho)*sin(2*M_PI*theta); p1[j][2] = z1;
			// sqrt(rho) otherwise the points would be concentrated in the center of the disk
			tab1[j]=j;
		}
		// p2: points in a unit disk of the plane z=z2
		double z2 = 1+distance[idist];
		vector<R3> p2(nc);
		vector<int> tab2(nc);
		for(int j=0; j<nc; j++){
            Ic[j] = j;
			double rho = ((double) rand() / (RAND_MAX)); // (double) otherwise integer division!
			double theta = ((double) rand() / (RAND_MAX));
			p2[j][0] = sqrt(rho)*cos(2*M_PI*theta); p2[j][1] = sqrt(rho)*sin(2*M_PI*theta); p2[j][2] = z2;
			tab2[j]=j;
		}

		Cluster t(p1,tab1); Cluster s(p2,tab2);
		MyMatrix A(p1,p2);

		// ACA with fixed rank
		int reqrank_max = 10;
		partialACA<double> A_partialACA_fixed(Ir,Ic,reqrank_max);
		A_partialACA_fixed.build(A,t,s);
		std::vector<double> partialACA_fixed_errors;
		for (int k = 0 ; k < A_partialACA_fixed.rank_of()+1 ; k++){
			partialACA_fixed_errors.push_back(Frobenius_absolute_error(A_partialACA_fixed,A,k));
		}

		cout << "Partial ACA with fixed rank" << endl;
		// Test rank
		cout << "rank : "<<A_partialACA_fixed.rank_of() << endl;
		test = test || !(A_partialACA_fixed.rank_of()==reqrank_max);

		// Test Frobenius errors
		test = test || !(partialACA_fixed_errors[partialACA_fixed_errors.size()-1]<1e-6);
		cout << "Errors with Frobenius norm : "<<partialACA_fixed_errors<<endl;

		// Test compression
		test = test || !(0.87<A_partialACA_fixed.compression() && A_partialACA_fixed.compression()<0.89);
		cout << "Compression rate : "<<A_partialACA_fixed.compression()<<endl;

		// Test mat vec prod
		std::vector<double> f(nc,1);
		double error=norm2(A*f-A_partialACA_fixed*f);
		test = test || !(error<1e-6);
		cout << "Errors on a mat vec prod : "<< error<<endl<<endl;

		// ACA automatic building
		partialACA<double> A_partialACA(Ir,Ic);
		A_partialACA.build(A,t,s);
		std::vector<double> partialACA_errors;
		for (int k = 0 ; k < A_partialACA.rank_of()+1 ; k++){
			partialACA_errors.push_back(Frobenius_absolute_error(A_partialACA,A,k));
		}

		cout << "Partial ACA" << endl;
		// Test Frobenius error
		test = test || !(partialACA_errors[A_partialACA.rank_of()]<GetEpsilon());
		cout << "Errors with Frobenius norm: "<<partialACA_errors<<endl;

		// Test compression rate
		test = test || !(0.93<A_partialACA.compression() && A_partialACA.compression()<0.96);
		cout << "Compression rate : "<<A_partialACA.compression()<<endl;

		// Test mat vec prod
		error = norm2(A*f-A_partialACA*f);
		test = test || !(error<GetEpsilon()*10);
		cout << "Errors on a mat vec prod : "<< error<<endl<<endl<<endl;
	}

	return test;
}
<|endoftext|>


<commit_before>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2017 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/abuffergl/processors/abuffergeometryglprocessor.h>
#include <modules/opengl/volume/volumegl.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/shader/shaderutils.h>
#include <modules/opengl/volume/volumeutils.h>
#include <modules/opengl/image/imagegl.h>
#include <inviwo/core/rendering/meshdrawerfactory.h>
#include <modules/opengl/image/layergl.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <modules/opengl/image/imagegl.h>
#include <inviwo/core/interaction/events/keyboardevent.h>
#include <inviwo/core/util/filesystem.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/shader/shaderutils.h>
#include <modules/opengl/openglutils.h>

#include <fstream>

namespace inviwo {

const ProcessorInfo ABufferGeometryGLProcessor::processorInfo_{
    "org.inviwo.ABufferGeometryGLProcessor",  // Class identifier
    "ABufferGeometryGLProcessor",             // Display name
    "ABufferDemo",                            // Category
    CodeState::Experimental,                  // Code state
    Tags::None,                               // Tags
};
const ProcessorInfo ABufferGeometryGLProcessor::getProcessorInfo() const {
    return processorInfo_;
}

ABufferGeometryGLProcessor::ABufferGeometryGLProcessor()
    : MeshRenderProcessorGL()
    , abuffer_()
    , transparency_("transparency", "Global Transparency", 0.5f, 0.0f, 1.0f, 0.001f)
    , abufferGeometryShader_("geometryrendering.vert", "abuffergeometrygl.frag", false) {
    addProperty(abuffer_.settings_);
    addProperty(transparency_);

    abuffer_.settings_.onChange(this, &ABufferGeometryGLProcessor::onAbufferSettingChanged);
    transparency_.onChange(this, &ABufferGeometryGLProcessor::onAbufferTransparencyChanged);
}

ABufferGeometryGLProcessor::~ABufferGeometryGLProcessor() {}

void ABufferGeometryGLProcessor::initializeResources() {
    MeshRenderProcessorGL::initializeResources();
    MeshRenderProcessorGL::addCommonShaderDefines(abufferGeometryShader_);
}

void ABufferGeometryGLProcessor::process() { geometryRender(); }

void ABufferGeometryGLProcessor::geometryRender() {
    ABUFFER_PROFILE("Total-Time");

    // tempImage_ = new Image(outport_.getDimensions());
    auto tempImage_ = outport_.getEditableData();
    ImageGL* tempImageGL = tempImage_->getEditableRepresentation<ImageGL>();
    ivec2 dim = outport_.getDimensions();

    bool abufferEnabled = abuffer_.settings_.abufferEnable_.get();

    // abuffer initialization
    if (abufferEnabled) {
        ABUFFER_PROFILE("Initialize-abuffer");
        abuffer_.abuffer_initABuffer(dim, updateRequried_);

        LGL_ERROR;
        abuffer_.abuffer_addShaderDefinesAndBuild(&abuffer_.resolveABufferShader_);

        LGL_ERROR;
        ABUFFER_PROFILE("Reset-abuffer");
        abuffer_.aBuffer_resetLinkList(tempImageGL);

        updateRequried_ = false;
    }

    abuffer_.abuffer_addShaderDefinesAndBuild(&abufferGeometryShader_);

    // Rendering
    {
        ABUFFER_PROFILE("Rendering");

        tempImageGL = tempImage_->getEditableRepresentation<ImageGL>();
        utilgl::activateAndClearTarget(outport_);

        // initialize shader
        abufferGeometryShader_.activate();
        // LGL_ERROR;
        utilgl::setShaderUniforms(abufferGeometryShader_, camera_, "camera_");
        // LGL_ERROR;
        utilgl::setShaderUniforms(abufferGeometryShader_, lightingProperty_, "light_");
        // LGL_ERROR;

        if (abufferEnabled) {
            abuffer_.abuffer_addUniforms(&abufferGeometryShader_);
            abufferGeometryShader_.setUniform("globalTransparency_", transparency_.get());
        }

        utilgl::GlBoolState depthTest(GL_DEPTH_TEST, true);
        utilgl::CullFaceState culling(cullFace_.get());
        utilgl::PolygonModeState polygon(polygonMode_.get(), renderLineWidth_, renderPointSize_);

        for (auto& drawer : drawers_) {
            utilgl::setShaderUniforms(abufferGeometryShader_, *(drawer.second->getMesh()),
                                      "geometry_");
            drawer.second->draw();
        }

        abufferGeometryShader_.deactivate();
        utilgl::deactivateCurrentTarget();

        glMemoryBarrierEXT(GL_ALL_BARRIER_BITS_EXT);
    }

    // abuffer resolve
    if (abufferEnabled) {
        ABUFFER_PROFILE("Resolving-abuffer");
        utilgl::activateAndClearTarget(outport_);
        abuffer_.aBuffer_resolveLinkList(tempImageGL, imageInport_.getData().get());
        utilgl::deactivateCurrentTarget();
    }
}

void ABufferGeometryGLProcessor::onAbufferSettingChanged() { updateRequried_ = true; }

void ABufferGeometryGLProcessor::onAbufferTransparencyChanged() { /*updateRequried_ = true;*/ }

}  // namespace

<commit_msg>ABufferGL: Minor changes.<commit_after>/*********************************************************************************
 *
 * Inviwo - Interactive Visualization Workshop
 *
 * Copyright (c) 2014-2017 Inviwo Foundation
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * 1. Redistributions of source code must retain the above copyright notice, this
 * list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright notice,
 * this list of conditions and the following disclaimer in the documentation
 * and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
 * ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 *********************************************************************************/

#include <modules/abuffergl/processors/abuffergeometryglprocessor.h>
#include <modules/opengl/volume/volumegl.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/shader/shaderutils.h>
#include <modules/opengl/volume/volumeutils.h>
#include <modules/opengl/image/imagegl.h>
#include <inviwo/core/rendering/meshdrawerfactory.h>
#include <modules/opengl/image/layergl.h>
#include <inviwo/core/datastructures/image/layerram.h>
#include <modules/opengl/image/imagegl.h>
#include <inviwo/core/interaction/events/keyboardevent.h>
#include <inviwo/core/util/filesystem.h>
#include <modules/opengl/texture/textureutils.h>
#include <modules/opengl/shader/shaderutils.h>
#include <modules/opengl/openglutils.h>

#include <fstream>

namespace inviwo {

const ProcessorInfo ABufferGeometryGLProcessor::processorInfo_{
    "org.inviwo.ABufferGeometryGLProcessor",  // Class identifier
    "ABufferGeometryGLProcessor",             // Display name
    "ABufferDemo",                            // Category
    CodeState::Experimental,                  // Code state
    Tags::None,                               // Tags
};
const ProcessorInfo ABufferGeometryGLProcessor::getProcessorInfo() const {
    return processorInfo_;
}

ABufferGeometryGLProcessor::ABufferGeometryGLProcessor()
    : MeshRenderProcessorGL()
    , abuffer_()
    , transparency_("transparency", "Global Transparency", 0.5f, 0.0f, 1.0f, 0.001f)
    , abufferGeometryShader_("geometryrendering.vert", "abuffergeometrygl.frag", false) {
    addProperty(abuffer_.settings_);
    addProperty(transparency_);

    abuffer_.settings_.onChange(this, &ABufferGeometryGLProcessor::onAbufferSettingChanged);
    transparency_.onChange(this, &ABufferGeometryGLProcessor::onAbufferTransparencyChanged);
}

ABufferGeometryGLProcessor::~ABufferGeometryGLProcessor() {}

void ABufferGeometryGLProcessor::initializeResources() {
    MeshRenderProcessorGL::initializeResources();
    MeshRenderProcessorGL::addCommonShaderDefines(abufferGeometryShader_);
}

void ABufferGeometryGLProcessor::process() { geometryRender(); }

void ABufferGeometryGLProcessor::geometryRender() {
    ABUFFER_PROFILE("Total-Time");

    // tempImage_ = new Image(outport_.getDimensions());
    auto tempImage_ = outport_.getEditableData();
    ImageGL* tempImageGL = tempImage_->getEditableRepresentation<ImageGL>();
    ivec2 dim = outport_.getDimensions();

    bool abufferEnabled = abuffer_.settings_.abufferEnable_.get();

    // abuffer initialization
    if (abufferEnabled) {
        ABUFFER_PROFILE("Initialize-abuffer");
        abuffer_.abuffer_initABuffer(dim, updateRequried_);

        LGL_ERROR;
        abuffer_.abuffer_addShaderDefinesAndBuild(&abuffer_.resolveABufferShader_);

        LGL_ERROR;
        ABUFFER_PROFILE("Reset-abuffer");
        abuffer_.aBuffer_resetLinkList(tempImageGL);

        updateRequried_ = false;
    }

    abuffer_.abuffer_addShaderDefinesAndBuild(&abufferGeometryShader_);

    // Rendering
    {
        ABUFFER_PROFILE("Rendering");

        tempImageGL = tempImage_->getEditableRepresentation<ImageGL>();

        if (imageInport_.isConnected())
            utilgl::activateTargetAndCopySource(outport_, imageInport_);
        else
            utilgl::activateAndClearTarget(outport_);

        // initialize shader
        abufferGeometryShader_.activate();
        // LGL_ERROR;
        utilgl::setShaderUniforms(abufferGeometryShader_, camera_, "camera_");
        // LGL_ERROR;
        utilgl::setShaderUniforms(abufferGeometryShader_, lightingProperty_, "light_");
        // LGL_ERROR;

        if (abufferEnabled) {
            abuffer_.abuffer_addUniforms(&abufferGeometryShader_);
            abufferGeometryShader_.setUniform("globalTransparency_", transparency_.get());
        }

        utilgl::GlBoolState depthTest(GL_DEPTH_TEST, true);
        utilgl::CullFaceState culling(cullFace_.get());
        utilgl::PolygonModeState polygon(polygonMode_.get(), renderLineWidth_, renderPointSize_);

        for (auto& drawer : drawers_) {
            utilgl::setShaderUniforms(abufferGeometryShader_, *(drawer.second->getMesh()),
                                      "geometry_");
            drawer.second->draw();
        }

        abufferGeometryShader_.deactivate();
        utilgl::deactivateCurrentTarget();

        glMemoryBarrierEXT(GL_ALL_BARRIER_BITS_EXT);
    }

    // abuffer resolve
    if (abufferEnabled) {
        ABUFFER_PROFILE("Resolving-abuffer");
        utilgl::activateAndClearTarget(outport_);
        abuffer_.aBuffer_resolveLinkList(tempImageGL, imageInport_.getData().get());
        utilgl::deactivateCurrentTarget();
    }
}

void ABufferGeometryGLProcessor::onAbufferSettingChanged() { updateRequried_ = true; }

void ABufferGeometryGLProcessor::onAbufferTransparencyChanged() { /*updateRequried_ = true;*/ }

}  // namespace

<|endoftext|>


<commit_before>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "testing/gtest/include/gtest/gtest.h"
extern "C" {
#include "webrtc/modules/audio_processing/aec/aec_core.h"
}
#include "webrtc/modules/audio_processing/include/audio_processing.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/test/testsupport/gtest_disable.h"

namespace webrtc {

TEST(EchoCancellationInternalTest, DISABLED_ON_ANDROID(DelayCorrection)) {
  scoped_ptr<AudioProcessing> ap(AudioProcessing::Create(0));
  EXPECT_TRUE(ap->echo_cancellation()->aec_core() == NULL);

  EXPECT_EQ(ap->kNoError, ap->echo_cancellation()->Enable(true));
  EXPECT_TRUE(ap->echo_cancellation()->is_enabled());

  AecCore* aec_core = ap->echo_cancellation()->aec_core();
  ASSERT_TRUE(aec_core != NULL);
  // Disabled by default.
  EXPECT_EQ(0, WebRtcAec_delay_correction_enabled(aec_core));

  Config config;
  config.Set<DelayCorrection>(new DelayCorrection(true));
  ap->SetExtraOptions(config);
  EXPECT_EQ(1, WebRtcAec_delay_correction_enabled(aec_core));

  // Retains setting after initialization.
  EXPECT_EQ(ap->kNoError, ap->Initialize());
  EXPECT_EQ(1, WebRtcAec_delay_correction_enabled(aec_core));

  config.Set<DelayCorrection>(new DelayCorrection(false));
  ap->SetExtraOptions(config);
  EXPECT_EQ(0, WebRtcAec_delay_correction_enabled(aec_core));

  // Retains setting after initialization.
  EXPECT_EQ(ap->kNoError, ap->Initialize());
  EXPECT_EQ(0, WebRtcAec_delay_correction_enabled(aec_core));
}

}  // namespace webrtc
<commit_msg>Enables DelayCorrection tests<commit_after>/*
 *  Copyright (c) 2013 The WebRTC project authors. All Rights Reserved.
 *
 *  Use of this source code is governed by a BSD-style license
 *  that can be found in the LICENSE file in the root of the source
 *  tree. An additional intellectual property rights grant can be found
 *  in the file PATENTS.  All contributing project authors may
 *  be found in the AUTHORS file in the root of the source tree.
 */

#include "testing/gtest/include/gtest/gtest.h"
extern "C" {
#include "webrtc/modules/audio_processing/aec/aec_core.h"
}
#include "webrtc/modules/audio_processing/include/audio_processing.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/test/testsupport/gtest_disable.h"

namespace webrtc {

TEST(EchoCancellationInternalTest, DelayCorrection) {
  scoped_ptr<AudioProcessing> ap(AudioProcessing::Create(0));
  EXPECT_TRUE(ap->echo_cancellation()->aec_core() == NULL);

  EXPECT_EQ(ap->kNoError, ap->echo_cancellation()->Enable(true));
  EXPECT_TRUE(ap->echo_cancellation()->is_enabled());

  AecCore* aec_core = ap->echo_cancellation()->aec_core();
  ASSERT_TRUE(aec_core != NULL);
  // Disabled by default.
  EXPECT_EQ(0, WebRtcAec_delay_correction_enabled(aec_core));

  Config config;
  config.Set<DelayCorrection>(new DelayCorrection(true));
  ap->SetExtraOptions(config);
  EXPECT_EQ(1, WebRtcAec_delay_correction_enabled(aec_core));

  // Retains setting after initialization.
  EXPECT_EQ(ap->kNoError, ap->Initialize());
  EXPECT_EQ(1, WebRtcAec_delay_correction_enabled(aec_core));

  config.Set<DelayCorrection>(new DelayCorrection(false));
  ap->SetExtraOptions(config);
  EXPECT_EQ(0, WebRtcAec_delay_correction_enabled(aec_core));

  // Retains setting after initialization.
  EXPECT_EQ(ap->kNoError, ap->Initialize());
  EXPECT_EQ(0, WebRtcAec_delay_correction_enabled(aec_core));
}

}  // namespace webrtc
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkTubeSpatialObjectTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

/*
* itkTubeSpatialObject, and itkTubeNetworkSpatialObject test file.
* This test file test also the basic functions of the CompositeSpatialObject class,
* like Add/RemoveSpatialObjecT(...), Get/SetChildren(...), etc...
*/

#include "itkPoint.h"
#include "itkVector.h"
#include "itkAffineTransform.h"
#include "itkTubePoint.h"
#include "itkTubeSpatialObject.h"
#include "itkTubeNetworkSpatialObject.h"

#include <cmath>
#include <vnl/vnl_math.h>

int itkTubeSpatialObjectTest(int, char **)
{
  typedef double ScalarType;
  typedef bool OutputType;
  typedef itk::Vector< ScalarType, 3> Vector;
  typedef itk::Vector< OutputType, 3> OutputVector;
  typedef itk::Point< ScalarType, 3> Point;
  typedef itk::Matrix< ScalarType, 3, 3> Matrix;
  typedef itk::TubeSpatialObject::Pointer TubePointer;
  typedef itk::TubeNetworkSpatialObject::Pointer TubeNetPointer;
  typedef itk::AffineTransform< ScalarType, 3 > AffineTransformType;
  typedef AffineTransformType::Pointer AffineTransformPointer;
  typedef itk::TubeNetworkSpatialObject::ChildrenListType ChildrenListType;

  Vector axis, translation;
  Point in, out;
  double angle;
  bool passed = true;

  //======================================
  // testing of a single SpatialObject...
  //======================================

  std::cout<<"=================================="<<std::endl;
  std::cout<<"Testing SpatialObject:"<<std::endl<<std::endl;

  TubePointer tube1 = itk::TubeSpatialObject::New();
  AffineTransformPointer tube1Transform = AffineTransformType::New();
  AffineTransformPointer tube1InverseTransform = AffineTransformType::New();
  itk::TubeSpatialObject::PointListPointer list = new itk::TubeSpatialObject::PointListType();

  translation.Fill(10);
  tube1Transform->Translate(translation);
  tube1InverseTransform->Translate(-translation);

  for( unsigned int i=0; i<10; i++)
    {
    itk::TubePoint * p = new itk::TubePoint();
    p->SetCenterLinePoint(i,i,i);
    p->SetRadius(1);
    list->push_back(p);
    }

  tube1->GetProperty()->SetName("Tube 1");
  tube1->SetId(1);
  tube1->SetLocalToGlobalTransform(tube1Transform);
  tube1->SetGlobalToLocalTransform(tube1InverseTransform);
  tube1->SetPoints(list);
  tube1->ComputeBounds();

  in.Fill(15);
  out.Fill(5);

  std::cout<<"IsInside()...";
  if( !tube1->IsInside(in) || tube1->IsInside(out) )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  itk::TubeSpatialObject::OutputVectorType derivative;

  std::cout<<"DerivativeAt()...";
  try
    {
    tube1->DerivativeAt(in,1,derivative);
    }
  catch(...)
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }

  itk::TubeSpatialObject::OutputVectorType expectedDerivative;
  expectedDerivative.Fill(0);

  if( expectedDerivative != derivative )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  std::cout<<"itkTubeSpatialObjectTest ";
  if( passed )
    {
    std::cout<<"[PASSED]"<<std::endl;
    }
  else
    {
    std::cout<<"[FAILED]"<<std::endl;
    }

  //==============================================
  // testing of a single CompositeSpatialObject...
  //==============================================

  std::cout<<"=================================="<<std::endl;
  std::cout<<"Testing TubeNetworkSpatialObject:"<<std::endl<<std::endl;

  ChildrenListType childrenList, returnedList;
  unsigned int nbChildren;

  TubePointer tube2 = itk::TubeSpatialObject::New();
  tube2->GetProperty()->SetName("Tube 2");
  tube2->SetId(2);
  tube2->SetPoints(list);
  tube2->ComputeBounds();

  TubePointer tube3 = itk::TubeSpatialObject::New();
  tube3->GetProperty()->SetName("Tube 3");
  tube3->SetId(3);
  tube3->SetPoints(list);
  tube3->ComputeBounds();

  TubeNetPointer tubeNet1 = itk::TubeNetworkSpatialObject::New();
  tubeNet1->GetProperty()->SetName("tube network 1");
  tubeNet1->AddSpatialObject( tube1.GetPointer() );
  tubeNet1->AddSpatialObject( tube2.GetPointer() );
  tubeNet1->AddSpatialObject( tube3.GetPointer() );

  // testing the AddSpatialObject() function...
  nbChildren = tubeNet1->GetNumberOfChildren();

  std::cout<<"AddSpatialObject()...";
  if( nbChildren != 3 )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  // testing the RemoveSpatialObject() function...
  tubeNet1->RemoveSpatialObject( tube1.GetPointer() );
  tubeNet1->RemoveSpatialObject( tube2.GetPointer() );
  tubeNet1->RemoveSpatialObject( tube3.GetPointer() );

  nbChildren = tubeNet1->GetNumberOfChildren();

  std::cout<<"RemoveSpatialObject()...";
  if( nbChildren != 0 )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  tubeNet1->AddSpatialObject( tube1.GetPointer() );
  tubeNet1->AddSpatialObject( tube2.GetPointer() );
  tubeNet1->AddSpatialObject( tube3.GetPointer() );

  // testing the GetChildren() function...
  childrenList.push_back(tube1.GetPointer());
  childrenList.push_back(tube2.GetPointer());
  childrenList.push_back(tube3.GetPointer());

  returnedList = tubeNet1->GetChildren();

  if( childrenList.size() == returnedList.size() )
    {
    ChildrenListType::iterator itTest = returnedList.begin();
    ChildrenListType::iterator it = childrenList.begin();
    ChildrenListType::iterator end = childrenList.end();

    for(unsigned int i=0; it!=end; itTest++,it++,i++ )
      {
      if((*itTest) != (*it))
        {
        passed = false;
        break;
        }
      }

    }
  else
    {
    passed = false;
    }

  std::cout<<"GetChildren()...";
  if( !passed )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  tubeNet1->RemoveSpatialObject( tube1.GetPointer() );
  tubeNet1->RemoveSpatialObject( tube2.GetPointer() );
  tubeNet1->RemoveSpatialObject( tube3.GetPointer() );

  // testing the SetChildren() function...
  tubeNet1->SetChildren(childrenList);
  returnedList = tubeNet1->GetChildren();

  if( childrenList.size() == returnedList.size() )
    {
    ChildrenListType::iterator itTest = returnedList.begin();
    ChildrenListType::iterator it = childrenList.begin();
    ChildrenListType::iterator end = childrenList.end();

    passed = true;

    for(unsigned int i=0; it!=end; itTest++,it++,i++ )
      {
      if((*itTest) != (*it))
        {
        passed = false;
        break;
        }
      }
    }
  else
    {
    passed = false;
    }

  std::cout<<"SetChildren()...";
  if( !passed )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  tubeNet1->ComputeBounds();

  std::cout<<"HasParent()...";
  if( !tube1->HasParent() )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  AffineTransformPointer tube2Transform = AffineTransformType::New();
  AffineTransformPointer tube2InverseTransform = AffineTransformType::New();
  tube2->SetLocalToGlobalTransform(tube2Transform);
  tube2->SetGlobalToLocalTransform(tube2InverseTransform);

  AffineTransformPointer tube3Transform = AffineTransformType::New();
  AffineTransformPointer tube3InverseTransform = AffineTransformType::New();
  tube3->SetLocalToGlobalTransform(tube3Transform);
  tube3->SetGlobalToLocalTransform(tube3InverseTransform);

  AffineTransformPointer tubeNet1Transform = AffineTransformType::New();
  AffineTransformPointer tubeNet1InverseTransform = AffineTransformType::New();
  tubeNet1->SetLocalToGlobalTransform(tubeNet1Transform);
  tubeNet1->SetGlobalToLocalTransform(tubeNet1InverseTransform);

  translation.Fill(10);

  tubeNet1Transform->Translate(translation,false);
  tubeNet1InverseTransform->Translate(-translation,false);

  axis.Fill(0);
  axis[1] = 1;

  angle = vnl_math::pi_over_2;
  tube2Transform->Rotate3D(axis,angle);
  tube2InverseTransform->Rotate3D(axis,-angle);

  angle = -vnl_math::pi_over_2;
  tube3Transform->Rotate3D(axis,angle);
  tube3InverseTransform->Rotate3D(axis,-angle);

  in.Fill(25);
  out.Fill(15);

  Point p1,p2;
  p1.Fill(15);
  p1[2]=5;
  p2.Fill(15);
  p2[0]=5;

  std::cout<<"IsInside()...";
  if( !tubeNet1->IsInside(in) || tubeNet1->IsInside(out) )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  std::cout<<"DerivativeAt()...";
  try
    {
    tubeNet1->DerivativeAt(in,(unsigned short)1,derivative);
    }
  catch(...)
    {
    std::cout<<"[FAILED]"<<std::endl;
    }

  if( derivative == expectedDerivative )
    {
    std::cout<<"[PASSED]"<<std::endl;
    }
  else
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;

}
<commit_msg>BUG- removed the <cmath> include<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkTubeSpatialObjectTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 2002 Insight Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

/*
* itkTubeSpatialObject, and itkTubeNetworkSpatialObject test file.
* This test file test also the basic functions of the CompositeSpatialObject class,
* like Add/RemoveSpatialObjecT(...), Get/SetChildren(...), etc...
*/

#include "itkPoint.h"
#include "itkVector.h"
#include "itkAffineTransform.h"
#include "itkTubePoint.h"
#include "itkTubeSpatialObject.h"
#include "itkTubeNetworkSpatialObject.h"

#include <vnl/vnl_math.h>

int itkTubeSpatialObjectTest(int, char **)
{
  typedef double ScalarType;
  typedef bool OutputType;
  typedef itk::Vector< ScalarType, 3> Vector;
  typedef itk::Vector< OutputType, 3> OutputVector;
  typedef itk::Point< ScalarType, 3> Point;
  typedef itk::Matrix< ScalarType, 3, 3> Matrix;
  typedef itk::TubeSpatialObject::Pointer TubePointer;
  typedef itk::TubeNetworkSpatialObject::Pointer TubeNetPointer;
  typedef itk::AffineTransform< ScalarType, 3 > AffineTransformType;
  typedef AffineTransformType::Pointer AffineTransformPointer;
  typedef itk::TubeNetworkSpatialObject::ChildrenListType ChildrenListType;

  Vector axis, translation;
  Point in, out;
  double angle;
  bool passed = true;

  //======================================
  // testing of a single SpatialObject...
  //======================================

  std::cout<<"=================================="<<std::endl;
  std::cout<<"Testing SpatialObject:"<<std::endl<<std::endl;

  TubePointer tube1 = itk::TubeSpatialObject::New();
  AffineTransformPointer tube1Transform = AffineTransformType::New();
  AffineTransformPointer tube1InverseTransform = AffineTransformType::New();
  itk::TubeSpatialObject::PointListPointer list = new itk::TubeSpatialObject::PointListType();

  translation.Fill(10);
  tube1Transform->Translate(translation);
  tube1InverseTransform->Translate(-translation);

  for( unsigned int i=0; i<10; i++)
    {
    itk::TubePoint * p = new itk::TubePoint();
    p->SetCenterLinePoint(i,i,i);
    p->SetRadius(1);
    list->push_back(p);
    }

  tube1->GetProperty()->SetName("Tube 1");
  tube1->SetId(1);
  tube1->SetLocalToGlobalTransform(tube1Transform);
  tube1->SetGlobalToLocalTransform(tube1InverseTransform);
  tube1->SetPoints(list);
  tube1->ComputeBounds();

  in.Fill(15);
  out.Fill(5);

  std::cout<<"IsInside()...";
  if( !tube1->IsInside(in) || tube1->IsInside(out) )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  itk::TubeSpatialObject::OutputVectorType derivative;

  std::cout<<"DerivativeAt()...";
  try
    {
    tube1->DerivativeAt(in,1,derivative);
    }
  catch(...)
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }

  itk::TubeSpatialObject::OutputVectorType expectedDerivative;
  expectedDerivative.Fill(0);

  if( expectedDerivative != derivative )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  std::cout<<"itkTubeSpatialObjectTest ";
  if( passed )
    {
    std::cout<<"[PASSED]"<<std::endl;
    }
  else
    {
    std::cout<<"[FAILED]"<<std::endl;
    }

  //==============================================
  // testing of a single CompositeSpatialObject...
  //==============================================

  std::cout<<"=================================="<<std::endl;
  std::cout<<"Testing TubeNetworkSpatialObject:"<<std::endl<<std::endl;

  ChildrenListType childrenList, returnedList;
  unsigned int nbChildren;

  TubePointer tube2 = itk::TubeSpatialObject::New();
  tube2->GetProperty()->SetName("Tube 2");
  tube2->SetId(2);
  tube2->SetPoints(list);
  tube2->ComputeBounds();

  TubePointer tube3 = itk::TubeSpatialObject::New();
  tube3->GetProperty()->SetName("Tube 3");
  tube3->SetId(3);
  tube3->SetPoints(list);
  tube3->ComputeBounds();

  TubeNetPointer tubeNet1 = itk::TubeNetworkSpatialObject::New();
  tubeNet1->GetProperty()->SetName("tube network 1");
  tubeNet1->AddSpatialObject( tube1.GetPointer() );
  tubeNet1->AddSpatialObject( tube2.GetPointer() );
  tubeNet1->AddSpatialObject( tube3.GetPointer() );

  // testing the AddSpatialObject() function...
  nbChildren = tubeNet1->GetNumberOfChildren();

  std::cout<<"AddSpatialObject()...";
  if( nbChildren != 3 )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  // testing the RemoveSpatialObject() function...
  tubeNet1->RemoveSpatialObject( tube1.GetPointer() );
  tubeNet1->RemoveSpatialObject( tube2.GetPointer() );
  tubeNet1->RemoveSpatialObject( tube3.GetPointer() );

  nbChildren = tubeNet1->GetNumberOfChildren();

  std::cout<<"RemoveSpatialObject()...";
  if( nbChildren != 0 )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  tubeNet1->AddSpatialObject( tube1.GetPointer() );
  tubeNet1->AddSpatialObject( tube2.GetPointer() );
  tubeNet1->AddSpatialObject( tube3.GetPointer() );

  // testing the GetChildren() function...
  childrenList.push_back(tube1.GetPointer());
  childrenList.push_back(tube2.GetPointer());
  childrenList.push_back(tube3.GetPointer());

  returnedList = tubeNet1->GetChildren();

  if( childrenList.size() == returnedList.size() )
    {
    ChildrenListType::iterator itTest = returnedList.begin();
    ChildrenListType::iterator it = childrenList.begin();
    ChildrenListType::iterator end = childrenList.end();

    for(unsigned int i=0; it!=end; itTest++,it++,i++ )
      {
      if((*itTest) != (*it))
        {
        passed = false;
        break;
        }
      }

    }
  else
    {
    passed = false;
    }

  std::cout<<"GetChildren()...";
  if( !passed )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  tubeNet1->RemoveSpatialObject( tube1.GetPointer() );
  tubeNet1->RemoveSpatialObject( tube2.GetPointer() );
  tubeNet1->RemoveSpatialObject( tube3.GetPointer() );

  // testing the SetChildren() function...
  tubeNet1->SetChildren(childrenList);
  returnedList = tubeNet1->GetChildren();

  if( childrenList.size() == returnedList.size() )
    {
    ChildrenListType::iterator itTest = returnedList.begin();
    ChildrenListType::iterator it = childrenList.begin();
    ChildrenListType::iterator end = childrenList.end();

    passed = true;

    for(unsigned int i=0; it!=end; itTest++,it++,i++ )
      {
      if((*itTest) != (*it))
        {
        passed = false;
        break;
        }
      }
    }
  else
    {
    passed = false;
    }

  std::cout<<"SetChildren()...";
  if( !passed )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  tubeNet1->ComputeBounds();

  std::cout<<"HasParent()...";
  if( !tube1->HasParent() )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  AffineTransformPointer tube2Transform = AffineTransformType::New();
  AffineTransformPointer tube2InverseTransform = AffineTransformType::New();
  tube2->SetLocalToGlobalTransform(tube2Transform);
  tube2->SetGlobalToLocalTransform(tube2InverseTransform);

  AffineTransformPointer tube3Transform = AffineTransformType::New();
  AffineTransformPointer tube3InverseTransform = AffineTransformType::New();
  tube3->SetLocalToGlobalTransform(tube3Transform);
  tube3->SetGlobalToLocalTransform(tube3InverseTransform);

  AffineTransformPointer tubeNet1Transform = AffineTransformType::New();
  AffineTransformPointer tubeNet1InverseTransform = AffineTransformType::New();
  tubeNet1->SetLocalToGlobalTransform(tubeNet1Transform);
  tubeNet1->SetGlobalToLocalTransform(tubeNet1InverseTransform);

  translation.Fill(10);

  tubeNet1Transform->Translate(translation,false);
  tubeNet1InverseTransform->Translate(-translation,false);

  axis.Fill(0);
  axis[1] = 1;

  angle = vnl_math::pi_over_2;
  tube2Transform->Rotate3D(axis,angle);
  tube2InverseTransform->Rotate3D(axis,-angle);

  angle = -vnl_math::pi_over_2;
  tube3Transform->Rotate3D(axis,angle);
  tube3InverseTransform->Rotate3D(axis,-angle);

  in.Fill(25);
  out.Fill(15);

  Point p1,p2;
  p1.Fill(15);
  p1[2]=5;
  p2.Fill(15);
  p2[0]=5;

  std::cout<<"IsInside()...";
  if( !tubeNet1->IsInside(in) || tubeNet1->IsInside(out) )
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }
  else
    {
    std::cout<<"[PASSED]"<<std::endl;
    }

  std::cout<<"DerivativeAt()...";
  try
    {
    tubeNet1->DerivativeAt(in,(unsigned short)1,derivative);
    }
  catch(...)
    {
    std::cout<<"[FAILED]"<<std::endl;
    }

  if( derivative == expectedDerivative )
    {
    std::cout<<"[PASSED]"<<std::endl;
    }
  else
    {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
    }

  return EXIT_SUCCESS;

}
<|endoftext|>


<commit_before>#include <gtest/gtest.h>
#include <stan/math/rev.hpp>
#include <test/unit/util.hpp>
#include <limits>

TEST(AgradRevErrorHandlingMatrix, checkPosSemiDefiniteMatrix_nan) {
  using Eigen::Dynamic;
  using Eigen::Matrix;
  using stan::math::var;

  Matrix<var, Dynamic, Dynamic> y;
  double nan = std::numeric_limits<double>::quiet_NaN();
  using stan::math::check_pos_semidefinite;

  y.resize(1, 1);
  y << nan;
  EXPECT_THROW_MSG(check_pos_semidefinite("checkPosDefiniteMatrix", "y", y),
                   std::domain_error,
                   "checkPosDefiniteMatrix: y[1] is nan, but must not be nan!");

  y.resize(3, 3);
  y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
  EXPECT_NO_THROW(check_pos_semidefinite("checkPosDefiniteMatrix", "y", y));

  for (int i = 0; i < y.rows(); i++)
    for (int j = 0; j < y.cols(); j++) {
      y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
      y(i, j) = nan;
      if (i >= j)
        EXPECT_THROW(check_pos_semidefinite("checkPosDefiniteMatrix", "y", y),
                     std::domain_error);
    }

  y << 0, 0, 0, 0, 0, 0, 0, 0, 0;
  EXPECT_NO_THROW(check_pos_semidefinite("checkPosDefiniteMatrix", "y", y));
  stan::math::recover_memory();
}

TEST(AgradRevErrorHandlingMatrix, checkPosSemiDefiniteMatrixVarCheck) {
  using Eigen::Dynamic;
  using Eigen::Matrix;
  using stan::math::var;

  Matrix<var, Dynamic, Dynamic> y;
  double nan = std::numeric_limits<double>::quiet_NaN();
  using stan::math::check_pos_semidefinite;

  y.resize(3, 3);
  y << 2, -1, 0, -1, 2, -1, 0, -1, 2;

  size_t stack_before_call
      = stan::math::ChainableStack::instance_->var_stack_.size()
        + stan::math::ChainableStack::instance_->var_nochain_stack_.size();
  EXPECT_EQ(9U, stack_before_call);

  EXPECT_NO_THROW(check_pos_semidefinite("checkPosDefiniteMatrix", "y", y));
  size_t stack_after_call
      = stan::math::ChainableStack::instance_->var_stack_.size()
        + stan::math::ChainableStack::instance_->var_nochain_stack_.size();

  EXPECT_EQ(9U, stack_after_call);
}
<commit_msg>another testimproved<commit_after>#include <gtest/gtest.h>
#include <stan/math/rev.hpp>
#include <test/unit/util.hpp>
#include <limits>

TEST(AgradRevErrorHandlingMatrix, checkPosSemiDefiniteMatrix_nan) {
  using Eigen::Dynamic;
  using Eigen::Matrix;
  using stan::math::var;

  Matrix<var, Dynamic, Dynamic> y;
  double nan = std::numeric_limits<double>::quiet_NaN();
  using stan::math::check_pos_semidefinite;

  y.resize(1, 1);
  y << nan;
  EXPECT_THROW_MSG(check_pos_semidefinite("checkPosDefiniteMatrix", "y", y),
                   std::domain_error,
                   "checkPosDefiniteMatrix: y[1, 1] is nan");

  y.resize(3, 3);
  y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
  EXPECT_NO_THROW(check_pos_semidefinite("checkPosDefiniteMatrix", "y", y));

  for (int i = 0; i < y.rows(); i++)
    for (int j = 0; j < y.cols(); j++) {
      y << 2, -1, 0, -1, 2, -1, 0, -1, 2;
      y(i, j) = nan;
      if (i >= j)
        EXPECT_THROW(check_pos_semidefinite("checkPosDefiniteMatrix", "y", y),
                     std::domain_error);
    }

  y << 0, 0, 0, 0, 0, 0, 0, 0, 0;
  EXPECT_NO_THROW(check_pos_semidefinite("checkPosDefiniteMatrix", "y", y));
  stan::math::recover_memory();
}

TEST(AgradRevErrorHandlingMatrix, checkPosSemiDefiniteMatrixVarCheck) {
  using Eigen::Dynamic;
  using Eigen::Matrix;
  using stan::math::var;

  Matrix<var, Dynamic, Dynamic> y;
  double nan = std::numeric_limits<double>::quiet_NaN();
  using stan::math::check_pos_semidefinite;

  y.resize(3, 3);
  y << 2, -1, 0, -1, 2, -1, 0, -1, 2;

  size_t stack_before_call
      = stan::math::ChainableStack::instance_->var_stack_.size()
        + stan::math::ChainableStack::instance_->var_nochain_stack_.size();
  EXPECT_EQ(9U, stack_before_call);

  EXPECT_NO_THROW(check_pos_semidefinite("checkPosDefiniteMatrix", "y", y));
  size_t stack_after_call
      = stan::math::ChainableStack::instance_->var_stack_.size()
        + stan::math::ChainableStack::instance_->var_nochain_stack_.size();

  EXPECT_EQ(9U, stack_after_call);
}
<|endoftext|>


<commit_before>#include "visual.h"
#include <array>
#include <ctime>
#include <iostream>
#include <list>
#include <random>
#include <stdlib.h>
#include <stdio.h>
#include <vector>

#include <AntTweakBar.h>

#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/rotate_vector.hpp>

#include "camera/camera.h"
#include "shaders/program.h"
#include "shaders/shader.h"
#include "textures/texture.h"
#include "util/checked_call.h"

static size_t sWinWidth = 1280;
static size_t sWinHeight = 800;
static bool sMouseVisible{ false };
glm::vec3 const sCubePos(0.0f, 0.0f, -15.0f);

static camera sCamera(sWinWidth, sWinHeight);
static float sYaw = 0.0f;
static float sPitch = 0.0f;
static std::vector<bool> sKeys(GLFW_KEY_LAST, false);
static float sStep = 1.0f;

static TwBar* sATB{ nullptr };

static void glfwErrorReporting(int errCode, char const* msg);
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int modifiers);
static void mouseCallback(GLFWwindow* window, double x, double y);
static void scrollCallback(GLFWwindow* window, double xDiff, double yDiff);
static void mouseButtonCallback(GLFWwindow* window, int button, int action, int modifiers);
static void charCallback(GLFWwindow* window, unsigned int symb);
static void windowSizeCallback(GLFWwindow* window, int sizeX, int sizeY);
static void moveCamera(float dt);

int runVisual()
{
    sCamera.fov(90);
    CHECK(GL_FALSE != glfwInit(), "GLFW init failed", return -1;);
        // Provide some hints for the GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);

    glfwSetErrorCallback(glfwErrorReporting);

        // Create a window
    GLFWwindow* window = glfwCreateWindow(sWinWidth, sWinHeight, "Renderize", nullptr, nullptr);
    CHECK(window, "Error creating window", { glfwTerminate(); return -1; });
    glfwMakeContextCurrent(window);

    if (TwInit(TW_OPENGL_CORE, NULL))
    {
        TwWindowSize(sWinWidth, sWinHeight);
        sATB = TwNewBar("Tweak");
        TwAddVarRW(sATB, "step", TW_TYPE_FLOAT, &sStep, " label='Step' step=0.1 ");
    }
    else
        std::cerr << TwGetLastError() << std::endl;

        // Initialize Glew
    glewExperimental = GL_TRUE;
    GLenum glewCode = glewInit();
    CHECK(GLEW_OK == glewCode, "Failed to initialize GLEW: ",
        std::cerr << glewGetErrorString(glewCode) << std::endl; return -1;);

    glViewport(0, 0, sWinWidth, sWinHeight);
    glEnable(GL_DEPTH_TEST);

    // Initialize some GLFW callbacks
    glfwSetInputMode(window, GLFW_CURSOR, sMouseVisible ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED);
    glfwSetKeyCallback(window, keyCallback);
    glfwSetCursorPosCallback(window, mouseCallback);
    glfwSetScrollCallback(window, scrollCallback);
    glfwSetMouseButtonCallback(window, mouseButtonCallback);
    glfwSetCharCallback(window, charCallback);
    glfwSetWindowSizeCallback(window, windowSizeCallback);

    glm::vec3 quad[] = {
        glm::vec3(-1.0f, -1.0f, 0.0f),
        glm::vec3(-1.0f, 1.0f, 0.0f),
        glm::vec3(1.0f, 1.0f, 0.0f),
        glm::vec3(-1.0f, -1.0f, 0.0f),
        glm::vec3(1.0f, 1.0f, 0.0f),
        glm::vec3(1.0f, -1.0f, 0.0f)
    };
    GLuint VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW);

    GLuint VAO;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);
    {
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), static_cast<GLvoid*>(0));
        glEnableVertexAttribArray(0);
    }

    program prog;
    CHECK(prog.create(), prog.lastError(), return -1;);

        // Shaders
    shader vertexShader, fragShader;
    CHECK(vertexShader.compile(readAllText("shaders/simple.vert"), GL_VERTEX_SHADER), vertexShader.lastError(), return -1;);
    CHECK(vertexShader.compile(readAllText("shaders/form.frag"), GL_FRAGMENT_SHADER), vertexShader.lastError(), return -1;);

    prog.attach(vertexShader);
    prog.attach(fragShader);
    CHECK(prog.link(), prog.lastError(), return -1;);

    texture tex;
    CHECK(tex.load("../tex/crate.png", true), "Error loading texture", );

    std::mt19937 randGen(static_cast<std::mt19937::result_type>(std::time(nullptr)));
    std::uniform_real_distribution<float>  uniDist;
    std::exponential_distribution<float>  expDist;

    float lastTime = static_cast<float>(glfwGetTime());
    float dt{ 0.0f };
    float const dT{ 0.0125f };
        // Game Loop
    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();

        float const curTime = static_cast<float>(glfwGetTime());
        dt = curTime - lastTime;
        if (dt < dT)
            continue;
        lastTime = curTime;

        moveCamera(dt);

        glm::mat4 view;
        view = sCamera.view();
        glm::mat4 projection;
        projection = sCamera.projection();
        glm::mat4 model;
        model = glm::translate(model, sCubePos);

        prog.use();
        prog["iResolution"] = glm::vec2(sWinWidth, sWinHeight);
        prog["iGlobalTime"] = curTime;
        prog["pvm"] = projection * view * model;

        // Rendering
        glClearColor(0.1f, 0.3f, 0.5f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glBindVertexArray(0);

        //TwDraw();

        glfwSwapBuffers(window);
    }

    TwDeleteBar(sATB);
    sATB = nullptr;

    glfwTerminate();
    return 0;
}

void glfwErrorReporting(int errCode, char const* msg)
{
    std::cerr << "ERROR " << errCode << ": " << msg << std::endl;
}

void keyCallback(GLFWwindow* window, int key, int scancode, int action, int modifiers)
{
    if (TwEventKeyGLFW(key, action))
        return;
    if (action == GLFW_PRESS)
        sKeys[key] = true;
    if (action == GLFW_RELEASE)
        sKeys[key] = false;

    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
    else if ((key == GLFW_KEY_LEFT_ALT || key == GLFW_KEY_RIGHT_ALT) && action == GLFW_PRESS)
    {
        sMouseVisible = !sMouseVisible;
        glfwSetInputMode(window, GLFW_CURSOR, sMouseVisible ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED);
    }
}

void mouseCallback(GLFWwindow* window, double x, double y)
{
    float const xFloat = static_cast<GLfloat>(x);
    float const yFloat = static_cast<GLfloat>(y);
    static GLfloat lastX = xFloat, lastY = yFloat;

    if (sMouseVisible)
    {
        lastX = xFloat;
        lastY = yFloat;
        TwEventMousePosGLFW(static_cast<int>(x), static_cast<int>(y));
        return;
    }

    GLfloat xDiff = xFloat - lastX;
    GLfloat yDiff = yFloat - lastY;
    lastX = xFloat;
    lastY = yFloat;
    GLfloat const sensitivity = 0.08f;
    xDiff *= sensitivity;
    yDiff *= sensitivity;

    sYaw += xDiff;
    sPitch = glm::clamp(sPitch - yDiff, -89.0f, 89.0f);
}

void scrollCallback(GLFWwindow* window, double xDiff, double yDiff)
{
    if (TwEventMouseWheelGLFW(static_cast<int>(yDiff)))
        return;
    sCamera.fov(sCamera.fov() - static_cast<float>(yDiff));
}

void mouseButtonCallback(GLFWwindow* window, int button, int action, int modifiers)
{
    TwEventMouseButtonGLFW(button, action);
}

void charCallback(GLFWwindow* window, unsigned int symb)
{
    TwEventCharGLFW(symb, GLFW_PRESS);
}

void windowSizeCallback(GLFWwindow* window, int sizeX, int sizeY)
{
    sWinWidth = sizeX;
    sWinHeight = sizeY;
    glViewport(0, 0, sWinWidth, sWinHeight);
    TwWindowSize(sWinWidth, sWinHeight);
}

void moveCamera(float dt)
{
    if (sMouseVisible)
        return;
    GLfloat cameraSpeed = 50.0f * dt;
    auto camPos = sCamera.pos();
    /*if (sKeys[GLFW_KEY_W])
        camPos += cameraSpeed * sCamera.front();
    if (sKeys[GLFW_KEY_S])
        camPos -= cameraSpeed * sCamera.front();*/
    if (sKeys[GLFW_KEY_A])
        camPos -= glm::normalize(glm::cross(sCamera.front(), sCamera.up())) * cameraSpeed;
    if (sKeys[GLFW_KEY_D])
        camPos += glm::normalize(glm::cross(sCamera.front(), sCamera.up())) * cameraSpeed;
    if (sKeys[GLFW_KEY_W] || sKeys[GLFW_KEY_SPACE])
        camPos += glm::normalize(sCamera.up()) * cameraSpeed;
    if (sKeys[GLFW_KEY_S] || sKeys[GLFW_KEY_LEFT_SHIFT] || sKeys[GLFW_KEY_RIGHT_SHIFT])
        camPos -= glm::normalize(sCamera.up()) * cameraSpeed;
    //sCamera.pos(camPos);
    glm::vec3 const toCube = sCubePos - sCamera.pos();
    glm::vec3 const wishToCube = toCube / glm::length(toCube) * 10.0f;
    glm::vec3 const shiftPos = toCube - wishToCube;
    sCamera.pos(camPos + shiftPos);
    sCamera.front(sCubePos - sCamera.pos());
    glm::vec3 const right = glm::normalize(glm::cross(sCamera.up(), sCamera.front()));
    sCamera.up(glm::normalize(glm::cross(sCamera.front(), right)));
    //sCamera.front(sPitch, sYaw);
}
<commit_msg>rotating the object instead of moving camera<commit_after>#include "visual.h"
#include <array>
#include <ctime>
#include <iostream>
#include <list>
#include <random>
#include <stdlib.h>
#include <stdio.h>
#include <vector>

#include <AntTweakBar.h>

#define GLEW_STATIC
#include <GL/glew.h>
#include <GLFW/glfw3.h>

#include <glm/glm.hpp>
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
#include <glm/gtx/rotate_vector.hpp>

#include "camera/camera.h"
#include "shaders/program.h"
#include "shaders/shader.h"
#include "textures/texture.h"
#include "util/checked_call.h"

static size_t sWinWidth = 1280;
static size_t sWinHeight = 800;
static bool sMouseVisible{ false };
glm::vec3 const sCubePos(0.0f, 0.0f, -15.0f);
glm::vec3 sRotAngles;

static camera sCamera(sWinWidth, sWinHeight);
static std::vector<bool> sKeys(GLFW_KEY_LAST, false);
static float sStep = 1.0f;

static TwBar* sATB{ nullptr };

static void glfwErrorReporting(int errCode, char const* msg);
static void keyCallback(GLFWwindow* window, int key, int scancode, int action, int modifiers);
static void mouseCallback(GLFWwindow* window, double x, double y);
static void scrollCallback(GLFWwindow* window, double xDiff, double yDiff);
static void mouseButtonCallback(GLFWwindow* window, int button, int action, int modifiers);
static void charCallback(GLFWwindow* window, unsigned int symb);
static void windowSizeCallback(GLFWwindow* window, int sizeX, int sizeY);
static void moveCamera(float dt);

int runVisual()
{
    sCamera.fov(90);
    CHECK(GL_FALSE != glfwInit(), "GLFW init failed", return -1;);
        // Provide some hints for the GLFW
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_RESIZABLE, GL_TRUE);

    glfwSetErrorCallback(glfwErrorReporting);

        // Create a window
    GLFWwindow* window = glfwCreateWindow(sWinWidth, sWinHeight, "Renderize", nullptr, nullptr);
    CHECK(window, "Error creating window", { glfwTerminate(); return -1; });
    glfwMakeContextCurrent(window);

    if (TwInit(TW_OPENGL_CORE, NULL))
    {
        TwWindowSize(sWinWidth, sWinHeight);
        sATB = TwNewBar("Tweak");
        TwAddVarRW(sATB, "step", TW_TYPE_FLOAT, &sStep, " label='Step' step=0.1 ");
    }
    else
        std::cerr << TwGetLastError() << std::endl;

        // Initialize Glew
    glewExperimental = GL_TRUE;
    GLenum glewCode = glewInit();
    CHECK(GLEW_OK == glewCode, "Failed to initialize GLEW: ",
        std::cerr << glewGetErrorString(glewCode) << std::endl; return -1;);

    glViewport(0, 0, sWinWidth, sWinHeight);
    glEnable(GL_DEPTH_TEST);

    // Initialize some GLFW callbacks
    glfwSetInputMode(window, GLFW_CURSOR, sMouseVisible ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED);
    glfwSetKeyCallback(window, keyCallback);
    glfwSetCursorPosCallback(window, mouseCallback);
    glfwSetScrollCallback(window, scrollCallback);
    glfwSetMouseButtonCallback(window, mouseButtonCallback);
    glfwSetCharCallback(window, charCallback);
    glfwSetWindowSizeCallback(window, windowSizeCallback);

    glm::vec3 quad[] = {
        glm::vec3(-1.0f, -1.0f, 0.0f),
        glm::vec3(-1.0f, 1.0f, 0.0f),
        glm::vec3(1.0f, 1.0f, 0.0f),
        glm::vec3(-1.0f, -1.0f, 0.0f),
        glm::vec3(1.0f, 1.0f, 0.0f),
        glm::vec3(1.0f, -1.0f, 0.0f)
    };
    GLuint VBO;
    glGenBuffers(1, &VBO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(quad), quad, GL_STATIC_DRAW);

    GLuint VAO;
    glGenVertexArrays(1, &VAO);
    glBindVertexArray(VAO);
    {
        glBindBuffer(GL_ARRAY_BUFFER, VBO);
        glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 3 * sizeof(GLfloat), static_cast<GLvoid*>(0));
        glEnableVertexAttribArray(0);
    }

    program prog;
    CHECK(prog.create(), prog.lastError(), return -1;);

        // Shaders
    shader vertexShader, fragShader;
    CHECK(vertexShader.compile(readAllText("shaders/simple.vert"), GL_VERTEX_SHADER), vertexShader.lastError(), return -1;);
    CHECK(vertexShader.compile(readAllText("shaders/form.frag"), GL_FRAGMENT_SHADER), vertexShader.lastError(), return -1;);

    prog.attach(vertexShader);
    prog.attach(fragShader);
    CHECK(prog.link(), prog.lastError(), return -1;);

    texture tex;
    CHECK(tex.load("../tex/crate.png", true), "Error loading texture", );

    std::mt19937 randGen(static_cast<std::mt19937::result_type>(std::time(nullptr)));
    std::uniform_real_distribution<float>  uniDist;
    std::exponential_distribution<float>  expDist;

    float lastTime = static_cast<float>(glfwGetTime());
    float dt{ 0.0f };
    float const dT{ 0.0125f };
        // Game Loop
    while (!glfwWindowShouldClose(window))
    {
        glfwPollEvents();

        float const curTime = static_cast<float>(glfwGetTime());
        dt = curTime - lastTime;
        if (dt < dT)
            continue;
        lastTime = curTime;

        moveCamera(dt);

        glm::mat4 view;
        view = sCamera.view();
        glm::mat4 projection;
        projection = sCamera.projection();
        glm::mat4 model;
        model = glm::translate(model, sCubePos);
        model = glm::rotate(model, glm::radians(sRotAngles.x), glm::vec3(1.0f, 0.0f, 0.0f));
        model = glm::rotate(model, glm::radians(sRotAngles.y), glm::vec3(0.0f, 1.0f, 0.0f));
        model = glm::rotate(model, glm::radians(sRotAngles.z), glm::vec3(0.0f, 0.0f, 1.0f));

        prog.use();
        prog["iResolution"] = glm::vec2(sWinWidth, sWinHeight);
        prog["iGlobalTime"] = curTime;
        prog["pvm"] = projection * view * model;

        // Rendering
        glClearColor(0.1f, 0.3f, 0.5f, 1.0f);
        glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

        glBindVertexArray(VAO);
        glDrawArrays(GL_TRIANGLES, 0, 6);
        glBindVertexArray(0);

        //TwDraw();

        glfwSwapBuffers(window);
    }

    TwDeleteBar(sATB);
    sATB = nullptr;

    glfwTerminate();
    return 0;
}

void glfwErrorReporting(int errCode, char const* msg)
{
    std::cerr << "ERROR " << errCode << ": " << msg << std::endl;
}

void keyCallback(GLFWwindow* window, int key, int scancode, int action, int modifiers)
{
    if (TwEventKeyGLFW(key, action))
        return;
    if (action == GLFW_PRESS)
        sKeys[key] = true;
    if (action == GLFW_RELEASE)
        sKeys[key] = false;

    if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS)
        glfwSetWindowShouldClose(window, GL_TRUE);
    else if ((key == GLFW_KEY_LEFT_ALT || key == GLFW_KEY_RIGHT_ALT) && action == GLFW_PRESS)
    {
        sMouseVisible = !sMouseVisible;
        glfwSetInputMode(window, GLFW_CURSOR, sMouseVisible ? GLFW_CURSOR_NORMAL : GLFW_CURSOR_DISABLED);
    }
}

void mouseCallback(GLFWwindow* window, double x, double y)
{
    float const xFloat = static_cast<GLfloat>(x);
    float const yFloat = static_cast<GLfloat>(y);
    static GLfloat lastX = xFloat, lastY = yFloat;

    if (sMouseVisible)
    {
        lastX = xFloat;
        lastY = yFloat;
        TwEventMousePosGLFW(static_cast<int>(x), static_cast<int>(y));
        return;
    }

    GLfloat xDiff = xFloat - lastX;
    GLfloat yDiff = yFloat - lastY;
    lastX = xFloat;
    lastY = yFloat;
    GLfloat const sensitivity = 0.08f;
    xDiff *= sensitivity;
    yDiff *= sensitivity;
}

void scrollCallback(GLFWwindow* window, double xDiff, double yDiff)
{
    if (TwEventMouseWheelGLFW(static_cast<int>(yDiff)))
        return;
    sCamera.fov(sCamera.fov() - static_cast<float>(yDiff));
}

void mouseButtonCallback(GLFWwindow* window, int button, int action, int modifiers)
{
    TwEventMouseButtonGLFW(button, action);
}

void charCallback(GLFWwindow* window, unsigned int symb)
{
    TwEventCharGLFW(symb, GLFW_PRESS);
}

void windowSizeCallback(GLFWwindow* window, int sizeX, int sizeY)
{
    sWinWidth = sizeX;
    sWinHeight = sizeY;
    glViewport(0, 0, sWinWidth, sWinHeight);
    TwWindowSize(sWinWidth, sWinHeight);
}

void moveCamera(float dt)
{
    if (sMouseVisible)
        return;
    float const rotAngle = 180.0f * dt;
    if (sKeys[GLFW_KEY_W])
        sRotAngles.x += rotAngle;
    if (sKeys[GLFW_KEY_S])
        sRotAngles.x -= rotAngle;
    if (sKeys[GLFW_KEY_A])
        sRotAngles.y -= rotAngle;
    if (sKeys[GLFW_KEY_D])
        sRotAngles.y += rotAngle;
    if (sKeys[GLFW_KEY_SPACE])
        sRotAngles.z += rotAngle;
    if (sKeys[GLFW_KEY_LEFT_SHIFT] || sKeys[GLFW_KEY_RIGHT_SHIFT])
        sRotAngles.z -= rotAngle;
}
<|endoftext|>


<commit_before>#include "internal.hpp"
#include "macros.hpp"
#include "message.hpp"

namespace CaDiCaL {

// Vivification is a special case of asymmetric tautology elimination.  It
// strengthens and removes irredundant clauses proven redundant through unit
// propagation.  The original algorithm is due to a paper by Piette, Hamadi
// published at ECAI'08.  We have an inprocessing version, e.g., it does not
// necessarily run-to-completion.  It does no conflict analysis and uses a
// new heuristic for selecting clauses to vivify.

/*------------------------------------------------------------------------*/

struct ClauseScore {
  Clause * clause;
  double score;
  ClauseScore (Clause * c) : clause (c), score (0) { }
};

struct less_clause_score {
  bool operator () (const ClauseScore & a, const ClauseScore & b) const {
    return a.score < b.score;
  }
};

// Check whether negated literal occurs less often.
//
struct less_negated_noccs2 {
  Internal * internal;
  less_negated_noccs2 (Internal * i) : internal (i) { }
  bool operator () (int a, int b) {
    long u = internal->noccs2 (-a), v = internal->noccs2 (-b);
    if (u < v) return true;
    if (u > v) return false;
    int i = abs (a), j = abs (b);
    if (i < j) return true;
    if (i > j) return false;
    return a < b;
  }
};

/*------------------------------------------------------------------------*/

void Internal::vivify () {

  assert (opts.vivify);

  SWITCH_AND_START (search, simplify, vivify);

  assert (!vivifying);
  vivifying = true;

  stats.vivifications++;
  if (level) backtrack ();

  // Refill the schedule every time.  Unchecked clauses are 'saved' by
  // setting their 'vivify' bit, such that they can be tried next time.
  //
  vector<ClauseScore> schedule;

  const const_clause_iterator end = clauses.end ();
  const_clause_iterator i;

  // After an arithmetic increasing number of calls to 'vivify' we
  // reschedule all clauses, instead of only those not tried before.  Then
  // this limit is increased by one. The argument is that we should focus on
  // clauses with many occurrences of their negated literals (also long
  // clauses), but in the limit eventually still should vivify all clauses.
  //
  bool reschedule_all = !lim.vivify_wait_reschedule;
  if (reschedule_all) {
    VRB ("vivify", stats.vivifications,
      "forced to reschedule all clauses");
    lim.vivify_wait_reschedule = ++inc.vivify_wait_reschedule;
  } else lim.vivify_wait_reschedule--;

  // In the first round check whether there are still clauses left, which
  // are scheduled to but have not been vivified yet.  In the second round
  // if no such clauses are found in the first round.  This is also
  // performed if rescheduling is forced because 'reschedule_all' is  true.
  //
  for (int round = 0; schedule.empty () && round <= 1; round++) {
    for (i = clauses.begin (); i != end; i++) {
      Clause * c = *i;
      if (c->garbage) continue;
      if (c->redundant) continue;
      if (c->size == 2) continue;       // see also [NO-BINARY] below
      if (!reschedule_all && !round && !c->vivify) continue;
      schedule.push_back (c);
      c->vivify = true;
    }
  }
  shrink_vector (schedule);

  // Count the number of occurrences of literals in all irredundant clauses,
  // particularly the irredundant binary clauses, responsible for most of
  // the propagation usually.
  //
  init_noccs2 ();

  for (i = clauses.begin (); i != end; i++) {
    Clause * c = *i;
    if (c->garbage) continue;
    if (c->redundant) continue;

    // Compute score as 'pow (2, -c->size)' without 'math.h' (it actually
    // could be faster even, since second argument is always an integer).
    // This is the same score the Jeroslow-Wang heuristic would give.
    //
    double base = 0.5, score = 0.25;
    for (int n = c->size - 2; n; n >>= 1) {
      if (n & 1) score *= base;
      base *= base;
    }

    const const_literal_iterator eoc = c->end ();
    const_literal_iterator j;
    for (j = c->begin (); j != eoc; j++)
      noccs2 (*j) += score;
  }

  // Then update the score of the candidate clauses by adding up the number
  // of occurrences of the negation of its literals.
  //
  const vector<ClauseScore>::const_iterator eos = schedule.end ();
  vector<ClauseScore>::iterator k;

  for (k = schedule.begin (); k != eos; k++) {
    ClauseScore & cs = *k;
    const const_literal_iterator eoc = cs.clause->end ();
    const_literal_iterator j;
    long score = 0;
    for (j = cs.clause->begin (); j != eoc; j++)
      score += noccs2 (-*j);
    cs.score = score;
  }

  // Now sort candidates, with best clause (many negative occurrences) last.
  //
  stable_sort (schedule.begin (), schedule.end (), less_clause_score ());

  long scheduled = schedule.size ();
  VRB ("vivify", stats.vivifications,
    "scheduled %ld clauses to be vivified %.0f%%",
    scheduled, percent (scheduled, stats.irredundant));

  // We need to make sure to propagate only over irredundant clauses.
  //
  flush_redundant_watches ();
  size_t old_propagated = propagated;   // see [RE-PROPAGATE] below.

  // Counters, for what happened.
  //
  long checked = 0, subsumed = 0, strengthened = 0, units = 0;

  // Temporarily save and sort the candidate clause literals here.
  //
  vector<int> sorted;

  // Limit the number of propagations during vivification as in 'probe'.
  //
  long delta = opts.vivifyreleff * stats.propagations.search;
  if (delta < opts.vivifymineff) delta = opts.vivifymineff;
  if (delta > opts.vivifymaxeff) delta = opts.vivifymaxeff;
  long limit = stats.propagations.vivify + delta;

  while (!unsat &&
         !schedule.empty () &&
         stats.propagations.vivify < limit) {

    // Next candidate clause to vivify.
    //
    Clause * c = schedule.back ().clause;
    schedule.pop_back ();
    assert (c->vivify);
    c->vivify = false;

    assert (!c->garbage);
    assert (!c->redundant);
    assert (c->size > 2);               // see [NO-BINARY] above
    assert (!level);

    // First check whether it is already satisfied.
    //
    const const_literal_iterator eoc = c->end ();
    const_literal_iterator j;
    bool satisfied = false;

    sorted.clear ();

    for (j = c->begin (); !satisfied && j != eoc; j++) {
      const int lit = *j, tmp = val (lit);
      if (tmp > 0) satisfied = true;
      else if (!tmp) sorted.push_back (lit);
    }

    if (satisfied) { mark_garbage (c); continue; }

    // The actual vivification checking is performed here, by assuming the
    // negation of each of the remaining literals of the clause in turn and
    // propagating it.  If a conflict occurs or another literal in the
    // clause becomes assigned during propagation, we can stop.
    //
    LOG (c, "vivification checking");
    checked++;

    // Sort the literals of the candidate with respect to the largest number
    // of negative occurrences.  The idea is that more negative occurrences
    // lead to more propagations and thus potentially higher earlier effect.
    //
    sort (sorted.begin (), sorted.end (), less_negated_noccs2 (this));

    // Make sure to ignore this clause during propagation.  This is not that
    // easy for binary clauses [NO-BINARY], e.g., ignoring binary clauses,
    // without changing 'propagate' and actually we also do not want to
    // remove binary clauses which are subsumed.  Those are hyper binary
    // resolvents and should be kept as learned clauses instead unless they
    // are transitive in the binary implication graph (TODO).
    //
    c->ignore = true;           // see also [NO-BINARY] above

    bool redundant = false;     // determined to be redundant / subsumed
    int remove = 0;             // at least literal 'remove' can be removed

    while (!redundant && !remove && !sorted.empty ()) {
      const int lit = sorted.back (), tmp = val (lit);
      sorted.pop_back ();
      if (tmp > 0) {
        LOG ("redundant since literal %d already true", lit);
        redundant = true;
      } else if (tmp < 0) {
        LOG ("removing at least literal %d which is already false", lit);
        remove = lit;
      } else {
        assume_decision (-lit);
        if (propagate ()) continue;
        LOG ("redundant since propagation produced conflict");
        redundant = true;
        conflict = 0;
      }
    }

    if (redundant) {
REDUNDANT:
      subsumed++;
      LOG (c, "redundant asymmetric tautology");
      mark_garbage (c);
    } else if (remove) {
      assert (level);
      assert (clause.empty ());
#ifndef NDEBUG
      bool found = false;
#endif
      // There might be other literals implied to false (or even root level
      // falsified).  Those should be removed in addition to 'remove'.  It
      // might further be possible that a latter to be assumed literal is
      // already forced to true in which case the clause is actually
      // redundant (we solved this by bad style 'goto' programming).
      //
      for (j = c->begin (); j != eoc; j++) {
        const int other = *j, tmp = val (other);
        Var & v = var (other);
        if (tmp > 0) {
          LOG ("redundant since literal %d already true", other);
          clause.clear ();
          goto REDUNDANT;
        }
        if (tmp < 0 && !v.level) continue;
        if (tmp < 0 && v.level && v.reason) {
          assert (v.level);
          assert (v.reason);
          LOG ("flushing literal %d", other);
          mark_removed (other);
#ifndef NDEBUG
          if (other == remove) found = true;
#endif
        } else clause.push_back (other);
      }

      // TODO: do we want to assume the remaining literals and propagate
      // them to see whether this clause is actually redundant.  Then there
      // would be no point in strengthening it?

      strengthened++; // only now because of 'goto REDUNDANT' above

      assert (found);
      assert (!clause.empty ());
      backtrack ();
      if (clause.size () == 1) {
        const int unit = clause[0];
        LOG (c, "vivification shrunken to unit %d", unit);
        assert (!val (unit));
        assign_unit (unit);
        units++;
        bool ok = propagate ();
        if (!ok) learn_empty_clause ();
      } else {
#ifdef LOGGING
        Clause * d =
#endif
        new_clause_as (c);
        LOG (c, "before vivification");
        LOG (d, "after vivification");
      }
      clause.clear ();
      mark_garbage (c);
    }
    if (level) backtrack ();
    c->ignore = false;
  }

  if (!unsat) {

    erase_vector (sorted);
    reset_noccs2 ();
    erase_vector (schedule);
    disconnect_watches ();
    connect_watches ();

    // [RE-PROPAGATE] Since redundant clause were disconnected during
    // propagating vivified units above, we have propagate all those fixed
    // literals again after connecting the redundant clauses back.
    // Otherwise, the invariants for watching and blocking literals break.
    //
    if (old_propagated < propagated) {
      propagated = old_propagated;
      if (!propagate ()) {
        LOG ("propagating vivified units leads to conflict");
        learn_empty_clause ();
      }
    }
  }

  VRB ("vivify", stats.vivifications,
    "checked %ld clauses %.02f%% out of scheduled",
    checked, percent (checked, scheduled));
  if (units)
  VRB ("vivify", stats.vivifications,
    "found %ld units %.02f%% out of checked",
    units, percent (units, checked));
  VRB ("vivify", stats.vivifications,
    "subsumed %ld clauses %.02f%% out of checked",
    subsumed, percent (subsumed, checked));
  VRB ("vivify", stats.vivifications,
    "strengthened %ld clauses %.02f%% out of checked",
    strengthened, percent (strengthened, checked));

  stats.vivifychecks += checked;
  stats.vivifysubs += subsumed;
  stats.vivifystrs += strengthened;
  stats.vivifyunits += units;

  stats.subsumed += subsumed;
  stats.strengthened += strengthened;

  assert (vivifying);
  vivifying = false;

  report ('v');
  STOP_AND_SWITCH (vivify, simplify, search);
}

};
<commit_msg>removed todo<commit_after>#include "internal.hpp"
#include "macros.hpp"
#include "message.hpp"

namespace CaDiCaL {

// Vivification is a special case of asymmetric tautology elimination.  It
// strengthens and removes irredundant clauses proven redundant through unit
// propagation.  The original algorithm is due to a paper by Piette, Hamadi
// published at ECAI'08.  We have an inprocessing version, e.g., it does not
// necessarily run-to-completion.  It does no conflict analysis and uses a
// new heuristic for selecting clauses to vivify.

/*------------------------------------------------------------------------*/

struct ClauseScore {
  Clause * clause;
  double score;
  ClauseScore (Clause * c) : clause (c), score (0) { }
};

struct less_clause_score {
  bool operator () (const ClauseScore & a, const ClauseScore & b) const {
    return a.score < b.score;
  }
};

// Check whether negated literal occurs less often.
//
struct less_negated_noccs2 {
  Internal * internal;
  less_negated_noccs2 (Internal * i) : internal (i) { }
  bool operator () (int a, int b) {
    long u = internal->noccs2 (-a), v = internal->noccs2 (-b);
    if (u < v) return true;
    if (u > v) return false;
    int i = abs (a), j = abs (b);
    if (i < j) return true;
    if (i > j) return false;
    return a < b;
  }
};

/*------------------------------------------------------------------------*/

void Internal::vivify () {

  assert (opts.vivify);

  SWITCH_AND_START (search, simplify, vivify);

  assert (!vivifying);
  vivifying = true;

  stats.vivifications++;
  if (level) backtrack ();

  // Refill the schedule every time.  Unchecked clauses are 'saved' by
  // setting their 'vivify' bit, such that they can be tried next time.
  //
  vector<ClauseScore> schedule;

  const const_clause_iterator end = clauses.end ();
  const_clause_iterator i;

  // After an arithmetic increasing number of calls to 'vivify' we
  // reschedule all clauses, instead of only those not tried before.  Then
  // this limit is increased by one. The argument is that we should focus on
  // clauses with many occurrences of their negated literals (also long
  // clauses), but in the limit eventually still should vivify all clauses.
  //
  bool reschedule_all = !lim.vivify_wait_reschedule;
  if (reschedule_all) {
    VRB ("vivify", stats.vivifications,
      "forced to reschedule all clauses");
    lim.vivify_wait_reschedule = ++inc.vivify_wait_reschedule;
  } else lim.vivify_wait_reschedule--;

  // In the first round check whether there are still clauses left, which
  // are scheduled to but have not been vivified yet.  In the second round
  // if no such clauses are found in the first round.  This is also
  // performed if rescheduling is forced because 'reschedule_all' is  true.
  //
  for (int round = 0; schedule.empty () && round <= 1; round++) {
    for (i = clauses.begin (); i != end; i++) {
      Clause * c = *i;
      if (c->garbage) continue;
      if (c->redundant) continue;
      if (c->size == 2) continue;       // see also [NO-BINARY] below
      if (!reschedule_all && !round && !c->vivify) continue;
      schedule.push_back (c);
      c->vivify = true;
    }
  }
  shrink_vector (schedule);

  // Count the number of occurrences of literals in all irredundant clauses,
  // particularly the irredundant binary clauses, responsible for most of
  // the propagation usually.
  //
  init_noccs2 ();

  for (i = clauses.begin (); i != end; i++) {
    Clause * c = *i;
    if (c->garbage) continue;
    if (c->redundant) continue;

    // Compute score as 'pow (2, -c->size)' without 'math.h' (it actually
    // could be faster even, since second argument is always an integer).
    // This is the same score the Jeroslow-Wang heuristic would give.
    //
    double base = 0.5, score = 0.25;
    for (int n = c->size - 2; n; n >>= 1) {
      if (n & 1) score *= base;
      base *= base;
    }

    const const_literal_iterator eoc = c->end ();
    const_literal_iterator j;
    for (j = c->begin (); j != eoc; j++)
      noccs2 (*j) += score;
  }

  // Then update the score of the candidate clauses by adding up the number
  // of occurrences of the negation of its literals.
  //
  const vector<ClauseScore>::const_iterator eos = schedule.end ();
  vector<ClauseScore>::iterator k;

  for (k = schedule.begin (); k != eos; k++) {
    ClauseScore & cs = *k;
    const const_literal_iterator eoc = cs.clause->end ();
    const_literal_iterator j;
    long score = 0;
    for (j = cs.clause->begin (); j != eoc; j++)
      score += noccs2 (-*j);
    cs.score = score;
  }

  // Now sort candidates, with best clause (many negative occurrences) last.
  //
  stable_sort (schedule.begin (), schedule.end (), less_clause_score ());

  long scheduled = schedule.size ();
  VRB ("vivify", stats.vivifications,
    "scheduled %ld clauses to be vivified %.0f%%",
    scheduled, percent (scheduled, stats.irredundant));

  // We need to make sure to propagate only over irredundant clauses.
  //
  flush_redundant_watches ();
  size_t old_propagated = propagated;   // see [RE-PROPAGATE] below.

  // Counters, for what happened.
  //
  long checked = 0, subsumed = 0, strengthened = 0, units = 0;

  // Temporarily save and sort the candidate clause literals here.
  //
  vector<int> sorted;

  // Limit the number of propagations during vivification as in 'probe'.
  //
  long delta = opts.vivifyreleff * stats.propagations.search;
  if (delta < opts.vivifymineff) delta = opts.vivifymineff;
  if (delta > opts.vivifymaxeff) delta = opts.vivifymaxeff;
  long limit = stats.propagations.vivify + delta;

  while (!unsat &&
         !schedule.empty () &&
         stats.propagations.vivify < limit) {

    // Next candidate clause to vivify.
    //
    Clause * c = schedule.back ().clause;
    schedule.pop_back ();
    assert (c->vivify);
    c->vivify = false;

    assert (!c->garbage);
    assert (!c->redundant);
    assert (c->size > 2);               // see [NO-BINARY] above
    assert (!level);

    // First check whether it is already satisfied.
    //
    const const_literal_iterator eoc = c->end ();
    const_literal_iterator j;
    bool satisfied = false;

    sorted.clear ();

    for (j = c->begin (); !satisfied && j != eoc; j++) {
      const int lit = *j, tmp = val (lit);
      if (tmp > 0) satisfied = true;
      else if (!tmp) sorted.push_back (lit);
    }

    if (satisfied) { mark_garbage (c); continue; }

    // The actual vivification checking is performed here, by assuming the
    // negation of each of the remaining literals of the clause in turn and
    // propagating it.  If a conflict occurs or another literal in the
    // clause becomes assigned during propagation, we can stop.
    //
    LOG (c, "vivification checking");
    checked++;

    // Sort the literals of the candidate with respect to the largest number
    // of negative occurrences.  The idea is that more negative occurrences
    // lead to more propagations and thus potentially higher earlier effect.
    //
    sort (sorted.begin (), sorted.end (), less_negated_noccs2 (this));

    // Make sure to ignore this clause during propagation.  This is not that
    // easy for binary clauses [NO-BINARY], e.g., ignoring binary clauses,
    // without changing 'propagate' and actually we also do not want to
    // remove binary clauses which are subsumed.  Those are hyper binary
    // resolvents and should be kept as learned clauses instead unless they
    // are transitive in the binary implication graph (TODO).
    //
    c->ignore = true;           // see also [NO-BINARY] above

    bool redundant = false;     // determined to be redundant / subsumed
    int remove = 0;             // at least literal 'remove' can be removed

    while (!redundant && !remove && !sorted.empty ()) {
      const int lit = sorted.back (), tmp = val (lit);
      sorted.pop_back ();
      if (tmp > 0) {
        LOG ("redundant since literal %d already true", lit);
        redundant = true;
      } else if (tmp < 0) {
        LOG ("removing at least literal %d which is already false", lit);
        remove = lit;
      } else {
        assume_decision (-lit);
        if (propagate ()) continue;
        LOG ("redundant since propagation produced conflict");
        redundant = true;
        conflict = 0;
      }
    }

    if (redundant) {
REDUNDANT:
      subsumed++;
      LOG (c, "redundant asymmetric tautology");
      mark_garbage (c);
    } else if (remove) {
      assert (level);
      assert (clause.empty ());
#ifndef NDEBUG
      bool found = false;
#endif
      // There might be other literals implied to false (or even root level
      // falsified).  Those should be removed in addition to 'remove'.  It
      // might further be possible that a latter to be assumed literal is
      // already forced to true in which case the clause is actually
      // redundant (we solved this by bad style 'goto' programming).
      //
      for (j = c->begin (); j != eoc; j++) {
        const int other = *j, tmp = val (other);
        Var & v = var (other);
        if (tmp > 0) {
          LOG ("redundant since literal %d already true", other);
          clause.clear ();
          goto REDUNDANT;
        }
        if (tmp < 0 && !v.level) continue;
        if (tmp < 0 && v.level && v.reason) {
          assert (v.level);
          assert (v.reason);
          LOG ("flushing literal %d", other);
          mark_removed (other);
#ifndef NDEBUG
          if (other == remove) found = true;
#endif
        } else clause.push_back (other);
      }

      // Assume remaining literals and propagate them to see whether this
      // clause is actually redundant and does not have to be strengthened.

      if (!sorted.empty ()) {

	do {
	  const int lit = sorted.back (), tmp = val (lit);
	  sorted.pop_back ();
	  if (tmp < 0) continue;
	  assert (!tmp);
	  assume_decision (-lit);
	} while (!sorted.empty ());

	if (!propagate ()) {
          LOG ("redundant since propagating rest produces conflict");
	  clause.clear ();
	  conflict = 0;
	  goto REDUNDANT;
	}

	LOG ("propagating remaining negated literals without conflict");
      }

      strengthened++; // only now because of 'goto REDUNDANT' above

      assert (found);
      assert (!clause.empty ());
      backtrack ();
      if (clause.size () == 1) {
        const int unit = clause[0];
        LOG (c, "vivification shrunken to unit %d", unit);
        assert (!val (unit));
        assign_unit (unit);
        units++;
        bool ok = propagate ();
        if (!ok) learn_empty_clause ();
      } else {
#ifdef LOGGING
        Clause * d =
#endif
        new_clause_as (c);
        LOG (c, "before vivification");
        LOG (d, "after vivification");
      }
      clause.clear ();
      mark_garbage (c);
    }
    if (level) backtrack ();
    c->ignore = false;
  }

  if (!unsat) {

    erase_vector (sorted);
    reset_noccs2 ();
    erase_vector (schedule);
    disconnect_watches ();
    connect_watches ();

    // [RE-PROPAGATE] Since redundant clause were disconnected during
    // propagating vivified units above, we have propagate all those fixed
    // literals again after connecting the redundant clauses back.
    // Otherwise, the invariants for watching and blocking literals break.
    //
    if (old_propagated < propagated) {
      propagated = old_propagated;
      if (!propagate ()) {
        LOG ("propagating vivified units leads to conflict");
        learn_empty_clause ();
      }
    }
  }

  VRB ("vivify", stats.vivifications,
    "checked %ld clauses %.02f%% out of scheduled",
    checked, percent (checked, scheduled));
  if (units)
  VRB ("vivify", stats.vivifications,
    "found %ld units %.02f%% out of checked",
    units, percent (units, checked));
  VRB ("vivify", stats.vivifications,
    "subsumed %ld clauses %.02f%% out of checked",
    subsumed, percent (subsumed, checked));
  VRB ("vivify", stats.vivifications,
    "strengthened %ld clauses %.02f%% out of checked",
    strengthened, percent (strengthened, checked));

  stats.vivifychecks += checked;
  stats.vivifysubs += subsumed;
  stats.vivifystrs += strengthened;
  stats.vivifyunits += units;

  stats.subsumed += subsumed;
  stats.strengthened += strengthened;

  assert (vivifying);
  vivifying = false;

  report ('v');
  STOP_AND_SWITCH (vivify, simplify, search);
}

};
<|endoftext|>