<commit_before>/*
 * Copyright (c) 2005-2006 The Regents of The University of Michigan
 * Copyright (c) 2013 Advanced Micro Devices, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * 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;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * 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.
 *
 * Authors: Korey Sewell
 *          Kevin Lim
 *          Steve Reinhardt
 */

#ifndef __CPU_O3_SCOREBOARD_HH__
#define __CPU_O3_SCOREBOARD_HH__

#include <iostream>
#include <utility>
#include <vector>

#include "base/trace.hh"
#include "config/the_isa.hh"
#include "cpu/o3/comm.hh"
#include "debug/Scoreboard.hh"

/**
 * Implements a simple scoreboard to track which registers are
 * ready. This class operates on the unified physical register space,
 * because the different classes of registers do not need to be distinguished.
 * Registers being part of a fixed mapping are always considered ready.
 */
class Scoreboard
{
  private:
    /** The object name, for DPRINTF.  We have to declare this
     *  explicitly because Scoreboard is not a SimObject. */
    const std::string _name;

    /** Scoreboard of physical integer registers, saying whether or not they
     *  are ready. */
    std::vector<bool> regScoreBoard;

    /** The number of actual physical registers */
    unsigned numPhysRegs;

  public:
    /** Constructs a scoreboard.
     *  @param _numPhysicalRegs Number of physical registers.
     *  @param _numMiscRegs Number of miscellaneous registers.
     */
    Scoreboard(const std::string &_my_name,
               unsigned _numPhysicalRegs);

    /** Destructor. */
    ~Scoreboard() {}

    /** Returns the name of the scoreboard. */
    std::string name() const { return _name; };

    /** Checks if the register is ready. */
    bool getReg(PhysRegIdPtr phys_reg) const
    {
        assert(phys_reg->flatIndex() < numPhysRegs);

        if (phys_reg->isFixedMapping()) {
            // Fixed mapping regs are always ready
            return true;
        }

        bool ready = regScoreBoard[phys_reg->flatIndex()];

        if (phys_reg->isZeroReg())
            assert(ready);

        return ready;
    }

    /** Sets the register as ready. */
    void setReg(PhysRegIdPtr phys_reg)
    {
        assert(phys_reg->flatIndex() < numPhysRegs);

        if (phys_reg->isFixedMapping()) {
            // Fixed mapping regs are always ready, ignore attempts to change
            // that
            return;
        }

        DPRINTF(Scoreboard, "Setting reg %i (%s) as ready\n",
                phys_reg->index(), phys_reg->className());

        regScoreBoard[phys_reg->flatIndex()] = true;
    }

    /** Sets the register as not ready. */
    void unsetReg(PhysRegIdPtr phys_reg)
    {
        assert(phys_reg->flatIndex() < numPhysRegs);

        if (phys_reg->isFixedMapping()) {
            // Fixed mapping regs are always ready, ignore attempts to
            // change that
            return;
        }

        // zero reg should never be marked unready
        if (phys_reg->isZeroReg())
            return;

        regScoreBoard[phys_reg->flatIndex()] = false;
    }

};

#endif
<commit_msg>cpu-o3: Add M5_VAR_USED to variable<commit_after>/*
 * Copyright (c) 2005-2006 The Regents of The University of Michigan
 * Copyright (c) 2013 Advanced Micro Devices, Inc.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * 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;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * 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.
 *
 * Authors: Korey Sewell
 *          Kevin Lim
 *          Steve Reinhardt
 */

#ifndef __CPU_O3_SCOREBOARD_HH__
#define __CPU_O3_SCOREBOARD_HH__

#include <iostream>
#include <utility>
#include <vector>

#include "base/trace.hh"
#include "config/the_isa.hh"
#include "cpu/o3/comm.hh"
#include "debug/Scoreboard.hh"

/**
 * Implements a simple scoreboard to track which registers are
 * ready. This class operates on the unified physical register space,
 * because the different classes of registers do not need to be distinguished.
 * Registers being part of a fixed mapping are always considered ready.
 */
class Scoreboard
{
  private:
    /** The object name, for DPRINTF.  We have to declare this
     *  explicitly because Scoreboard is not a SimObject. */
    const std::string _name;

    /** Scoreboard of physical integer registers, saying whether or not they
     *  are ready. */
    std::vector<bool> regScoreBoard;

    /** The number of actual physical registers */
    unsigned M5_CLASS_VAR_USED numPhysRegs;

  public:
    /** Constructs a scoreboard.
     *  @param _numPhysicalRegs Number of physical registers.
     *  @param _numMiscRegs Number of miscellaneous registers.
     */
    Scoreboard(const std::string &_my_name,
               unsigned _numPhysicalRegs);

    /** Destructor. */
    ~Scoreboard() {}

    /** Returns the name of the scoreboard. */
    std::string name() const { return _name; };

    /** Checks if the register is ready. */
    bool getReg(PhysRegIdPtr phys_reg) const
    {
        assert(phys_reg->flatIndex() < numPhysRegs);

        if (phys_reg->isFixedMapping()) {
            // Fixed mapping regs are always ready
            return true;
        }

        bool ready = regScoreBoard[phys_reg->flatIndex()];

        if (phys_reg->isZeroReg())
            assert(ready);

        return ready;
    }

    /** Sets the register as ready. */
    void setReg(PhysRegIdPtr phys_reg)
    {
        assert(phys_reg->flatIndex() < numPhysRegs);

        if (phys_reg->isFixedMapping()) {
            // Fixed mapping regs are always ready, ignore attempts to change
            // that
            return;
        }

        DPRINTF(Scoreboard, "Setting reg %i (%s) as ready\n",
                phys_reg->index(), phys_reg->className());

        regScoreBoard[phys_reg->flatIndex()] = true;
    }

    /** Sets the register as not ready. */
    void unsetReg(PhysRegIdPtr phys_reg)
    {
        assert(phys_reg->flatIndex() < numPhysRegs);

        if (phys_reg->isFixedMapping()) {
            // Fixed mapping regs are always ready, ignore attempts to
            // change that
            return;
        }

        // zero reg should never be marked unready
        if (phys_reg->isZeroReg())
            return;

        regScoreBoard[phys_reg->flatIndex()] = false;
    }

};

#endif
<|endoftext|>


<commit_before>/*
 * Copyright 2007-2020 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - 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
 * FOUNDATION 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.
 */

/*
 * Fork a process and delegate open() to it.  The subprocess returns
 * the file descriptor over a unix socket.
 */

#include "Protocol.hxx"
#include "net/ScmRightsBuilder.hxx"
#include "util/Compiler.h"

#include <stdbool.h>
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/un.h>
#include <unistd.h>

static bool
delegate_send(const void *data, size_t length)
{
	ssize_t nbytes = send(0, data, length, 0);
	if (nbytes < 0) {
		fprintf(stderr, "send() on delegate socket failed: %s\n",
			strerror(errno));
		return false;
	}

	if ((size_t)nbytes != length) {
		fprintf(stderr, "short send() on delegate socket\n");
		return false;
	}

	return true;
}

static bool
delegate_send_int(DelegateResponseCommand command, int value)
{
	const DelegateIntPacket packet = {
		.header = {
			.length = sizeof(packet) - sizeof(packet.header),
			.command = command,
		},
		.value = value,
	};

	return delegate_send(&packet, sizeof(packet));
}

static bool
delegate_send_fd(DelegateResponseCommand command, int fd)
{
	DelegateResponseHeader header = {
		.length = 0,
		.command = command,
	};
	struct iovec vec = {
		.iov_base = &header,
		.iov_len = sizeof(header),
	};

	struct msghdr msg = {
		.msg_name = nullptr,
		.msg_namelen = 0,
		.msg_iov = &vec,
		.msg_iovlen = 1,
		.msg_control = nullptr,
		.msg_controllen = 0,
		.msg_flags = 0,
	};

	ScmRightsBuilder<1> srb(msg);
	srb.push_back(fd);
	srb.Finish(msg);

	if (sendmsg(0, &msg, 0) < 0) {
		fprintf(stderr, "failed to send fd: %s\n", strerror(errno));
		return false;
	}

	return true;
}

static bool
delegate_handle_open(const char *payload)
{
	int fd = open(payload, O_RDONLY|O_CLOEXEC|O_NOCTTY);
	if (fd >= 0) {
		bool success = delegate_send_fd(DelegateResponseCommand::FD, fd);
		close(fd);
		return success;
	} else {
		/* error: send error code to client */

		return delegate_send_int(DelegateResponseCommand::ERRNO, errno);
	}
}

static bool
delegate_handle(DelegateRequestCommand command,
		const char *payload, size_t length)
{
	(void)length;

	switch (command) {
	case DelegateRequestCommand::OPEN:
		return delegate_handle_open(payload);
	}

	fprintf(stderr, "unknown command: %d\n", int(command));
	return false;
}

int main(int argc gcc_unused, char **argv gcc_unused)
{
	while (true) {
		DelegateRequestHeader header;
		ssize_t nbytes = recv(0, &header, sizeof(header), 0);
		if (nbytes < 0) {
			fprintf(stderr, "recv() on delegate socket failed: %s\n",
				strerror(errno));
			return 2;
		}

		if (nbytes == 0)
			break;

		if ((size_t)nbytes != sizeof(header)) {
			fprintf(stderr, "short recv() on delegate socket\n");
			return 2;
		}

		char payload[4096];
		if (header.length >= sizeof(payload)) {
			fprintf(stderr, "delegate payload too large\n");
			return 2;
		}

		size_t length = 0;

		while (length < header.length) {
			nbytes = recv(0, payload + length,
				      sizeof(payload) - 1 - length, 0);
			if (nbytes < 0) {
				fprintf(stderr, "recv() on delegate socket failed: %s\n",
					strerror(errno));
				return 2;
			}

			if (nbytes == 0)
				break;

			length += (size_t)nbytes;
		}

		payload[length] = 0;

		if (!delegate_handle(header.command, payload, length))
			return 2;
	}

	return 0;
}
<commit_msg>delegate/Helper: use MakeIovec()<commit_after>/*
 * Copyright 2007-2020 CM4all GmbH
 * All rights reserved.
 *
 * author: Max Kellermann <mk@cm4all.com>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * - Redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer.
 *
 * - 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
 * FOUNDATION 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.
 */

/*
 * Fork a process and delegate open() to it.  The subprocess returns
 * the file descriptor over a unix socket.
 */

#include "Protocol.hxx"
#include "net/ScmRightsBuilder.hxx"
#include "io/Iovec.hxx"
#include "util/Compiler.h"

#include <stdbool.h>
#include <sys/socket.h>
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/un.h>
#include <unistd.h>

static bool
delegate_send(const void *data, size_t length)
{
	ssize_t nbytes = send(0, data, length, 0);
	if (nbytes < 0) {
		fprintf(stderr, "send() on delegate socket failed: %s\n",
			strerror(errno));
		return false;
	}

	if ((size_t)nbytes != length) {
		fprintf(stderr, "short send() on delegate socket\n");
		return false;
	}

	return true;
}

static bool
delegate_send_int(DelegateResponseCommand command, int value)
{
	const DelegateIntPacket packet = {
		.header = {
			.length = sizeof(packet) - sizeof(packet.header),
			.command = command,
		},
		.value = value,
	};

	return delegate_send(&packet, sizeof(packet));
}

static bool
delegate_send_fd(DelegateResponseCommand command, int fd)
{
	DelegateResponseHeader header = {
		.length = 0,
		.command = command,
	};
	auto vec = MakeIovecT(header);

	struct msghdr msg = {
		.msg_name = nullptr,
		.msg_namelen = 0,
		.msg_iov = &vec,
		.msg_iovlen = 1,
		.msg_control = nullptr,
		.msg_controllen = 0,
		.msg_flags = 0,
	};

	ScmRightsBuilder<1> srb(msg);
	srb.push_back(fd);
	srb.Finish(msg);

	if (sendmsg(0, &msg, 0) < 0) {
		fprintf(stderr, "failed to send fd: %s\n", strerror(errno));
		return false;
	}

	return true;
}

static bool
delegate_handle_open(const char *payload)
{
	int fd = open(payload, O_RDONLY|O_CLOEXEC|O_NOCTTY);
	if (fd >= 0) {
		bool success = delegate_send_fd(DelegateResponseCommand::FD, fd);
		close(fd);
		return success;
	} else {
		/* error: send error code to client */

		return delegate_send_int(DelegateResponseCommand::ERRNO, errno);
	}
}

static bool
delegate_handle(DelegateRequestCommand command,
		const char *payload, size_t length)
{
	(void)length;

	switch (command) {
	case DelegateRequestCommand::OPEN:
		return delegate_handle_open(payload);
	}

	fprintf(stderr, "unknown command: %d\n", int(command));
	return false;
}

int main(int argc gcc_unused, char **argv gcc_unused)
{
	while (true) {
		DelegateRequestHeader header;
		ssize_t nbytes = recv(0, &header, sizeof(header), 0);
		if (nbytes < 0) {
			fprintf(stderr, "recv() on delegate socket failed: %s\n",
				strerror(errno));
			return 2;
		}

		if (nbytes == 0)
			break;

		if ((size_t)nbytes != sizeof(header)) {
			fprintf(stderr, "short recv() on delegate socket\n");
			return 2;
		}

		char payload[4096];
		if (header.length >= sizeof(payload)) {
			fprintf(stderr, "delegate payload too large\n");
			return 2;
		}

		size_t length = 0;

		while (length < header.length) {
			nbytes = recv(0, payload + length,
				      sizeof(payload) - 1 - length, 0);
			if (nbytes < 0) {
				fprintf(stderr, "recv() on delegate socket failed: %s\n",
					strerror(errno));
				return 2;
			}

			if (nbytes == 0)
				break;

			length += (size_t)nbytes;
		}

		payload[length] = 0;

		if (!delegate_handle(header.command, payload, length))
			return 2;
	}

	return 0;
}
<|endoftext|>


<commit_before>/*
 * main.cpp
 *
 *  Created on: Dec 9, 2014
 *      Author: bewo
 */

#include "boost/shared_ptr.hpp"

#include <geneial/algorithm/BaseGeneticAlgorithm.h>
#include <geneial/algorithm/criteria/MaxGenerationCriterion.h>
#include <geneial/algorithm/criteria/NegationDecorator.h>
#include <geneial/core/fitness/Fitness.h>
#include <geneial/core/fitness/FitnessEvaluator.h>
#include <geneial/core/population/PopulationSettings.h>
#include <geneial/core/population/builder/MultiValueBuilderSettings.h>
#include <geneial/core/population/builder/MultiIntValueChromosomeFactory.h>

//#include <geneial/core/operations/selection/FitnessProportionalSelection.h>
//#include <geneial/core/operations/selection/FitnessProportionalSelectionSettings.h>

#include <geneial/core/operations/selection/SelectionSettings.h>
#include <geneial/core/operations/selection/RouletteWheelSelection.h>
#include <geneial/core/operations/selection/UniformRandomSelection.h>

//#include <geneial/core/operations/coupling/SimpleCouplingOperation.h>
#include <geneial/core/operations/coupling/RandomCouplingOperation.h>

#include <geneial/core/operations/replacement/BaseReplacementSettings.h>

#include <geneial/core/operations/replacement/ReplaceWorstOperation.h>
#include <geneial/core/operations/replacement/ReplaceRandomOperation.h>

#include <geneial/core/operations/crossover/MultiValueChromosomeNPointCrossover.h>
#include <geneial/core/operations/crossover/MultiValueChromosomeNPointCrossoverSettings.h>

#include <geneial/core/operations/crossover/MultiValueChromosomeAverageCrossover.h>

#include <geneial/core/operations/mutation/MutationSettings.h>
#include <geneial/core/operations/mutation/NonUniformMutationOperation.h>

#include <geneial/core/operations/choosing/ChooseRandom.h>

#include <geneial/config.h>

#include <stdexcept>

using namespace GeneticLibrary;

using namespace GeneticLibrary::Algorithm;
using namespace GeneticLibrary::Algorithm::StoppingCriteria;

using namespace GeneticLibrary::Population;
using namespace GeneticLibrary::Population::Chromosome;

using namespace GeneticLibrary::Operation::Selection;
using namespace GeneticLibrary::Operation::Coupling;
using namespace GeneticLibrary::Operation::Crossover;
using namespace GeneticLibrary::Operation::Replacement;
using namespace GeneticLibrary::Operation::Mutation;
using namespace GeneticLibrary::Operation::Choosing;

class DemoChromosomeEvaluator: public FitnessEvaluator<double>{
public:
	DemoChromosomeEvaluator(){};
	Fitness<double>::ptr evaluate(const BaseChromosome<double>::ptr chromosome) const{

		MultiValueChromosome<int,double>::ptr mvc = boost::dynamic_pointer_cast<MultiValueChromosome<int,double> >(chromosome);
		if(mvc){
			//Let the fitness be the sum of all values
			return boost::shared_ptr<Fitness<double> > (new Fitness<double>(mvc->getSum()));
		}else{
			throw new std::runtime_error("Chromosome is not an Integer MultiValueChromosome with double fitness!");
		}

		boost::shared_ptr<Fitness<double> > ptr(new Fitness<double>(1));
		return ptr;
	}
};

int main(int argc, char **argv) {

	std::cout << "Running GENEIAL demo1 - Version " << GENEIAL_VERSION_MAJOR << "." << GENEIAL_VERSION_MINOR << std::endl;

	DemoChromosomeEvaluator::ptr evaluator(new DemoChromosomeEvaluator());

	//TODO (bewo): write reasonable example demo

	PopulationSettings *populationSettings = new PopulationSettings(50);

	MultiValueBuilderSettings<int,double> *builderSettings = new MultiValueBuilderSettings<int,double>(evaluator,10,130,0);

	MultiIntValueChromosomeFactory<double> *chromosomeFactory = new MultiIntValueChromosomeFactory<double>(builderSettings);

	MutationSettings* mutationSettings = new MutationSettings(0.1,0.1,5);

	ChooseRandom<int,double> *mutationChoosingOperation = new ChooseRandom<int,double>(mutationSettings);

	BaseMutationOperation<double> *mutationOperation = new NonUniformMutationOperation<int,double>(1000,0.2,mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);

	//FitnessProportionalSelectionSettings* selectionSettings = new FitnessProportionalSelectionSettings(20,10);
	SelectionSettings* selectionSettings = new SelectionSettings(10);

	//BaseSelectionOperation<double> *selectionOperation = new FitnessProportionalSelection<double>(selectionSettings);
	BaseSelectionOperation<double> *selectionOperation = new RouletteWheelSelection<double>(selectionSettings);
	//BaseSelectionOperation<double> *selectionOperation = new UniformRandomSelection<double>(selectionSettings);

	CouplingSettings *couplingSettings = new CouplingSettings(20);

	//BaseCouplingOperation<double> *couplingOperation = new SimpleCouplingOperation<double>(couplingSettings);
	BaseCouplingOperation<double> *couplingOperation = new RandomCouplingOperation<double>(couplingSettings);

	MultiValueChromosomeNPointCrossoverSettings *crossoverSettings = new MultiValueChromosomeNPointCrossoverSettings(1,MultiValueChromosomeNPointCrossoverSettings::RANDOM_WIDTH,1);
	BaseCrossoverOperation<double> *crossoverOperation = new MultiValueChromosomeNPointCrossover<int,double>(crossoverSettings,builderSettings,chromosomeFactory);
	//BaseCrossoverOperation<double> *crossoverOperation = new MultiValueChromosomeAverageCrossover<int,double>(builderSettings,chromosomeFactory);

	//BaseReplacementSettings *replacementSettings = new BaseReplacementSettings(BaseReplacementSettings::replace_offspring_mode::REPLACE_FIXED_NUMBER,20);
	BaseReplacementSettings *replacementSettings = new BaseReplacementSettings(BaseReplacementSettings::REPLACE_ALL_OFFSPRING,5,2);

	ReplaceWorstOperation<double> *replacementOperation = new ReplaceWorstOperation<double>(replacementSettings);
	//ReplaceRandomOperation<double> *replacementOperation = new ReplaceRandomOperation<double>(replacementSettings);

	BaseStoppingCriterion<double> *stoppingCriterion = new MaxGenerationCriterion<double>(100000);

	BaseGeneticAlgorithm<double> algorithm = BaseGeneticAlgorithm<double>(
			populationSettings,
			chromosomeFactory,
			stoppingCriterion,
			selectionOperation,
			couplingOperation,
			crossoverOperation,
			replacementOperation,
			mutationOperation
	);

	algorithm.solve();
	std::cout << *algorithm.getHighestFitnessChromosome() <<std::endl;
	std::cout << "end." << std::endl;

	//normally, this is not necessary because we're exiting here anyway,
	//but for valgrind's satisfaction, we free stuff nonetheless.
	delete populationSettings;
	delete chromosomeFactory;
	delete selectionOperation;
	delete selectionSettings;
	delete stoppingCriterion;
	delete couplingOperation;
	delete crossoverOperation;
	delete replacementOperation;

	delete mutationSettings;
	delete mutationChoosingOperation;
	delete mutationOperation;

}
<commit_msg>adapted demo to use continous mvc<commit_after>/*
 * main.cpp
 *
 *  Created on: Dec 9, 2014
 *      Author: bewo
 */

#include "boost/shared_ptr.hpp"

#include <geneial/algorithm/BaseGeneticAlgorithm.h>
#include <geneial/algorithm/criteria/MaxGenerationCriterion.h>
#include <geneial/algorithm/criteria/NegationDecorator.h>
#include <geneial/core/fitness/Fitness.h>
#include <geneial/core/fitness/FitnessEvaluator.h>
#include <geneial/core/population/PopulationSettings.h>

#include <geneial/core/population/builder/ContinousMultiValueBuilderSettings.h>
#include <geneial/core/population/builder/ContinousMultiIntValueChromosomeFactory.h>

//#include <geneial/core/operations/selection/FitnessProportionalSelection.h>
//#include <geneial/core/operations/selection/FitnessProportionalSelectionSettings.h>

#include <geneial/core/operations/selection/SelectionSettings.h>
#include <geneial/core/operations/selection/RouletteWheelSelection.h>
#include <geneial/core/operations/selection/UniformRandomSelection.h>

//#include <geneial/core/operations/coupling/SimpleCouplingOperation.h>
#include <geneial/core/operations/coupling/RandomCouplingOperation.h>

#include <geneial/core/operations/replacement/BaseReplacementSettings.h>

#include <geneial/core/operations/replacement/ReplaceWorstOperation.h>
#include <geneial/core/operations/replacement/ReplaceRandomOperation.h>

#include <geneial/core/operations/crossover/MultiValueChromosomeNPointCrossover.h>
#include <geneial/core/operations/crossover/MultiValueChromosomeNPointCrossoverSettings.h>

#include <geneial/core/operations/crossover/MultiValueChromosomeAverageCrossover.h>

#include <geneial/core/operations/mutation/MutationSettings.h>
#include <geneial/core/operations/mutation/NonUniformMutationOperation.h>

#include <geneial/core/operations/choosing/ChooseRandom.h>

#include <geneial/config.h>

#include <stdexcept>

using namespace GeneticLibrary;

using namespace GeneticLibrary::Algorithm;
using namespace GeneticLibrary::Algorithm::StoppingCriteria;

using namespace GeneticLibrary::Population;
using namespace GeneticLibrary::Population::Chromosome;

using namespace GeneticLibrary::Operation::Selection;
using namespace GeneticLibrary::Operation::Coupling;
using namespace GeneticLibrary::Operation::Crossover;
using namespace GeneticLibrary::Operation::Replacement;
using namespace GeneticLibrary::Operation::Mutation;
using namespace GeneticLibrary::Operation::Choosing;

class DemoChromosomeEvaluator: public FitnessEvaluator<double>{
public:
	DemoChromosomeEvaluator(){};
	Fitness<double>::ptr evaluate(const BaseChromosome<double>::ptr chromosome) const{

		MultiValueChromosome<int,double>::ptr mvc = boost::dynamic_pointer_cast<MultiValueChromosome<int,double> >(chromosome);
		if(mvc){
			//Let the fitness be the sum of all values
			return boost::shared_ptr<Fitness<double> > (new Fitness<double>(mvc->getSum()));
		}else{
			throw new std::runtime_error("Chromosome is not an Integer MultiValueChromosome with double fitness!");
		}

		boost::shared_ptr<Fitness<double> > ptr(new Fitness<double>(1));
		return ptr;
	}
};

int main(int argc, char **argv) {

	std::cout << "Running GENEIAL demo1 - Version " << GENEIAL_VERSION_MAJOR << "." << GENEIAL_VERSION_MINOR << std::endl;

	DemoChromosomeEvaluator::ptr evaluator(new DemoChromosomeEvaluator());

	//TODO (bewo): write reasonable example demo

	PopulationSettings *populationSettings = new PopulationSettings(50);

	ContinousMultiValueBuilderSettings<int,double> *builderSettings = new ContinousMultiValueBuilderSettings<int,double>(evaluator,10,130,0,true,20,5);

	ContinousMultiIntValueChromosomeFactory<double> *chromosomeFactory = new ContinousMultiIntValueChromosomeFactory<double>(builderSettings);

	MutationSettings* mutationSettings = new MutationSettings(0.1,0.1,5);

	ChooseRandom<int,double> *mutationChoosingOperation = new ChooseRandom<int,double>(mutationSettings);

	BaseMutationOperation<double> *mutationOperation = new NonUniformMutationOperation<int,double>(1000,0.2,mutationSettings, mutationChoosingOperation, builderSettings, chromosomeFactory);

	//FitnessProportionalSelectionSettings* selectionSettings = new FitnessProportionalSelectionSettings(20,10);
	SelectionSettings* selectionSettings = new SelectionSettings(10);

	//BaseSelectionOperation<double> *selectionOperation = new FitnessProportionalSelection<double>(selectionSettings);
	BaseSelectionOperation<double> *selectionOperation = new RouletteWheelSelection<double>(selectionSettings);
	//BaseSelectionOperation<double> *selectionOperation = new UniformRandomSelection<double>(selectionSettings);

	CouplingSettings *couplingSettings = new CouplingSettings(20);

	//BaseCouplingOperation<double> *couplingOperation = new SimpleCouplingOperation<double>(couplingSettings);
	BaseCouplingOperation<double> *couplingOperation = new RandomCouplingOperation<double>(couplingSettings);

	MultiValueChromosomeNPointCrossoverSettings *crossoverSettings = new MultiValueChromosomeNPointCrossoverSettings(1,MultiValueChromosomeNPointCrossoverSettings::RANDOM_WIDTH,1);
	BaseCrossoverOperation<double> *crossoverOperation = new MultiValueChromosomeNPointCrossover<int,double>(crossoverSettings,builderSettings,chromosomeFactory);
	//BaseCrossoverOperation<double> *crossoverOperation = new MultiValueChromosomeAverageCrossover<int,double>(builderSettings,chromosomeFactory);

	//BaseReplacementSettings *replacementSettings = new BaseReplacementSettings(BaseReplacementSettings::replace_offspring_mode::REPLACE_FIXED_NUMBER,20);
	BaseReplacementSettings *replacementSettings = new BaseReplacementSettings(BaseReplacementSettings::REPLACE_ALL_OFFSPRING,5,2);

	ReplaceWorstOperation<double> *replacementOperation = new ReplaceWorstOperation<double>(replacementSettings);
	//ReplaceRandomOperation<double> *replacementOperation = new ReplaceRandomOperation<double>(replacementSettings);

	BaseStoppingCriterion<double> *stoppingCriterion = new MaxGenerationCriterion<double>(100000);

	BaseGeneticAlgorithm<double> algorithm = BaseGeneticAlgorithm<double>(
			populationSettings,
			chromosomeFactory,
			stoppingCriterion,
			selectionOperation,
			couplingOperation,
			crossoverOperation,
			replacementOperation,
			mutationOperation
	);

	algorithm.solve();
	std::cout << *algorithm.getHighestFitnessChromosome() <<std::endl;
	std::cout << "end." << std::endl;

	//normally, this is not necessary because we're exiting here anyway,
	//but for valgrind's satisfaction, we free stuff nonetheless.
	delete populationSettings;
	delete chromosomeFactory;
	delete selectionOperation;
	delete selectionSettings;
	delete stoppingCriterion;
	delete couplingOperation;
	delete crossoverOperation;
	delete replacementOperation;

	delete mutationSettings;
	delete mutationChoosingOperation;
	delete mutationOperation;

}
<|endoftext|>


<commit_before>#include "diffusionSystem.h"
#include <assert.h>

DiffusionSystem::DiffusionSystem()
    : yInf(0)
    , wallConst(0)
{
}

void DiffusionSystem::get_A(sdBandMatrix& A)
{
    // Build the matrix A describing the linear ODE
    SetToZero(A.forSundials());
    size_t N = D.size();

    assert(N == jRight - jLeft + 1);
    dvector c1(N);
    dvector c2(N);

    for (size_t j=0; j<=jRight-jLeft; j++) {
        c1[j] = 0.5*B[j]/(dlj[j+jLeft]*r[j+jLeft]);
        c2[j] = rphalf[j+jLeft]*(D[j]+D[j+1])/hh[j+jLeft];
    }

    assert(mathUtils::notnan(c1));
    assert(mathUtils::notnan(c2));
    assert(mathUtils::notnan(splitLinear));

    // Left boundary value
    size_t jStart;
    if (jLeft == 0) {
        if (grid.leftBC == BoundaryCondition::FixedValue) {
            jStart = 1;
        } else if (grid.leftBC == BoundaryCondition::ControlVolume) {
            jStart =  1;
            double c0 = B[0] * (grid.alpha + 1) * (D[0]+D[1]) / (2 * hh[0] * hh[0]);
            A(0,0) = -c0;
            A(0,1) = c0;
        } else if (grid.leftBC == BoundaryCondition::WallFlux) {
            jStart = 1;
            double c0 = B[0] * (grid.alpha + 1) / hh[0];
            double d = 0.5 * (D[0]+D[1]);
            A(0,0) = - c0 * (d / hh[0] + wallConst);
            A(0,1) = d * c0 / hh[0];
        } else  { // (leftBC == BoundaryCondition::ZeroGradient)
            // In the case of a zero gradient boundary condition, the boundary value
            // is not computed, and the value one point in is computed by substituting
            // y[0] = y[1] in the finite difference formula.
            jStart = 2;
            A(1,1) = -c1[1]*c2[1];
            A(1,2) = c1[1]*c2[1];
        }
    } else {
        // truncated domain -- boundary value is fixed
        jStart = 1;
    }

    // Right boundary value
    size_t jStop;
    if (jRight == jj) {
        if (grid.rightBC == BoundaryCondition::FixedValue) {
            jStop = N-1;
        } else { // (rightBC == BoundaryCondition::ZeroGradient)
            // In the case of a zero gradient boundary condition, the boundary value
            // is not computed, and the value one point in is computed by substituting
            // y[N-1] = y[N-2] in the finite difference formula.
            jStop = N-2;
            A(N-2,N-3) = c1[N-2]*c2[N-3];
            A(N-2,N-2) = -c1[N-2]*c2[N-3];
        }
    } else {
        // truncated domain -- boundary value is fixed
        jStop = N-1;
    }

    // Intermediate points
    for (size_t j=jStart; j<jStop; j++) {
        A(j,j-1) = c1[j]*c2[j-1];
        A(j,j) = -c1[j]*(c2[j-1] + c2[j]);
        A(j,j+1) = c1[j]*c2[j];
    }

    // Contribution from splitting
    for (size_t j=0; j<N; j++) {
        A(j,j) += splitLinear[j];
    }
}

void DiffusionSystem::get_C(dvector& other_c)
{
    other_c.assign(splitConst.begin(), splitConst.end());
    if (grid.leftBC == BoundaryCondition::WallFlux) {
        other_c[0] += B[0] * (grid.alpha + 1) / hh[0] * wallConst * yInf;
    }
    assert(mathUtils::notnan(other_c));
}

void DiffusionSystem::setGrid(const oneDimGrid& other)
{
    GridBased::setGrid(other);

    // Changing the grid resets the region the solver expects to be operating over
    jLeft = 0;
    jRight = jj;
}

void DiffusionSystem::resize(int N_)
{
    N = N_;
    B.resize(N);
    D.resize(N);
    splitConst.resize(N);
    splitLinear.resize(N);
}

void DiffusionSystem::resetSplitConstants()
{
    splitConst.assign(N, 0);
    splitLinear.assign(N, 0);
}
<commit_msg>Fixed a falsely-triggered assertion in diffusionSystem::get_A<commit_after>#include "diffusionSystem.h"
#include <assert.h>

DiffusionSystem::DiffusionSystem()
    : yInf(0)
    , wallConst(0)
{
}

void DiffusionSystem::get_A(sdBandMatrix& A)
{
    // Build the matrix A describing the linear ODE
    SetToZero(A.forSundials());
    size_t N = D.size();

    assert(N == jRight - jLeft + 1);
    dvector c1(N, 0);
    dvector c2(N, 0);

    for (size_t j=1; j<=jRight-jLeft-1; j++) {
        c1[j] = 0.5*B[j]/(dlj[j+jLeft]*r[j+jLeft]);
        c2[j] = rphalf[j+jLeft]*(D[j]+D[j+1])/hh[j+jLeft];
    }

    assert(mathUtils::notnan(c1));
    assert(mathUtils::notnan(c2));
    assert(mathUtils::notnan(splitLinear));

    // Left boundary value
    size_t jStart;
    if (jLeft == 0) {
        if (grid.leftBC == BoundaryCondition::FixedValue) {
            jStart = 1;
        } else if (grid.leftBC == BoundaryCondition::ControlVolume) {
            jStart =  1;
            double c0 = B[0] * (grid.alpha + 1) * (D[0]+D[1]) / (2 * hh[0] * hh[0]);
            A(0,0) = -c0;
            A(0,1) = c0;
        } else if (grid.leftBC == BoundaryCondition::WallFlux) {
            jStart = 1;
            double c0 = B[0] * (grid.alpha + 1) / hh[0];
            double d = 0.5 * (D[0]+D[1]);
            A(0,0) = - c0 * (d / hh[0] + wallConst);
            A(0,1) = d * c0 / hh[0];
        } else  { // (leftBC == BoundaryCondition::ZeroGradient)
            // In the case of a zero gradient boundary condition, the boundary value
            // is not computed, and the value one point in is computed by substituting
            // y[0] = y[1] in the finite difference formula.
            jStart = 2;
            A(1,1) = -c1[1]*c2[1];
            A(1,2) = c1[1]*c2[1];
        }
    } else {
        // truncated domain -- boundary value is fixed
        jStart = 1;
    }

    // Right boundary value
    size_t jStop;
    if (jRight == jj) {
        if (grid.rightBC == BoundaryCondition::FixedValue) {
            jStop = N-1;
        } else { // (rightBC == BoundaryCondition::ZeroGradient)
            // In the case of a zero gradient boundary condition, the boundary value
            // is not computed, and the value one point in is computed by substituting
            // y[N-1] = y[N-2] in the finite difference formula.
            jStop = N-2;
            A(N-2,N-3) = c1[N-2]*c2[N-3];
            A(N-2,N-2) = -c1[N-2]*c2[N-3];
        }
    } else {
        // truncated domain -- boundary value is fixed
        jStop = N-1;
    }

    // Intermediate points
    for (size_t j=jStart; j<jStop; j++) {
        A(j,j-1) = c1[j]*c2[j-1];
        A(j,j) = -c1[j]*(c2[j-1] + c2[j]);
        A(j,j+1) = c1[j]*c2[j];
    }

    // Contribution from splitting
    for (size_t j=0; j<N; j++) {
        A(j,j) += splitLinear[j];
    }
}

void DiffusionSystem::get_C(dvector& other_c)
{
    other_c.assign(splitConst.begin(), splitConst.end());
    if (grid.leftBC == BoundaryCondition::WallFlux) {
        other_c[0] += B[0] * (grid.alpha + 1) / hh[0] * wallConst * yInf;
    }
    assert(mathUtils::notnan(other_c));
}

void DiffusionSystem::setGrid(const oneDimGrid& other)
{
    GridBased::setGrid(other);

    // Changing the grid resets the region the solver expects to be operating over
    jLeft = 0;
    jRight = jj;
}

void DiffusionSystem::resize(int N_)
{
    N = N_;
    B.resize(N);
    D.resize(N);
    splitConst.resize(N);
    splitLinear.resize(N);
}

void DiffusionSystem::resetSplitConstants()
{
    splitConst.assign(N, 0);
    splitLinear.assign(N, 0);
}
<|endoftext|>


<commit_before>#include "Base.h"
#include "MeshBatch.h"

namespace gameplay
{

MeshBatch::MeshBatch(const VertexFormat& vertexFormat, Mesh::PrimitiveType primitiveType, Material* material, bool indexed, unsigned int initialCapacity, unsigned int growSize)
    : _vertexFormat(vertexFormat), _primitiveType(primitiveType), _material(material), _indexed(indexed), _capacity(0), _growSize(growSize),
      _vertexCapacity(0), _indexCapacity(0), _vertexCount(0), _indexCount(0), _vertices(NULL), _verticesPtr(NULL), _indices(NULL), _indicesPtr(NULL)
{
    resize(initialCapacity);
}

MeshBatch::~MeshBatch()
{
    SAFE_RELEASE(_material);
    SAFE_DELETE_ARRAY(_vertices);
    SAFE_DELETE_ARRAY(_indices);
}

MeshBatch* MeshBatch::create(const VertexFormat& vertexFormat, Mesh::PrimitiveType primitiveType, const char* materialPath, bool indexed, unsigned int initialCapacity, unsigned int growSize)
{
    Material* material = Material::create(materialPath);
    if (material == NULL)
    {
        GP_ERROR("Failed to create material for mesh batch from file '%s'.", materialPath);
        return NULL;
    }
    MeshBatch* batch = create(vertexFormat, primitiveType, material, indexed, initialCapacity, growSize);
    SAFE_RELEASE(material); // batch now owns the material
    return batch;
}

MeshBatch* MeshBatch::create(const VertexFormat& vertexFormat, Mesh::PrimitiveType primitiveType, Material* material, bool indexed, unsigned int initialCapacity, unsigned int growSize)
{
    GP_ASSERT(material);

    MeshBatch* batch = new MeshBatch(vertexFormat, primitiveType, material, indexed, initialCapacity, growSize);

    material->addRef();

    return batch;
}

void MeshBatch::updateVertexAttributeBinding()
{
    GP_ASSERT(_material);

    // Update our vertex attribute bindings.
    for (unsigned int i = 0, techniqueCount = _material->getTechniqueCount(); i < techniqueCount; ++i)
    {
        Technique* t = _material->getTechnique(i);
        GP_ASSERT(t);
        for (unsigned int j = 0, passCount = t->getPassCount(); j < passCount; ++j)
        {
            Pass* p = t->getPass(j);
            GP_ASSERT(p);
            VertexAttributeBinding* b = VertexAttributeBinding::create(_vertexFormat, _vertices, p->getEffect());
            p->setVertexAttributeBinding(b);
            SAFE_RELEASE(b);
        }
    }
}

unsigned int MeshBatch::getCapacity() const
{
    return _capacity;
}

void MeshBatch::setCapacity(unsigned int capacity)
{
    resize(capacity);
}

bool MeshBatch::resize(unsigned int capacity)
{
    if (capacity == 0)
    {
        GP_ERROR("Invalid resize capacity (0).");
        return false;
    }

    if (capacity == _capacity)
        return true;

    // Store old batch data.
    unsigned char* oldVertices = _vertices;
    unsigned short* oldIndices = _indices;

    unsigned int vertexCapacity = 0;
    switch (_primitiveType)
    {
    case Mesh::LINES:
        vertexCapacity = capacity * 2;
        break;
    case Mesh::LINE_STRIP:
        vertexCapacity = capacity + 1;
        break;
    case Mesh::POINTS:
        vertexCapacity = capacity;
        break;
    case Mesh::TRIANGLES:
        vertexCapacity = capacity * 3;
        break;
    case Mesh::TRIANGLE_STRIP:
        vertexCapacity = capacity + 2;
        break;
    default:
        GP_ERROR("Unsupported primitive type for mesh batch (%d).", _primitiveType);
        return false;
    }

    // We have no way of knowing how many vertices will be stored in the batch
    // (we only know how many indices will be stored). Assume the worst case
    // for now, which is the same number of vertices as indices.
    unsigned int indexCapacity = vertexCapacity;
    if (indexCapacity > USHRT_MAX)
    {
        GP_ERROR("Index capacity is greater than the maximum unsigned short value (%d > %d).", indexCapacity, USHRT_MAX);
        return false;
    }

    // Allocate new data and reset pointers.
    unsigned int voffset = _verticesPtr - _vertices;
    unsigned int vBytes = vertexCapacity * _vertexFormat.getVertexSize();
    _vertices = new unsigned char[vBytes];
    if (voffset >= vBytes)
        voffset = vBytes - 1;
    _verticesPtr = _vertices + voffset;

    if (_indexed)
    {
        unsigned int ioffset = _indicesPtr - _indices;
        _indices = new unsigned short[indexCapacity];
        if (ioffset >= indexCapacity)
            ioffset = indexCapacity - 1;
        _indicesPtr = _indices + ioffset;
    }

    // Copy old data back in
    if (oldVertices)
        memcpy(_vertices, oldVertices, std::min(_vertexCapacity, vertexCapacity) * _vertexFormat.getVertexSize());
    SAFE_DELETE_ARRAY(oldVertices);
    if (oldIndices)
        memcpy(_indices, oldIndices, std::min(_indexCapacity, indexCapacity) * sizeof(unsigned short));
    SAFE_DELETE_ARRAY(oldIndices);

    // Assign new capacities
    _capacity = capacity;
    _vertexCapacity = vertexCapacity;
    _indexCapacity = indexCapacity;

    // Update our vertex attribute bindings now that our client array pointers have changed
    updateVertexAttributeBinding();

    return true;
}

void MeshBatch::begin()
{
    _vertexCount = 0;
    _indexCount = 0;
    _verticesPtr = _vertices;
    _indicesPtr = _indices;
}

void MeshBatch::finish()
{
}

void MeshBatch::draw()
{
    if (_vertexCount == 0 || (_indexed && _indexCount == 0))
        return; // nothing to draw

    // Not using VBOs, so unbind the element array buffer.
    // ARRAY_BUFFER will be unbound automatically during pass->bind().
    GL_ASSERT( glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0 ) );

    GP_ASSERT(_material);
    if (_indexed)
        GP_ASSERT(_indices);

    // Bind the material.
    Technique* technique = _material->getTechnique();
    GP_ASSERT(technique);
    unsigned int passCount = technique->getPassCount();
    for (unsigned int i = 0; i < passCount; ++i)
    {
        Pass* pass = technique->getPass(i);
        GP_ASSERT(pass);
        pass->bind();

        if (_indexed)
        {
            GL_ASSERT( glDrawElements(_primitiveType, _indexCount, GL_UNSIGNED_SHORT, (GLvoid*)_indices) );
        }
        else
        {
            GL_ASSERT( glDrawArrays(_primitiveType, 0, _vertexCount) );
        }

        pass->unbind();
    }
}

}
<commit_msg>Remove unnecessary error when mesh batch is not indexed. Code review required. Tested fine using non-indexed batches with over 100k verticies.<commit_after>#include "Base.h"
#include "MeshBatch.h"

namespace gameplay
{

MeshBatch::MeshBatch(const VertexFormat& vertexFormat, Mesh::PrimitiveType primitiveType, Material* material, bool indexed, unsigned int initialCapacity, unsigned int growSize)
    : _vertexFormat(vertexFormat), _primitiveType(primitiveType), _material(material), _indexed(indexed), _capacity(0), _growSize(growSize),
      _vertexCapacity(0), _indexCapacity(0), _vertexCount(0), _indexCount(0), _vertices(NULL), _verticesPtr(NULL), _indices(NULL), _indicesPtr(NULL)
{
    resize(initialCapacity);
}

MeshBatch::~MeshBatch()
{
    SAFE_RELEASE(_material);
    SAFE_DELETE_ARRAY(_vertices);
    SAFE_DELETE_ARRAY(_indices);
}

MeshBatch* MeshBatch::create(const VertexFormat& vertexFormat, Mesh::PrimitiveType primitiveType, const char* materialPath, bool indexed, unsigned int initialCapacity, unsigned int growSize)
{
    Material* material = Material::create(materialPath);
    if (material == NULL)
    {
        GP_ERROR("Failed to create material for mesh batch from file '%s'.", materialPath);
        return NULL;
    }
    MeshBatch* batch = create(vertexFormat, primitiveType, material, indexed, initialCapacity, growSize);
    SAFE_RELEASE(material); // batch now owns the material
    return batch;
}

MeshBatch* MeshBatch::create(const VertexFormat& vertexFormat, Mesh::PrimitiveType primitiveType, Material* material, bool indexed, unsigned int initialCapacity, unsigned int growSize)
{
    GP_ASSERT(material);

    MeshBatch* batch = new MeshBatch(vertexFormat, primitiveType, material, indexed, initialCapacity, growSize);

    material->addRef();

    return batch;
}

void MeshBatch::updateVertexAttributeBinding()
{
    GP_ASSERT(_material);

    // Update our vertex attribute bindings.
    for (unsigned int i = 0, techniqueCount = _material->getTechniqueCount(); i < techniqueCount; ++i)
    {
        Technique* t = _material->getTechnique(i);
        GP_ASSERT(t);
        for (unsigned int j = 0, passCount = t->getPassCount(); j < passCount; ++j)
        {
            Pass* p = t->getPass(j);
            GP_ASSERT(p);
            VertexAttributeBinding* b = VertexAttributeBinding::create(_vertexFormat, _vertices, p->getEffect());
            p->setVertexAttributeBinding(b);
            SAFE_RELEASE(b);
        }
    }
}

unsigned int MeshBatch::getCapacity() const
{
    return _capacity;
}

void MeshBatch::setCapacity(unsigned int capacity)
{
    resize(capacity);
}

bool MeshBatch::resize(unsigned int capacity)
{
    if (capacity == 0)
    {
        GP_ERROR("Invalid resize capacity (0).");
        return false;
    }

    if (capacity == _capacity)
        return true;

    // Store old batch data.
    unsigned char* oldVertices = _vertices;
    unsigned short* oldIndices = _indices;

    unsigned int vertexCapacity = 0;
    switch (_primitiveType)
    {
    case Mesh::LINES:
        vertexCapacity = capacity * 2;
        break;
    case Mesh::LINE_STRIP:
        vertexCapacity = capacity + 1;
        break;
    case Mesh::POINTS:
        vertexCapacity = capacity;
        break;
    case Mesh::TRIANGLES:
        vertexCapacity = capacity * 3;
        break;
    case Mesh::TRIANGLE_STRIP:
        vertexCapacity = capacity + 2;
        break;
    default:
        GP_ERROR("Unsupported primitive type for mesh batch (%d).", _primitiveType);
        return false;
    }

    // We have no way of knowing how many vertices will be stored in the batch
    // (we only know how many indices will be stored). Assume the worst case
    // for now, which is the same number of vertices as indices.
    unsigned int indexCapacity = vertexCapacity;
    if (_indexed && indexCapacity > USHRT_MAX)
    {
        GP_ERROR("Index capacity is greater than the maximum unsigned short value (%d > %d).", indexCapacity, USHRT_MAX);
        return false;
    }

    // Allocate new data and reset pointers.
    unsigned int voffset = _verticesPtr - _vertices;
    unsigned int vBytes = vertexCapacity * _vertexFormat.getVertexSize();
    _vertices = new unsigned char[vBytes];
    if (voffset >= vBytes)
        voffset = vBytes - 1;
    _verticesPtr = _vertices + voffset;

    if (_indexed)
    {
        unsigned int ioffset = _indicesPtr - _indices;
        _indices = new unsigned short[indexCapacity];
        if (ioffset >= indexCapacity)
            ioffset = indexCapacity - 1;
        _indicesPtr = _indices + ioffset;
    }

    // Copy old data back in
    if (oldVertices)
        memcpy(_vertices, oldVertices, std::min(_vertexCapacity, vertexCapacity) * _vertexFormat.getVertexSize());
    SAFE_DELETE_ARRAY(oldVertices);
    if (oldIndices)
        memcpy(_indices, oldIndices, std::min(_indexCapacity, indexCapacity) * sizeof(unsigned short));
    SAFE_DELETE_ARRAY(oldIndices);

    // Assign new capacities
    _capacity = capacity;
    _vertexCapacity = vertexCapacity;
    _indexCapacity = indexCapacity;

    // Update our vertex attribute bindings now that our client array pointers have changed
    updateVertexAttributeBinding();

    return true;
}

void MeshBatch::begin()
{
    _vertexCount = 0;
    _indexCount = 0;
    _verticesPtr = _vertices;
    _indicesPtr = _indices;
}

void MeshBatch::finish()
{
}

void MeshBatch::draw()
{
    if (_vertexCount == 0 || (_indexed && _indexCount == 0))
        return; // nothing to draw

    // Not using VBOs, so unbind the element array buffer.
    // ARRAY_BUFFER will be unbound automatically during pass->bind().
    GL_ASSERT( glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0 ) );

    GP_ASSERT(_material);
    if (_indexed)
        GP_ASSERT(_indices);

    // Bind the material.
    Technique* technique = _material->getTechnique();
    GP_ASSERT(technique);
    unsigned int passCount = technique->getPassCount();
    for (unsigned int i = 0; i < passCount; ++i)
    {
        Pass* pass = technique->getPass(i);
        GP_ASSERT(pass);
        pass->bind();

        if (_indexed)
        {
            GL_ASSERT( glDrawElements(_primitiveType, _indexCount, GL_UNSIGNED_SHORT, (GLvoid*)_indices) );
        }
        else
        {
            GL_ASSERT( glDrawArrays(_primitiveType, 0, _vertexCount) );
        }

        pass->unbind();
    }
}

}
<|endoftext|>


<commit_before>#include "ros/ros.h"
#include "sensor_msgs/Joy.h"
#include "jaws_msgs/Thrusters.h"

const float MAX_THRUST = 500.0;

class Controls
{
  private:
    ros::NodeHandle nh;
    ros::NodeHandle parameters;
    ros::Publisher pub;
    ros::Subscriber sub;
    jaws_msgs::Thrusters thrusters;
    int stbd_thrust_mult_pull;
    int port_thrust_mult_pull;
    float stbd_thrust_mult;
    float port_thrust_mult;
    int refresh_rate;

  public:
    Controls() : nh()
    {
      nh.param("/controls_node/port_thrust_multiplier", port_thrust_mult_pull, 1);
      ROS_INFO("Port multiplier: %i", port_thrust_mult_pull);
      nh.param("/controls_node/stbd_thrust_multiplier", stbd_thrust_mult_pull, 1);
      ROS_INFO("Starboard multiplier: %i", stbd_thrust_mult_pull);
      nh.param("/controls_node/controls_refresh_rate", refresh_rate, 10);
      ROS_INFO("Refresh rate: %i", refresh_rate);

      stbd_thrust_mult=(float) stbd_thrust_mult_pull;
      port_thrust_mult=(float) port_thrust_mult_pull;

      sub = nh.subscribe<sensor_msgs::Joy>("joy", 1, &Controls::callback, this);
      pub = nh.advertise<jaws_msgs::Thrusters>("thrusters", 1);
    }

    void callback(const sensor_msgs::Joy::ConstPtr& joy)
    {
      float raw_thrust = joy->axes[1] * MAX_THRUST;
      float stbd_power = stbd_thrust_mult * (raw_thrust * raw_thrust * raw_thrust) / (MAX_THRUST * MAX_THRUST);
      float port_power = port_thrust_mult * (raw_thrust * raw_thrust * raw_thrust) / (MAX_THRUST * MAX_THRUST);
      float stbd_yaw = 1 + joy->axes[13];
      float port_yaw = 1 + joy->axes[12];

      float aft_thrust = joy->axes[3] * MAX_THRUST;
      float aft_power = (aft_thrust * aft_thrust * aft_thrust) / (MAX_THRUST * MAX_THRUST);

      thrusters.stbd_angle = (int)(90 + joy->axes[2] * 90);
      thrusters.port_angle = (int)(90 + joy->axes[2] * 90);
      thrusters.aft_power = (int)(1500 + aft_power);
      thrusters.stbd_power = (int)(1500 + stbd_power * stbd_yaw);
      thrusters.port_power = (int)(1500 + port_power * port_yaw);
      //*** I don't know if the below axes indices are correct.
      //*** Supposed to be the D-pad, doesnt matter which.
      if(joy->axes[5]>0){
	stbd_thrust_mult+=0.001;
      }
      else if(joy->axes[6]>0){
 	stbd_thrust_mult-=0.001;
      }
      if(joy->axes[7]>0){
	port_thrust_mult+=0.001;
      }
      else if(joy->axes[8]>0){
	port_thrust_mult-=0.001;
      }

      ROS_INFO("Current PTM: %4f - Current STM: %4f",port_thrust_mult,stbd_thrust_mult);
      pub.publish(thrusters);

    }

    void loop()
    {
      ros::Rate rate(refresh_rate);
      while(ros::ok())
      {
        ros::spinOnce();
        rate.sleep();
      }
    }
};

int main(int argc, char **argv)
{
  ros::init(argc, argv, "controls_node");
  Controls controls;
  controls.loop();
}
<commit_msg>Fixed D-Pad, added Aft Thruster, floats became doubles.<commit_after>#include "ros/ros.h"
#include "sensor_msgs/Joy.h"
#include "jaws_msgs/Thrusters.h"

const float MAX_THRUST = 500.0;

class Controls
{
  private:
    ros::NodeHandle nh;
    ros::NodeHandle parameters;
    ros::Publisher pub;
    ros::Subscriber sub;
    jaws_msgs::Thrusters thrusters;
    int refresh_rate;
    double aft_thrust_mult;
    double stbd_thrust_mult;
    double port_thrust_mult;

  public:
    Controls() : nh()
    {
      nh.param<int>("/controls_node/controls_refresh_rate", refresh_rate, 10);
      ROS_INFO("Refresh rate: %i", refresh_rate);

      nh.param<double>("/controls_node/aft_thrust_multiplier", aft_thrust_mult, 1.0);
      ROS_INFO("Aft multiplier: %f", aft_thrust_mult);
      nh.param<double>("/controls_node/port_thrust_multiplier", port_thrust_mult, 1.0);
      ROS_INFO("Port multiplier: %f", port_thrust_mult);
      nh.param<double>("/controls_node/stbd_thrust_multiplier", stbd_thrust_mult, 1.0);
      ROS_INFO("Starboard multiplier: %f", stbd_thrust_mult);

      sub = nh.subscribe<sensor_msgs::Joy>("joy", 1, &Controls::callback, this);
      pub = nh.advertise<jaws_msgs::Thrusters>("thrusters", 1);
    }

    void callback(const sensor_msgs::Joy::ConstPtr& joy)
    {
      float raw_thrust = joy->axes[1] * MAX_THRUST;
      float stbd_power = stbd_thrust_mult * (raw_thrust * raw_thrust * raw_thrust) / (MAX_THRUST * MAX_THRUST);
      float port_power = port_thrust_mult * (raw_thrust * raw_thrust * raw_thrust) / (MAX_THRUST * MAX_THRUST);
      float stbd_yaw = 1 + joy->axes[13];
      float port_yaw = 1 + joy->axes[12];

      float aft_thrust = joy->axes[3] * MAX_THRUST;
      float aft_power = (aft_thrust * aft_thrust * aft_thrust) / (MAX_THRUST * MAX_THRUST);

      thrusters.stbd_angle = (int)(90 + joy->axes[2] * 90);
      thrusters.port_angle = (int)(90 + joy->axes[2] * 90);
      thrusters.aft_power = (int)(1500 + aft_power);
      thrusters.stbd_power = (int)(1500 + stbd_power * stbd_yaw);
      thrusters.port_power = (int)(1500 + port_power * port_yaw);

      if(joy->buttons[4]){
	stbd_thrust_mult+=0.001;
      }
      else if(joy->buttons[5]){
 	stbd_thrust_mult-=0.001;
      }
      if(joy->buttons[6]){
	port_thrust_mult+=0.001;
      }
      else if(joy->buttons[7]){
	port_thrust_mult-=0.001;
      }

      ROS_INFO("Current PTM: %4f - Current STM: %4f",port_thrust_mult,stbd_thrust_mult);
      pub.publish(thrusters);

    }

    void loop()
    {
      ros::Rate rate(refresh_rate);
      while(ros::ok())
      {
        ros::spinOnce();
        rate.sleep();
      }
    }
};

int main(int argc, char **argv)
{
  ros::init(argc, argv, "controls_node");
  Controls controls;
  controls.loop();
}
<|endoftext|>


<commit_before>#ifndef png_infopp_NULL
    #define png_infopp_NULL (png_infopp)NULL
#endif
#ifndef int_p_NULL
    #define int_p_NULL (int*)NULL
#endif

#include <dirent.h>
#include <sys/types.h>

#include <iostream>
#include <vector>
#include <stdio.h>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <set>
using namespace std;

#include <boost/gil/gil_all.hpp>
#include <boost/gil/extension/io/jpeg_io.hpp>
#include <boost/gil/extension/io/png_io.hpp>
#include "util.h"
#include <boost/bind.hpp>
#include <boost/timer.hpp>
#include <boost/format.hpp>
#include <boost/ref.hpp>

#include "poselet_api.h"

#include "config.h"
#include "util/Timer.h"

using namespace boost::gil;
using namespace poselet_api;

enum img_format
{
	JPEG,
	PNG,
	NOTKNOW
};

//#define debug

map<string, int> GT, RESULT;
double threshold;
string input_dir;
string modelname = "person";
bool output_score = false;
string output_name = "result.txt";
string score_name = "score.txt";
bool test_mode = false;
string test_filename;
set<string> file_to_test;

template <typename Value>
void append_hit(const Value& oh, vector<Value>& hits) {
  hits.push_back(oh);
}

template <typename View, typename Hit, typename Color>
void draw_hit(const View& v, const Hit& hit, const Color& c, int thickness=1) {
  typename View::value_type color;
  boost::gil::color_convert(c,color);
  int_bounds b(hit.x0,hit.y0,hit.width,hit.height);
  draw_bounds(v,color,b,thickness);

  render_text(v, b._min+int_point(thickness,thickness),
              str(boost::format("%4.2f") % hit.score), c, 1, 1);
}

bool file_exists(const char *filename)
{
  ifstream ifile(filename);
  return !!ifile;
}

vector<string> get_files(const string& input_dir){
	vector<string> files;

	DIR *dpdf;
	struct dirent *epdf;

	dpdf = opendir(input_dir.c_str());
	if (dpdf != NULL){
	   while (epdf = readdir(dpdf)){
		   string filename = string(epdf->d_name);
		   if(filename.find(".jpg")!=filename.length() - 4
		   && filename.find(".JPG")!=filename.length() - 4
		   && filename.find(".jpeg")!=filename.length() - 5
		   && filename.find(".JPEG")!=filename.length() - 5)
			   continue;
		   if(filename.find("-profile") == std::string::npos)
			   files.push_back(filename);
	   }
	}
	std::sort(files.begin(), files.end());
	return files;
}

vector<string> get_wrong_files(const string& output){
	vector<string> files;
	ifstream fs;
	fs.open(output.c_str(), ios::in);
	string str;
	while(fs>>str)
		files.push_back(str);
	fs.close();
	return files;
}

void readGroundTruth( const string& ground_truth)
{
	ifstream fs;
	string filename;
	int value;
	fs.open(ground_truth.c_str(), std::ifstream::in);
	while(fs>>filename>>value)
	{
		GT[filename] = value;
	}
}

void evaluation() {
	int sum = 0;
	int total = RESULT.size();
	for(map<string,int>::const_iterator it = RESULT.begin(); it != RESULT.end(); ++it)
	{
		if(GT[it->first] == it->second) sum++;
	}
	cout<<"============================================================"<<endl;
	cout<<"score:"<<(double)sum/total<<endl;
	cout<<"============================================================"<<endl;
}

int get_image_format(char* header)
{
	if ((unsigned int)(unsigned char)header[0]==0xFF && (unsigned int)(unsigned char)header[1]==0xD8)
		return JPEG;
	else if ((unsigned int)(unsigned char)header[0]==0x89 && (unsigned int)(unsigned char)header[1]==0x50 &&
			 (unsigned int)(unsigned char)header[2]==0x4E && (unsigned int)(unsigned char)header[3]==0x47 &&
			 (unsigned int)(unsigned char)header[4]==0x0D && (unsigned int)(unsigned char)header[5]==0x0A &&
			 (unsigned int)(unsigned char)header[6]==0x1A && (unsigned int)(unsigned char)header[7]==0x0A)
			return PNG;
		else
			return NOTKNOW;

}

void initial_config(){
	const config& c = config::get();
	c.PYRAMID_SCALE_RATIO = 1.5;
	threshold = 1.8;
}

bool parse_arg(int argc, char** argv){
	if(argc < 2) {
		return false;
	}
	int i=1;
	while(i<argc){
		string arg = argv[i];
		if(arg == "-t"){
			if(i+1 < argc && argv[i+1][0] != '-'){
				stringstream ss(argv[++i]);
				ss>>threshold;
			}
			else{
				return false;
			}
		}
		else if (arg == "-r"){
			if(i+1 < argc && argv[i+1][0] != '-'){
				stringstream rr(argv[++i]);
				rr>>config::get().PYRAMID_SCALE_RATIO;
			}else{
				return false;
			}
		}
		else if (arg == "-s"){
			output_score = true;
			score_name = argv[++i];
		}
		else if (arg == "-o"){
			if(i+1 < argc && argv[i+1][0] != '-'){
				output_name = argv[++i];
			}else{
				return false;
			}
		}
		else if(arg == "-if") {
			test_mode = true;
			test_filename = argv[++i];
		}
		else{
			input_dir = arg;
		}
		++i;
	}
	return true;
}

double human_detect(const string& img_path)
{
	try{
		  bgr8_image_t img;

		  // detect image type
		  ifstream ifs;
		  char memblock[10];
		  ifs.open(img_path.c_str(), ios::in|ios::binary);
		  ifs.read(memblock, 8);
		  ifs.close();
		  int img_type = get_image_format(memblock);
		  if (img_type==JPEG)
			  jpeg_read_image(img_path.c_str(),img);
		  else if (img_type==PNG)
			  png_read_image(img_path.c_str(),img);
		  else
			  return 0;

		  Image img_proxy(
			img.width(), img.height(), const_view(img).pixels().row_size(),
			Image::k8Bit, Image::kRGB, interleaved_view_get_raw_data(const_view(img)));

		  vector<ObjectHit> object_hits;
		  vector<PoseletHit> poselet_hits;

		  RunDetector(img_proxy, boost::bind(append_hit<PoseletHit>, _1,
			boost::ref(poselet_hits)), boost::bind(append_hit<ObjectHit>, _1,
			boost::ref(object_hits)), true, 0, false);

		  if (object_hits.size()>0)
		  {
			  return object_hits[0].score;
		  }
		  else
		  {
			  return 0;
		  }
	  }
	  catch (std::ios_base::failure& exception)
	  {
		  cout << "jpeg read exception" << endl;
		  return 0;
	  }
	  catch (int e)
	  {
		  cout << "unkown exception" << endl;
		  return 0;
	  }

	  return 0;
}

void load_test_files() {
	ifstream fs(test_filename.c_str());
	string test_file;
	while(fs>>test_file) {
		file_to_test.insert(test_file);
	}

	cout<<file_to_test.size()<<" files to test"<<endl;
}

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

	if (!parse_arg(argc, argv))
	{
		cout << "Usage: " << argv[0] << " input_dir"<<endl;
		return 0;
	}

	vector<string> files = get_files(input_dir);

	if(test_mode) load_test_files();

	InitDetector(".", modelname.c_str(), true);

	ofstream fs;
	fs.open(output_name.c_str(),std::ofstream::out);
	if(fs.bad())
	{
	  cout << "Failed to create result.txt" << endl;
	  return 0;
	}

	ofstream fscore;
	fscore.open(score_name.c_str(),std::ofstream::out);

	for (size_t i=0; i<files.size(); i++)
	{
		Timer t;
		if(test_mode && file_to_test.count(files[i])==0) {
			//cout<<"[TEST MODE] skip "<<files[i]<<endl;
			continue;
		}
		cerr << "Processing "<< files[i] << " ";
		double score = human_detect(input_dir + "/" + files[i]);
		int value = score > threshold ? 1 : 0;
		fs << files[i] << " " << value << endl;
		if (output_score)
		  fscore << files[i] << " " << score << endl;
		cerr << "label = " << value << " score = " << score << " "<< t.getElapsedMilliseconds() << "ms" <<endl;
	}
	fs.close();
	fscore.close();
	return 0;
}
<commit_msg>ouput obj size<commit_after>#ifndef png_infopp_NULL
    #define png_infopp_NULL (png_infopp)NULL
#endif
#ifndef int_p_NULL
    #define int_p_NULL (int*)NULL
#endif

#include <dirent.h>
#include <sys/types.h>

#include <iostream>
#include <vector>
#include <stdio.h>
#include <fstream>
#include <sstream>
#include <string>
#include <map>
#include <set>
using namespace std;

#include <boost/gil/gil_all.hpp>
#include <boost/gil/extension/io/jpeg_io.hpp>
#include <boost/gil/extension/io/png_io.hpp>
#include "util.h"
#include <boost/bind.hpp>
#include <boost/timer.hpp>
#include <boost/format.hpp>
#include <boost/ref.hpp>

#include "poselet_api.h"

#include "config.h"
#include "util/Timer.h"

using namespace boost::gil;
using namespace poselet_api;

enum img_format
{
	JPEG,
	PNG,
	NOTKNOW
};

//#define debug

map<string, int> GT, RESULT;
double threshold;
string input_dir;
string modelname = "person";
bool output_score = false;
string output_name = "result.txt";
string score_name = "score.txt";
bool test_mode = false;
string test_filename;
set<string> file_to_test;

template <typename Value>
void append_hit(const Value& oh, vector<Value>& hits) {
  hits.push_back(oh);
}

template <typename View, typename Hit, typename Color>
void draw_hit(const View& v, const Hit& hit, const Color& c, int thickness=1) {
  typename View::value_type color;
  boost::gil::color_convert(c,color);
  int_bounds b(hit.x0,hit.y0,hit.width,hit.height);
  draw_bounds(v,color,b,thickness);

  render_text(v, b._min+int_point(thickness,thickness),
              str(boost::format("%4.2f") % hit.score), c, 1, 1);
}

bool file_exists(const char *filename)
{
  ifstream ifile(filename);
  return !!ifile;
}

vector<string> get_files(const string& input_dir){
	vector<string> files;

	DIR *dpdf;
	struct dirent *epdf;

	dpdf = opendir(input_dir.c_str());
	if (dpdf != NULL){
	   while (epdf = readdir(dpdf)){
		   string filename = string(epdf->d_name);
		   if(filename.find(".jpg")!=filename.length() - 4
		   && filename.find(".JPG")!=filename.length() - 4
		   && filename.find(".jpeg")!=filename.length() - 5
		   && filename.find(".JPEG")!=filename.length() - 5)
			   continue;
		   if(filename.find("-profile") == std::string::npos)
			   files.push_back(filename);
	   }
	}
	std::sort(files.begin(), files.end());
	return files;
}

vector<string> get_wrong_files(const string& output){
	vector<string> files;
	ifstream fs;
	fs.open(output.c_str(), ios::in);
	string str;
	while(fs>>str)
		files.push_back(str);
	fs.close();
	return files;
}

void readGroundTruth( const string& ground_truth)
{
	ifstream fs;
	string filename;
	int value;
	fs.open(ground_truth.c_str(), std::ifstream::in);
	while(fs>>filename>>value)
	{
		GT[filename] = value;
	}
}

void evaluation() {
	int sum = 0;
	int total = RESULT.size();
	for(map<string,int>::const_iterator it = RESULT.begin(); it != RESULT.end(); ++it)
	{
		if(GT[it->first] == it->second) sum++;
	}
	cout<<"============================================================"<<endl;
	cout<<"score:"<<(double)sum/total<<endl;
	cout<<"============================================================"<<endl;
}

int get_image_format(char* header)
{
	if ((unsigned int)(unsigned char)header[0]==0xFF && (unsigned int)(unsigned char)header[1]==0xD8)
		return JPEG;
	else if ((unsigned int)(unsigned char)header[0]==0x89 && (unsigned int)(unsigned char)header[1]==0x50 &&
			 (unsigned int)(unsigned char)header[2]==0x4E && (unsigned int)(unsigned char)header[3]==0x47 &&
			 (unsigned int)(unsigned char)header[4]==0x0D && (unsigned int)(unsigned char)header[5]==0x0A &&
			 (unsigned int)(unsigned char)header[6]==0x1A && (unsigned int)(unsigned char)header[7]==0x0A)
			return PNG;
		else
			return NOTKNOW;

}

void initial_config(){
	const config& c = config::get();
	c.PYRAMID_SCALE_RATIO = 1.5;
	threshold = 1.8;
}

bool parse_arg(int argc, char** argv){
	if(argc < 2) {
		return false;
	}
	int i=1;
	while(i<argc){
		string arg = argv[i];
		if(arg == "-t"){
			if(i+1 < argc && argv[i+1][0] != '-'){
				stringstream ss(argv[++i]);
				ss>>threshold;
			}
			else{
				return false;
			}
		}
		else if (arg == "-r"){
			if(i+1 < argc && argv[i+1][0] != '-'){
				stringstream rr(argv[++i]);
				rr>>config::get().PYRAMID_SCALE_RATIO;
			}else{
				return false;
			}
		}
		else if (arg == "-s"){
			output_score = true;
			score_name = argv[++i];
		}
		else if (arg == "-o"){
			if(i+1 < argc && argv[i+1][0] != '-'){
				output_name = argv[++i];
			}else{
				return false;
			}
		}
		else if(arg == "-if") {
			test_mode = true;
			test_filename = argv[++i];
		}
		else{
			input_dir = arg;
		}
		++i;
	}
	return true;
}

double human_detect(const string& img_path)
{
	try{
		  bgr8_image_t img;

		  // detect image type
		  ifstream ifs;
		  char memblock[10];
		  ifs.open(img_path.c_str(), ios::in|ios::binary);
		  ifs.read(memblock, 8);
		  ifs.close();
		  int img_type = get_image_format(memblock);
		  if (img_type==JPEG)
			  jpeg_read_image(img_path.c_str(),img);
		  else if (img_type==PNG)
			  png_read_image(img_path.c_str(),img);
		  else
			  return 0;

		  Image img_proxy(
			img.width(), img.height(), const_view(img).pixels().row_size(),
			Image::k8Bit, Image::kRGB, interleaved_view_get_raw_data(const_view(img)));

		  vector<ObjectHit> object_hits;
		  vector<PoseletHit> poselet_hits;

		  RunDetector(img_proxy, boost::bind(append_hit<PoseletHit>, _1,
			boost::ref(poselet_hits)), boost::bind(append_hit<ObjectHit>, _1,
			boost::ref(object_hits)), true, 0, false);

		  if (object_hits.size()>0)
		  {
			  cout <<"- obj size = " << object_hits[0].width << "*" << object_hits[0].height<<endl;
			  return object_hits[0].score;
		  }
		  else
		  {
			  return 0;
		  }
	  }
	  catch (std::ios_base::failure& exception)
	  {
		  cout << "jpeg read exception" << endl;
		  return 0;
	  }
	  catch (int e)
	  {
		  cout << "unkown exception" << endl;
		  return 0;
	  }

	  return 0;
}

void load_test_files() {
	ifstream fs(test_filename.c_str());
	string test_file;
	while(fs>>test_file) {
		file_to_test.insert(test_file);
	}

	cout<<file_to_test.size()<<" files to test"<<endl;
}

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

	if (!parse_arg(argc, argv))
	{
		cout << "Usage: " << argv[0] << " input_dir"<<endl;
		return 0;
	}

	vector<string> files = get_files(input_dir);

	if(test_mode) load_test_files();

	InitDetector(".", modelname.c_str(), true);

	ofstream fs;
	fs.open(output_name.c_str(),std::ofstream::out);
	if(fs.bad())
	{
	  cout << "Failed to create result.txt" << endl;
	  return 0;
	}

	ofstream fscore;
	fscore.open(score_name.c_str(),std::ofstream::out);

	for (size_t i=0; i<files.size(); i++)
	{
		Timer t;
		if(test_mode && file_to_test.count(files[i])==0) {
			//cout<<"[TEST MODE] skip "<<files[i]<<endl;
			continue;
		}
		cerr << "Processing "<< files[i] << " ";
		double score = human_detect(input_dir + "/" + files[i]);
		int value = score > threshold ? 1 : 0;
		fs << files[i] << " " << value << endl;
		if (output_score)
		  fscore << files[i] << " " << score << endl;
		cerr << "label = " << value << " score = " << score << " "<< t.getElapsedMilliseconds() << "ms" <<endl;
	}
	fs.close();
	fscore.close();
	return 0;
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <qdeclarativedatatest.h>
#include <qdir.h>
#include <QtDeclarative/qdeclarativeengine.h>
#include <QtDeclarative/qdeclarativecomponent.h>
#include <QDebug>
#include <QtCore/qlibraryinfo.h>

#include "../shared/testhttpserver.h"

#define SERVER_ADDR "http://127.0.0.1:14450"
#define SERVER_PORT 14450

class tst_qdeclarativemoduleplugin : public QDeclarativeDataTest
{
    Q_OBJECT
public:
    tst_qdeclarativemoduleplugin()
    {
    }

private slots:
    void importsPlugin();
    void importsPlugin2();
    void importsPlugin21();
    void importsMixedQmlCppPlugin();
    void incorrectPluginCase();
    void importPluginWithQmlFile();
    void remoteImportWithQuotedUrl();
    void remoteImportWithUnquotedUri();
    void versionNotInstalled();
    void versionNotInstalled_data();
};

#define VERIFY_ERRORS(errorfile) \
    if (!errorfile) { \
        if (qgetenv("DEBUG") != "" && !component.errors().isEmpty()) \
            qWarning() << "Unexpected Errors:" << component.errors(); \
        QVERIFY(!component.isError()); \
        QVERIFY(component.errors().isEmpty()); \
    } else { \
        QFile file(testFile(errorfile)); \
        QVERIFY(file.open(QIODevice::ReadOnly | QIODevice::Text)); \
        QByteArray data = file.readAll(); \
        file.close(); \
        QList<QByteArray> expected = data.split('\n'); \
        expected.removeAll(QByteArray("")); \
        QList<QDeclarativeError> errors = component.errors(); \
        QList<QByteArray> actual; \
        for (int ii = 0; ii < errors.count(); ++ii) { \
            const QDeclarativeError &error = errors.at(ii); \
            QByteArray errorStr = QByteArray::number(error.line()) + ":" +  \
                                  QByteArray::number(error.column()) + ":" + \
                                  error.description().toUtf8(); \
            actual << errorStr; \
        } \
        if (qgetenv("DEBUG") != "" && expected != actual) \
            qWarning() << "Expected:" << expected << "Actual:" << actual;  \
        if (qgetenv("QDECLARATIVELANGUAGE_UPDATEERRORS") != "" && expected != actual) {\
            QFile file(testFile(errorfile)); \
            QVERIFY(file.open(QIODevice::WriteOnly)); \
            for (int ii = 0; ii < actual.count(); ++ii) { \
                file.write(actual.at(ii)); file.write("\n"); \
            } \
            file.close(); \
        } else { \
            QCOMPARE(expected, actual); \
        } \
    }

void tst_qdeclarativemoduleplugin::importsPlugin()
{
    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());
    QTest::ignoreMessage(QtWarningMsg, "plugin created");
    QTest::ignoreMessage(QtWarningMsg, "import worked");
    QDeclarativeComponent component(&engine, testFileUrl("works.qml"));
    foreach (QDeclarativeError err, component.errors())
    	qWarning() << err;
    VERIFY_ERRORS(0);
    QObject *object = component.create();
    QVERIFY(object != 0);
    QCOMPARE(object->property("value").toInt(),123);
    delete object;
}

void tst_qdeclarativemoduleplugin::importsPlugin2()
{
    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());
    QTest::ignoreMessage(QtWarningMsg, "plugin2 created");
    QTest::ignoreMessage(QtWarningMsg, "import2 worked");
    QDeclarativeComponent component(&engine, testFileUrl("works2.qml"));
    foreach (QDeclarativeError err, component.errors())
        qWarning() << err;
    VERIFY_ERRORS(0);
    QObject *object = component.create();
    QVERIFY(object != 0);
    QCOMPARE(object->property("value").toInt(),123);
    delete object;
}

void tst_qdeclarativemoduleplugin::importsPlugin21()
{
    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());
    QTest::ignoreMessage(QtWarningMsg, "plugin2.1 created");
    QTest::ignoreMessage(QtWarningMsg, "import2.1 worked");
    QDeclarativeComponent component(&engine, testFileUrl("works21.qml"));
    foreach (QDeclarativeError err, component.errors())
        qWarning() << err;
    VERIFY_ERRORS(0);
    QObject *object = component.create();
    QVERIFY(object != 0);
    QCOMPARE(object->property("value").toInt(),123);
    delete object;
}

void tst_qdeclarativemoduleplugin::incorrectPluginCase()
{
    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());

    QDeclarativeComponent component(&engine, testFileUrl("incorrectCase.qml"));

    QList<QDeclarativeError> errors = component.errors();
    QCOMPARE(errors.count(), 1);

#if defined(Q_OS_MAC) || defined(Q_OS_WIN32)
#if defined(Q_OS_MAC)
    QString libname = "libPluGin.dylib";
#elif defined(Q_OS_WIN32)
    QString libname = "PluGin.dll";
#endif
    QString expectedError = QLatin1String("plugin cannot be loaded for module \"org.qtproject.WrongCase\": File name case mismatch for \"") + QFileInfo(__FILE__).absoluteDir().filePath("imports/org/qtproject/WrongCase/" + libname) + QLatin1String("\"");
#else
    QString expectedError = QLatin1String("module \"org.qtproject.WrongCase\" plugin \"PluGin\" not found");
#endif

    QCOMPARE(errors.at(0).description(), expectedError);
}

void tst_qdeclarativemoduleplugin::importPluginWithQmlFile()
{
    QString path = importsDirectory();

    // QTBUG-16885: adding an import path with a lower-case "c:" causes assert failure
    // (this only happens if the plugin includes pure QML files)
    #ifdef Q_OS_WIN
    if (path.size() > 1 && path.at(0).isUpper() && path.at(1) == QLatin1Char(':'))
        path = path.at(0).toLower() + path.mid(1);
    #endif

    QDeclarativeEngine engine;
    engine.addImportPath(path);

    QDeclarativeComponent component(&engine, testFileUrl("pluginWithQmlFile.qml"));
    foreach (QDeclarativeError err, component.errors())
        qWarning() << err;
    VERIFY_ERRORS(0);
    QObject *object = component.create();
    QVERIFY(object != 0);
    delete object;
}

void tst_qdeclarativemoduleplugin::remoteImportWithQuotedUrl()
{
    TestHTTPServer server(SERVER_PORT);
    QVERIFY(server.isValid());
    server.serveDirectory(importsDirectory());

    QDeclarativeEngine engine;
    QDeclarativeComponent component(&engine);
    component.setData("import \"http://127.0.0.1:14450/org/qtproject/PureQmlModule\" \nComponentA { width: 300; ComponentB{} }", QUrl());

    QTRY_COMPARE(component.status(), QDeclarativeComponent::Ready);
    QObject *object = component.create();
    QCOMPARE(object->property("width").toInt(), 300);
    QVERIFY(object != 0);
    delete object;

    foreach (QDeclarativeError err, component.errors())
        qWarning() << err;
    VERIFY_ERRORS(0);
}

void tst_qdeclarativemoduleplugin::remoteImportWithUnquotedUri()
{
    TestHTTPServer server(SERVER_PORT);
    QVERIFY(server.isValid());
    server.serveDirectory(directory() + QStringLiteral("/imports"));

    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());
    QDeclarativeComponent component(&engine);
    component.setData("import org.qtproject.PureQmlModule 1.0 \nComponentA { width: 300; ComponentB{} }", QUrl());

    QTRY_COMPARE(component.status(), QDeclarativeComponent::Ready);
    QObject *object = component.create();
    QVERIFY(object != 0);
    QCOMPARE(object->property("width").toInt(), 300);
    delete object;

    foreach (QDeclarativeError err, component.errors())
        qWarning() << err;
    VERIFY_ERRORS(0);
}

// QTBUG-17324
void tst_qdeclarativemoduleplugin::importsMixedQmlCppPlugin()
{
    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());

    {
    QDeclarativeComponent component(&engine, testFileUrl("importsMixedQmlCppPlugin.qml"));

    QObject *o = component.create();
    QVERIFY2(o, msgComponentError(component, &engine).constData());
    QCOMPARE(o->property("test").toBool(), true);
    delete o;
    }

    {
    QDeclarativeComponent component(&engine, testFileUrl("importsMixedQmlCppPlugin.2.qml"));

    QObject *o = component.create();
    QVERIFY(o != 0);
    QCOMPARE(o->property("test").toBool(), true);
    QCOMPARE(o->property("test2").toBool(), true);
    delete o;
    }

}

void tst_qdeclarativemoduleplugin::versionNotInstalled_data()
{
    QTest::addColumn<QString>("file");
    QTest::addColumn<QString>("errorFile");

    QTest::newRow("versionNotInstalled") << "versionNotInstalled.qml" << "versionNotInstalled.errors.txt";
    QTest::newRow("versionNotInstalled") << "versionNotInstalled.2.qml" << "versionNotInstalled.2.errors.txt";
}

void tst_qdeclarativemoduleplugin::versionNotInstalled()
{
    QFETCH(QString, file);
    QFETCH(QString, errorFile);

    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());

    QDeclarativeComponent component(&engine, testFileUrl(file));
    VERIFY_ERRORS(errorFile.toLatin1().constData());
}

QTEST_MAIN(tst_qdeclarativemoduleplugin)

#include "tst_qdeclarativemoduleplugin.moc"
<commit_msg>tests: fix tst_qdeclarativemoduleplugin::incorrectPluginCase()<commit_after>/****************************************************************************
**
** Copyright (C) 2013 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the test suite of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU General Public License version 3.0 requirements will be
** met: http://www.gnu.org/copyleft/gpl.html.
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qtest.h>
#include <qdeclarativedatatest.h>
#include <qdir.h>
#include <QtDeclarative/qdeclarativeengine.h>
#include <QtDeclarative/qdeclarativecomponent.h>
#include <QDebug>
#include <QtCore/qlibraryinfo.h>

#include "../shared/testhttpserver.h"

#define SERVER_ADDR "http://127.0.0.1:14450"
#define SERVER_PORT 14450

class tst_qdeclarativemoduleplugin : public QDeclarativeDataTest
{
    Q_OBJECT
public:
    tst_qdeclarativemoduleplugin()
    {
    }

private slots:
    void importsPlugin();
    void importsPlugin2();
    void importsPlugin21();
    void importsMixedQmlCppPlugin();
    void incorrectPluginCase();
    void importPluginWithQmlFile();
    void remoteImportWithQuotedUrl();
    void remoteImportWithUnquotedUri();
    void versionNotInstalled();
    void versionNotInstalled_data();
};

#define VERIFY_ERRORS(errorfile) \
    if (!errorfile) { \
        if (qgetenv("DEBUG") != "" && !component.errors().isEmpty()) \
            qWarning() << "Unexpected Errors:" << component.errors(); \
        QVERIFY(!component.isError()); \
        QVERIFY(component.errors().isEmpty()); \
    } else { \
        QFile file(testFile(errorfile)); \
        QVERIFY(file.open(QIODevice::ReadOnly | QIODevice::Text)); \
        QByteArray data = file.readAll(); \
        file.close(); \
        QList<QByteArray> expected = data.split('\n'); \
        expected.removeAll(QByteArray("")); \
        QList<QDeclarativeError> errors = component.errors(); \
        QList<QByteArray> actual; \
        for (int ii = 0; ii < errors.count(); ++ii) { \
            const QDeclarativeError &error = errors.at(ii); \
            QByteArray errorStr = QByteArray::number(error.line()) + ":" +  \
                                  QByteArray::number(error.column()) + ":" + \
                                  error.description().toUtf8(); \
            actual << errorStr; \
        } \
        if (qgetenv("DEBUG") != "" && expected != actual) \
            qWarning() << "Expected:" << expected << "Actual:" << actual;  \
        if (qgetenv("QDECLARATIVELANGUAGE_UPDATEERRORS") != "" && expected != actual) {\
            QFile file(testFile(errorfile)); \
            QVERIFY(file.open(QIODevice::WriteOnly)); \
            for (int ii = 0; ii < actual.count(); ++ii) { \
                file.write(actual.at(ii)); file.write("\n"); \
            } \
            file.close(); \
        } else { \
            QCOMPARE(expected, actual); \
        } \
    }

void tst_qdeclarativemoduleplugin::importsPlugin()
{
    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());
    QTest::ignoreMessage(QtWarningMsg, "plugin created");
    QTest::ignoreMessage(QtWarningMsg, "import worked");
    QDeclarativeComponent component(&engine, testFileUrl("works.qml"));
    foreach (QDeclarativeError err, component.errors())
    	qWarning() << err;
    VERIFY_ERRORS(0);
    QObject *object = component.create();
    QVERIFY(object != 0);
    QCOMPARE(object->property("value").toInt(),123);
    delete object;
}

void tst_qdeclarativemoduleplugin::importsPlugin2()
{
    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());
    QTest::ignoreMessage(QtWarningMsg, "plugin2 created");
    QTest::ignoreMessage(QtWarningMsg, "import2 worked");
    QDeclarativeComponent component(&engine, testFileUrl("works2.qml"));
    foreach (QDeclarativeError err, component.errors())
        qWarning() << err;
    VERIFY_ERRORS(0);
    QObject *object = component.create();
    QVERIFY(object != 0);
    QCOMPARE(object->property("value").toInt(),123);
    delete object;
}

void tst_qdeclarativemoduleplugin::importsPlugin21()
{
    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());
    QTest::ignoreMessage(QtWarningMsg, "plugin2.1 created");
    QTest::ignoreMessage(QtWarningMsg, "import2.1 worked");
    QDeclarativeComponent component(&engine, testFileUrl("works21.qml"));
    foreach (QDeclarativeError err, component.errors())
        qWarning() << err;
    VERIFY_ERRORS(0);
    QObject *object = component.create();
    QVERIFY(object != 0);
    QCOMPARE(object->property("value").toInt(),123);
    delete object;
}

void tst_qdeclarativemoduleplugin::incorrectPluginCase()
{
    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());

    QDeclarativeComponent component(&engine, testFileUrl("incorrectCase.qml"));

    QList<QDeclarativeError> errors = component.errors();
    QCOMPARE(errors.count(), 1);

    QString expectedError = QLatin1String("module \"org.qtproject.WrongCase\" plugin \"PluGin\" not found");

#if defined(Q_OS_MAC) || defined(Q_OS_WIN32)
    bool caseSensitive = true;
#if defined(Q_OS_MAC)
    caseSensitive = pathconf(QDir::currentPath().toLatin1().constData(), _PC_CASE_SENSITIVE);
    QString libname = "libPluGin.dylib";
#elif defined(Q_OS_WIN32)
    caseSensitive = false;
    QString libname = "PluGin.dll";
#endif
    if (!caseSensitive)
        expectedError = QLatin1String("plugin cannot be loaded for module \"org.qtproject.WrongCase\": File name case mismatch for \"") + QDir(importsDirectory()).filePath("org/qtproject/WrongCase/" + libname) + QLatin1String("\"");
#endif

    QCOMPARE(errors.at(0).description(), expectedError);
}

void tst_qdeclarativemoduleplugin::importPluginWithQmlFile()
{
    QString path = importsDirectory();

    // QTBUG-16885: adding an import path with a lower-case "c:" causes assert failure
    // (this only happens if the plugin includes pure QML files)
    #ifdef Q_OS_WIN
    if (path.size() > 1 && path.at(0).isUpper() && path.at(1) == QLatin1Char(':'))
        path = path.at(0).toLower() + path.mid(1);
    #endif

    QDeclarativeEngine engine;
    engine.addImportPath(path);

    QDeclarativeComponent component(&engine, testFileUrl("pluginWithQmlFile.qml"));
    foreach (QDeclarativeError err, component.errors())
        qWarning() << err;
    VERIFY_ERRORS(0);
    QObject *object = component.create();
    QVERIFY(object != 0);
    delete object;
}

void tst_qdeclarativemoduleplugin::remoteImportWithQuotedUrl()
{
    TestHTTPServer server(SERVER_PORT);
    QVERIFY(server.isValid());
    server.serveDirectory(importsDirectory());

    QDeclarativeEngine engine;
    QDeclarativeComponent component(&engine);
    component.setData("import \"http://127.0.0.1:14450/org/qtproject/PureQmlModule\" \nComponentA { width: 300; ComponentB{} }", QUrl());

    QTRY_COMPARE(component.status(), QDeclarativeComponent::Ready);
    QObject *object = component.create();
    QCOMPARE(object->property("width").toInt(), 300);
    QVERIFY(object != 0);
    delete object;

    foreach (QDeclarativeError err, component.errors())
        qWarning() << err;
    VERIFY_ERRORS(0);
}

void tst_qdeclarativemoduleplugin::remoteImportWithUnquotedUri()
{
    TestHTTPServer server(SERVER_PORT);
    QVERIFY(server.isValid());
    server.serveDirectory(directory() + QStringLiteral("/imports"));

    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());
    QDeclarativeComponent component(&engine);
    component.setData("import org.qtproject.PureQmlModule 1.0 \nComponentA { width: 300; ComponentB{} }", QUrl());

    QTRY_COMPARE(component.status(), QDeclarativeComponent::Ready);
    QObject *object = component.create();
    QVERIFY(object != 0);
    QCOMPARE(object->property("width").toInt(), 300);
    delete object;

    foreach (QDeclarativeError err, component.errors())
        qWarning() << err;
    VERIFY_ERRORS(0);
}

// QTBUG-17324
void tst_qdeclarativemoduleplugin::importsMixedQmlCppPlugin()
{
    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());

    {
    QDeclarativeComponent component(&engine, testFileUrl("importsMixedQmlCppPlugin.qml"));

    QObject *o = component.create();
    QVERIFY2(o, msgComponentError(component, &engine).constData());
    QCOMPARE(o->property("test").toBool(), true);
    delete o;
    }

    {
    QDeclarativeComponent component(&engine, testFileUrl("importsMixedQmlCppPlugin.2.qml"));

    QObject *o = component.create();
    QVERIFY(o != 0);
    QCOMPARE(o->property("test").toBool(), true);
    QCOMPARE(o->property("test2").toBool(), true);
    delete o;
    }

}

void tst_qdeclarativemoduleplugin::versionNotInstalled_data()
{
    QTest::addColumn<QString>("file");
    QTest::addColumn<QString>("errorFile");

    QTest::newRow("versionNotInstalled") << "versionNotInstalled.qml" << "versionNotInstalled.errors.txt";
    QTest::newRow("versionNotInstalled") << "versionNotInstalled.2.qml" << "versionNotInstalled.2.errors.txt";
}

void tst_qdeclarativemoduleplugin::versionNotInstalled()
{
    QFETCH(QString, file);
    QFETCH(QString, errorFile);

    QDeclarativeEngine engine;
    engine.addImportPath(importsDirectory());

    QDeclarativeComponent component(&engine, testFileUrl(file));
    VERIFY_ERRORS(errorFile.toLatin1().constData());
}

QTEST_MAIN(tst_qdeclarativemoduleplugin)

#include "tst_qdeclarativemoduleplugin.moc"
<|endoftext|>