void InterpolationDialog::interpolate()
{
	QString curve = boxName->currentText();
	QStringList curvesList = graph->analysableCurvesList();
	if (!curvesList.contains(curve)){
		QMessageBox::critical(this,tr("QtiPlot - Warning"),
		tr("The curve <b> %1 </b> doesn't exist anymore! Operation aborted!").arg(curve));
		boxName->clear();
		boxName->addItems(curvesList);
		return;
	}

	double from = boxStart->value();
	double to = boxEnd->value();
	if (from >= to){
		QMessageBox::critical(this, tr("QtiPlot - Input error"), tr("Please enter x limits that satisfy: from < to!"));
		boxEnd->setFocus();
		return;
	}

	Interpolation *i = new Interpolation((ApplicationWindow *)parent(), (QwtPlotCurve *)graph->curve(boxName->currentIndex()), from, to, boxMethod->currentIndex());
	i->setOutputPoints(boxPoints->value());
	i->setColor(boxColor->color());
	i->run();
	delete i;
}
void BaselineDialog::createBaseline()
{
	ApplicationWindow *app = (ApplicationWindow *)parent();
	QPen pen = QPen(Qt::red);

	if (d_baseline){
		pen = d_baseline->pen();
		graph->removeCurve(d_baseline->title().text());
		delete d_baseline;
		d_baseline = NULL;

		if (d_table){
			d_table->askOnCloseEvent(false);
			app->closeWindow(d_table);
			d_table = NULL;
		}
	}

	disableBaselineTool();

	if (btnAutomatic->isChecked()){
		Interpolation *i = new Interpolation(app, graph, boxInputName->currentText(), boxInterpolationMethod->currentIndex());
		i->setOutputPoints(boxPoints->value());
		i->run();
		delete i;
		d_baseline = graph->dataCurve(graph->curveCount() - 1);
		d_table = ((DataCurve *)d_baseline)->table();
	} else if (btnEquation->isChecked()){
		double start = graph->axisScaleDiv(QwtPlot::xBottom)->lowerBound();
		double end = graph->axisScaleDiv(QwtPlot::xBottom)->upperBound();
		DataCurve *c = graph->dataCurve(graph->curveIndex(boxInputName->currentText()));
		if (c){
			start = c->minXValue();
			end = c->maxXValue();
		}
		d_baseline = graph->addFunction(QStringList() << boxEquation->text(), start, end, boxPoints->value(), "x", FunctionCurve::Normal, tr("Baseline"));
	} else if (btnDataset->isChecked()){
		Table *t = app->table(boxTableName->currentText());
		if (t){
			int rows = t->numRows();
			d_table = app->newTable(rows, 2);
			app->setWindowName(d_table, tr("Baseline"));
			app->hideWindow(d_table);
			int ycol = t->colIndex(boxColumnName->currentText());
			int xcol = t->colX(ycol);
			for (int i = 0; i < rows; i++){
				d_table->setText(i, 0, t->text(i, xcol));
				d_table->setText(i, 1, t->text(i, ycol));
			}
			d_baseline = graph->insertCurve(d_table, d_table->objectName() + "_2", Graph::Line, 0, -1);
			graph->setAutoScale();
		}
	}

	if (d_baseline){
		d_baseline->setPen(pen);
		graph->replot();
	}
}
Esempio n. 3
0
bool Interpolation::operator == (const Interpolation& interpolation) const
{
  return 
    (this->getType() == interpolation.getType()) &&
    (this->value_0_ == interpolation.value_0_) &&
    (this->value_1_ == interpolation.value_1_);
}
Esempio n. 4
0
void Animation::dump()
{
	int controller_size;
	int actions_size;

	int controller_task;
	action_t action;
	Interpolation interp;

	controller_size = _controller.size();

	for (int i = 0; i < controller_size; i++)
	{
		controller_task = _controller.front();
		_controller.pop();
		_controller.push(controller_task);

		if (controller_task == ANIM_CTR_ACTION)
		{
			action = _actions.front();
			_actions.pop();
			_actions.push(action);

			continue;
		}

		interp = _interps.front();
		_interps.pop();
		_interps.push(interp);

		actions_size = interp.actions().size();

		for (int j = 0; j < actions_size; j++)
		{
			action = interp.actions()[j];
		}
	}
}
void VannaVolgaDoubleBarrierEngine::calculate() const {

    const Real sigmaShift_vega = 0.001;
    const Real sigmaShift_volga = 0.0001;
    const Real spotShift_delta = 0.0001 * spotFX_->value();
    const Real sigmaShift_vanna = 0.0001;

    Handle<Quote> x0Quote(  //used for shift
        boost::make_shared<SimpleQuote>(spotFX_->value()));
    Handle<Quote> atmVolQuote( //used for shift
        boost::make_shared<SimpleQuote>(atmVol_->value()));

    boost::shared_ptr<BlackVolTermStructure> blackVolTS =
        boost::make_shared<BlackConstantVol>(
            Settings::instance().evaluationDate(),
            NullCalendar(), atmVolQuote, Actual365Fixed());
    boost::shared_ptr<BlackScholesMertonProcess> stochProcess =
        boost::make_shared<BlackScholesMertonProcess>(
            x0Quote,
            foreignTS_,
            domesticTS_,
            Handle<BlackVolTermStructure>(blackVolTS));

    boost::shared_ptr<PricingEngine> engineBS =
        boost::make_shared<AnalyticDoubleBarrierEngine>(stochProcess,
                series_);

    BlackDeltaCalculator blackDeltaCalculatorAtm(
        Option::Call, atmVol_->deltaType(), x0Quote->value(),
        domesticTS_->discount(T_), foreignTS_->discount(T_),
        atmVol_->value() * sqrt(T_));
    Real atmStrike = blackDeltaCalculatorAtm.atmStrike(atmVol_->atmType());

    Real call25Vol = vol25Call_->value();
    Real put25Vol = vol25Put_->value();
    BlackDeltaCalculator blackDeltaCalculatorPut25(
        Option::Put, vol25Put_->deltaType(), x0Quote->value(),
        domesticTS_->discount(T_), foreignTS_->discount(T_),
        put25Vol * sqrt(T_));
    Real put25Strike = blackDeltaCalculatorPut25.strikeFromDelta(-0.25);
    BlackDeltaCalculator blackDeltaCalculatorCall25(
        Option::Call, vol25Call_->deltaType(), x0Quote->value(),
        domesticTS_->discount(T_), foreignTS_->discount(T_),
        call25Vol * sqrt(T_));
    Real call25Strike = blackDeltaCalculatorCall25.strikeFromDelta(0.25);

    //here use vanna volga interpolated smile to price vanilla
    std::vector<Real> strikes;
    std::vector<Real> vols;
    strikes.push_back(put25Strike);
    vols.push_back(put25Vol);
    strikes.push_back(atmStrike);
    vols.push_back(atmVol_->value());
    strikes.push_back(call25Strike);
    vols.push_back(call25Vol);
    VannaVolga vannaVolga(x0Quote->value(), foreignTS_->discount(T_), foreignTS_->discount(T_), T_);
    Interpolation interpolation = vannaVolga.interpolate(strikes.begin(), strikes.end(), vols.begin());
    interpolation.enableExtrapolation();
    const boost::shared_ptr<StrikedTypePayoff> payoff =
        boost::dynamic_pointer_cast<StrikedTypePayoff>(arguments_.payoff);
    Real strikeVol = interpolation(payoff->strike());
    //vannila option price
    Real vanillaOption = blackFormula(payoff->optionType(), payoff->strike(),
                                      x0Quote->value()* foreignTS_->discount(T_)/ domesticTS_->discount(T_),
                                      strikeVol * sqrt(T_),
                                      domesticTS_->discount(T_));

    //already out
    if((x0Quote->value() > arguments_.barrier[1] || x0Quote->value() < arguments_.barrier[0])
            && arguments_.barrierType[0] == Barrier::DownOut) {
        results_.value = 0.0;
        results_.additionalResults["VanillaPrice"] = adaptVanDelta_? bsPriceWithSmile_ : vanillaOption;
        results_.additionalResults["BarrierInPrice"] = adaptVanDelta_? bsPriceWithSmile_ : vanillaOption;
        results_.additionalResults["BarrierOutPrice"] = 0.0;
    }
    //already in
    else if((x0Quote->value() > arguments_.barrier[1] || x0Quote->value() < arguments_.barrier[0])
            && arguments_.barrierType[0] == Barrier::DownIn) {
        results_.value = adaptVanDelta_? bsPriceWithSmile_ : vanillaOption;
        results_.additionalResults["VanillaPrice"] = adaptVanDelta_? bsPriceWithSmile_ : vanillaOption;
        results_.additionalResults["BarrierInPrice"] = adaptVanDelta_? bsPriceWithSmile_ : vanillaOption;
        results_.additionalResults["BarrierOutPrice"] = 0.0;
    }
    else {

        //set up BS barrier option pricing
        //only calculate out barrier option price
        // in barrier price = vanilla - out barrier
        boost::shared_ptr<StrikedTypePayoff> payoff
            = boost::static_pointer_cast<StrikedTypePayoff> (arguments_.payoff);
        DoubleBarrierOption doubleBarrierOption(arguments_.barrierType,
                                                arguments_.barrier,
                                                arguments_.rebate,
                                                payoff,
                                                arguments_.exercise);

        doubleBarrierOption.setPricingEngine(engineBS);

        //BS price
        Real priceBS = doubleBarrierOption.NPV();

        Real priceAtmCallBS = blackFormula(Option::Call,atmStrike,
                                           x0Quote->value()* foreignTS_->discount(T_)/ domesticTS_->discount(T_),
                                           atmVol_->value() * sqrt(T_),
                                           domesticTS_->discount(T_));
        Real price25CallBS = blackFormula(Option::Call,call25Strike,
                                          x0Quote->value()* foreignTS_->discount(T_)/ domesticTS_->discount(T_),
                                          atmVol_->value() * sqrt(T_),
                                          domesticTS_->discount(T_));
        Real price25PutBS = blackFormula(Option::Put,put25Strike,
                                         x0Quote->value()* foreignTS_->discount(T_)/ domesticTS_->discount(T_),
                                         atmVol_->value() * sqrt(T_),
                                         domesticTS_->discount(T_));

        //market price
        Real priceAtmCallMkt = blackFormula(Option::Call,atmStrike,
                                            x0Quote->value()* foreignTS_->discount(T_)/ domesticTS_->discount(T_),
                                            atmVol_->value() * sqrt(T_),
                                            domesticTS_->discount(T_));
        Real price25CallMkt = blackFormula(Option::Call,call25Strike,
                                           x0Quote->value()* foreignTS_->discount(T_)/ domesticTS_->discount(T_),
                                           call25Vol * sqrt(T_),
                                           domesticTS_->discount(T_));
        Real price25PutMkt = blackFormula(Option::Put,put25Strike,
                                          x0Quote->value()* foreignTS_->discount(T_)/ domesticTS_->discount(T_),
                                          put25Vol * sqrt(T_),
                                          domesticTS_->discount(T_));

        //Analytical Black Scholes formula
        NormalDistribution norm;
        Real d1atm = (std::log(x0Quote->value()* foreignTS_->discount(T_)/ domesticTS_->discount(T_)/atmStrike)
                      + 0.5*std::pow(atmVolQuote->value(),2.0) * T_)/(atmVolQuote->value() * sqrt(T_));
        Real vegaAtm_Analytical = x0Quote->value() * norm(d1atm) * sqrt(T_) * foreignTS_->discount(T_);
        Real vannaAtm_Analytical = vegaAtm_Analytical/x0Quote->value() *(1.0 - d1atm/(atmVolQuote->value()*sqrt(T_)));
        Real volgaAtm_Analytical = vegaAtm_Analytical * d1atm * (d1atm - atmVolQuote->value() * sqrt(T_))/atmVolQuote->value();

        Real d125call = (std::log(x0Quote->value()* foreignTS_->discount(T_)/ domesticTS_->discount(T_)/call25Strike)
                         + 0.5*std::pow(atmVolQuote->value(),2.0) * T_)/(atmVolQuote->value() * sqrt(T_));
        Real vega25Call_Analytical = x0Quote->value() * norm(d125call) * sqrt(T_) * foreignTS_->discount(T_);
        Real vanna25Call_Analytical = vega25Call_Analytical/x0Quote->value() *(1.0 - d125call/(atmVolQuote->value()*sqrt(T_)));
        Real volga25Call_Analytical = vega25Call_Analytical * d125call * (d125call - atmVolQuote->value() * sqrt(T_))/atmVolQuote->value();

        Real d125Put = (std::log(x0Quote->value()* foreignTS_->discount(T_)/ domesticTS_->discount(T_)/put25Strike)
                        + 0.5*std::pow(atmVolQuote->value(),2.0) * T_)/(atmVolQuote->value() * sqrt(T_));
        Real vega25Put_Analytical = x0Quote->value() * norm(d125Put) * sqrt(T_) * foreignTS_->discount(T_);
        Real vanna25Put_Analytical = vega25Put_Analytical/x0Quote->value() *(1.0 - d125Put/(atmVolQuote->value()*sqrt(T_)));
        Real volga25Put_Analytical = vega25Put_Analytical * d125Put * (d125Put - atmVolQuote->value() * sqrt(T_))/atmVolQuote->value();


        //BS vega
        boost::static_pointer_cast<SimpleQuote> (atmVolQuote.currentLink())->setValue(atmVolQuote->value() + sigmaShift_vega);
        doubleBarrierOption.recalculate();
        Real vegaBarBS = (doubleBarrierOption.NPV() - priceBS)/sigmaShift_vega;
        boost::static_pointer_cast<SimpleQuote> (atmVolQuote.currentLink())->setValue(atmVolQuote->value() - sigmaShift_vega);//setback

        //BS volga

        //vegaBar2
        //base NPV
        boost::static_pointer_cast<SimpleQuote> (atmVolQuote.currentLink())->setValue(atmVolQuote->value() + sigmaShift_volga);
        doubleBarrierOption.recalculate();
        Real priceBS2 = doubleBarrierOption.NPV();

        //shifted npv
        boost::static_pointer_cast<SimpleQuote> (atmVolQuote.currentLink())->setValue(atmVolQuote->value() + sigmaShift_vega);
        doubleBarrierOption.recalculate();
        Real vegaBarBS2 = (doubleBarrierOption.NPV() - priceBS2)/sigmaShift_vega;
        Real volgaBarBS = (vegaBarBS2 - vegaBarBS)/sigmaShift_volga;
        boost::static_pointer_cast<SimpleQuote> (atmVolQuote.currentLink())->setValue(atmVolQuote->value()
                - sigmaShift_volga
                - sigmaShift_vega);//setback

        //BS Delta
        //base delta
        boost::static_pointer_cast<SimpleQuote> (x0Quote.currentLink())->setValue(x0Quote->value() + spotShift_delta);//shift forth
        doubleBarrierOption.recalculate();
        Real priceBS_delta1 = doubleBarrierOption.NPV();

        boost::static_pointer_cast<SimpleQuote> (x0Quote.currentLink())->setValue(x0Quote->value() - 2 * spotShift_delta);//shift back
        doubleBarrierOption.recalculate();
        Real priceBS_delta2 = doubleBarrierOption.NPV();

        boost::static_pointer_cast<SimpleQuote> (x0Quote.currentLink())->setValue(x0Quote->value() +  spotShift_delta);//set back
        Real deltaBar1 = (priceBS_delta1 - priceBS_delta2)/(2.0*spotShift_delta);

        //shifted vanna
        boost::static_pointer_cast<SimpleQuote> (atmVolQuote.currentLink())->setValue(atmVolQuote->value() + sigmaShift_vanna);//shift sigma
        //shifted delta
        boost::static_pointer_cast<SimpleQuote> (x0Quote.currentLink())->setValue(x0Quote->value() + spotShift_delta);//shift forth
        doubleBarrierOption.recalculate();
        priceBS_delta1 = doubleBarrierOption.NPV();

        boost::static_pointer_cast<SimpleQuote> (x0Quote.currentLink())->setValue(x0Quote->value() - 2 * spotShift_delta);//shift back
        doubleBarrierOption.recalculate();
        priceBS_delta2 = doubleBarrierOption.NPV();

        boost::static_pointer_cast<SimpleQuote> (x0Quote.currentLink())->setValue(x0Quote->value() +  spotShift_delta);//set back
        Real deltaBar2 = (priceBS_delta1 - priceBS_delta2)/(2.0*spotShift_delta);

        Real vannaBarBS = (deltaBar2 - deltaBar1)/sigmaShift_vanna;

        boost::static_pointer_cast<SimpleQuote> (atmVolQuote.currentLink())->setValue(atmVolQuote->value() - sigmaShift_vanna);//set back

        //Matrix
        Matrix A(3,3,0.0);

        //analytical
        A[0][0] = vegaAtm_Analytical;
        A[0][1] = vega25Call_Analytical;
        A[0][2] = vega25Put_Analytical;
        A[1][0] = vannaAtm_Analytical;
        A[1][1] = vanna25Call_Analytical;
        A[1][2] = vanna25Put_Analytical;
        A[2][0] = volgaAtm_Analytical;
        A[2][1] = volga25Call_Analytical;
        A[2][2] = volga25Put_Analytical;

        Array b(3,0.0);
        b[0] = vegaBarBS;
        b[1] = vannaBarBS;
        b[2] = volgaBarBS;
        Array q = inverse(A) * b;

        Real H = arguments_.barrier[1];
        Real L = arguments_.barrier[0];
        Real theta_tilt_minus = ((domesticTS_->zeroRate(T_, Continuous) - foreignTS_->zeroRate(T_, Continuous))/atmVol_->value() - atmVol_->value()/2.0)*std::sqrt(T_);
        Real h = 1.0/atmVol_->value() * std::log(H/x0Quote->value())/std::sqrt(T_);
        Real l = 1.0/atmVol_->value() * std::log(L/x0Quote->value())/std::sqrt(T_);
        CumulativeNormalDistribution cnd;

        Real doubleNoTouch = 0.0;
        for(int j = -series_; j< series_; j++ ) {
            Real e_minus = 2*j*(h-l) - theta_tilt_minus;
            doubleNoTouch += std::exp(-2.0*j*theta_tilt_minus*(h-l))*(cnd(h+e_minus) - cnd(l+e_minus))
                             - std::exp(-2.0*j*theta_tilt_minus*(h-l)+2.0*theta_tilt_minus*h)*(cnd(h-2.0*h+e_minus) - cnd(l-2.0*h+e_minus));
        }

        Real p_survival = doubleNoTouch;

        Real lambda = p_survival ;
        Real adjust = q[0]*(priceAtmCallMkt - priceAtmCallBS)
                      + q[1]*(price25CallMkt - price25CallBS)
                      + q[2]*(price25PutMkt - price25PutBS);
        Real outPrice = priceBS + lambda*adjust;//
        Real inPrice;

        //adapt Vanilla delta
        if(adaptVanDelta_ == true) {
            outPrice += lambda*(bsPriceWithSmile_ - vanillaOption);
            //capfloored by (0, vanilla)
            outPrice = std::max(0.0, std::min(bsPriceWithSmile_, outPrice));
            inPrice = bsPriceWithSmile_ - outPrice;
        }
        else {
            //capfloored by (0, vanilla)
            outPrice = std::max(0.0, std::min(vanillaOption , outPrice));
            inPrice = vanillaOption - outPrice;
        }

        if(arguments_.barrierType[0] == Barrier::DownOut)
            results_.value = outPrice;
        else
            results_.value = inPrice;
        results_.additionalResults["VanillaPrice"] = vanillaOption;
        results_.additionalResults["BarrierInPrice"] = inPrice;
        results_.additionalResults["BarrierOutPrice"] = outPrice;
        results_.additionalResults["lambda"] = lambda;
    }
}
Esempio n. 6
0
int main(int argc, char **argv)
{


    int rank = 0;
    int process_count = 1;
    int reader_count = 1;
    int buffer_size = 10000;
    int is_mpi = 0;
    mpi_times *timer = NULL;
    // end, mpi variables
    clock_t t0, t1;

    // parameters
    char inputName[1024] = {0};
    char inputURL[2048] = {0};
    char outputName[1024] = {0};

    int input_format = INPUT_LAS;
    int interpolation_mode = INTERP_AUTO;
    int output_format = 0;
    unsigned int type = 0x00000000;
    double GRID_DIST_X = 6.0;
    double GRID_DIST_Y = 6.0;
    double searchRadius = (double) sqrt(2.0) * GRID_DIST_X;
    int window_size = 0;

    // argument processing..
    po::options_description general("General options"),
    df("Data file"),
    ot("Output Type"),
    res("Resolution"),
    nf("Null Filling"),
    desc;

    general.add_options()
    ("help", "produce a help message")
    ("output_file_name,o", po::value<std::string>(), "required. name of output file without extension, i.e. if you want the output file to be test.asc, this parameter shoud be \"test\"")
    ("search_radius,r", po::value<float>(), "specifies the search radius. The default value is square root 2 of horizontal distance in a grid cell")
    ("output_format", po::value<std::string>(), "'all' generates every possible format,\n"
     "'arc' for ArcGIS format,\n"
     "'grid' for Ascii GRID format,\n"
     "the default value is --all")
    ("input_format", po::value<std::string>(), "'ascii' expects input point cloud in ASCII format\n"
     "'las' expects input point cloud in LAS format (default)")
    ("interpolation_mode,m", po::value<std::string>()->default_value("auto"), "'incore' stores working data in memory\n"
     "'outcore' stores working data on the filesystem, 'parallel' uses number of processes specified by mpirun -n\n"
     "'auto' (default) guesses based on the size of the data file")
    ("reader_count,c", po::value<int>(), "when interpolation mode is 'parallel', arg is number of reader processes, default is 1")
    ("buffer_size,b", po::value<int>(), "when interpolation mode is 'parallel', arg is write buffer size in bytes, default is 10000 bytes")
    ("mpi_times,t", "time mpi run");

    df.add_options()
#ifdef CURL_FOUND
    ("data_file_name,i", po::value<std::string>(), "path to unzipped plain text data file")
    ("data_file_url,l", po::value<std::string>(), "URL of unzipped plain text data file"
     "You must specify either a data_file_name or data_file_url.");
#else
    ("data_file_name,i", po::value<std::string>(), "required. path to unzipped plain text data file");
#endif

    ot.add_options()
    ("min", "the Zmin values are stored")
    ("max", "the Zmax values are stored")
    ("mean", "the Zmean values are stored")
    ("idw", "the Zidw values are stored")
    ("std", "the Zstd values are stored")
    ("den", "the density values are stored")
    ("all", "all the values are stored (default)");

    res.add_options()
    ("resolution", po::value<float>(), "The resolution is set to the specified value. Use square grids.\n"
     "If no resolution options are specified, a 6 unit square grid is used")
    ("resolution-x", po::value<float>(), "The X side of grid cells is set to the specified value")
    ("resolution-y", po::value<float>(), "The Y side of grid cells is set to the specified value");

    nf.add_options()
    ("fill", "fills nulls in the DEM. Default window size is 3.")
    ("fill_window_size", po::value<int>(), "The fill window is set to value. Permissible values are 3, 5 and 7.");

    desc.add(general).add(df).add(ot).add(res).add(nf);

    po::variables_map vm;

    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);

        if (vm.count("help")) {
            cout << "------------------------------------------------------------------------" << endl;
            cout << "   " << appName << " (development version )" << endl;
            cout << "------------------------------------------------------------------------" << endl;
            cout << "Usage: " << appName << " [options]" << endl;
            cout << desc << endl;
            exit(0);
        }

        po::notify(vm);


        if (vm.count("output_format")) {
            std::string of = vm["output_format"].as<std::string>();
            if(of.compare("all") == 0) {
                output_format = OUTPUT_FORMAT_ALL;
            }
            else if(of.compare("arc") == 0)
                output_format = OUTPUT_FORMAT_ARC_ASCII;
            else if(of.compare("grid") == 0)
                output_format = OUTPUT_FORMAT_GRID_ASCII;
            else {
                throw std::logic_error("'" + of + "' is not a recognized output_format");
            }
        }
        // resolution
        if(vm.count("resolution")) {
            float res = vm["resolution"].as<float>();
            GRID_DIST_X = res;
            GRID_DIST_Y = res;
            if(searchRadius == sqrt(2.0) * 6.0)
                searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

            if(GRID_DIST_X == 0) {
                throw std::logic_error("resolution must not be 0");
            }
        }

        if(vm.count("resolution-x")) {
            GRID_DIST_X = vm["resolution-x"].as<float>();
            if(searchRadius == sqrt(2.0) * 6.0)
                searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

            if(GRID_DIST_X == 0) {
                throw std::logic_error("resolution-x must not be 0");
            }
        }

        if(vm.count("resolution-y")) {
            GRID_DIST_Y = vm["resolution-y"].as<float>();
            if(GRID_DIST_Y == 0) {
                throw std::logic_error("resolution-y must not be 0");
            }
        }

        if(vm.count("min")) {
            type |= OUTPUT_TYPE_MIN;
        }

        if(vm.count("max")) {
            type |= OUTPUT_TYPE_MAX;
        }

        if(vm.count("mean")) {
            type |= OUTPUT_TYPE_MEAN;
        }

        if(vm.count("idw")) {
            type |= OUTPUT_TYPE_IDW;
        }

        if(vm.count("std")) {
            type |= OUTPUT_TYPE_STD;
        }

        if(vm.count("den")) {
            type |= OUTPUT_TYPE_DEN;
        }

        if(vm.count("all")) {
            type = OUTPUT_TYPE_ALL;
        }

        if(vm.count("fill")) {
            window_size = 3;
        }

        if(vm.count("fill_window_size")) {
            window_size = vm["fill_window_size"].as<int>();
            if(!((window_size == 3) || (window_size == 5) || (window_size == 7))) {
                throw std::logic_error("window-size must be either 3, 5, or 7");
            }
        }

        if(vm.count("input_format")) {
            std::string inf = vm["input_format"].as<std::string>();

            if(inf.compare("ascii") == 0)
                input_format = INPUT_ASCII;
            else if(inf.compare("las") == 0)
                input_format = INPUT_LAS;
            else {
                throw std::logic_error("'" + inf + "' is not a recognized input_format");
            }
        }


#ifdef CURL_FOUND
        if(vm.count("data_file_name")) {
            strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
        }
        if(vm.count("data_file_url")) {
            strncpy(inputURL, vm["data_file_url"].as<std::string>().c_str(), sizeof(inputURL));
        }

        if((inputName == NULL || !strcmp(inputName, "")) &&
                (inputURL == NULL || !strcmp(inputURL, "")))
        {
            throw std::logic_error("you must specify a valid data file");
        }
#else
        if(!vm.count("data_file_name")) {
            throw std::logic_error("data_file_name  must be specified");
        }
        else {
            strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
            if (!strcmp(inputName, "")) {
                throw std::logic_error("data_file_name must not be an empty string");
            }
        }
#endif

        if (!vm.count("output_file_name")) {
            throw std::logic_error("output_file_name must be specified");
        }
        else {
            strncpy(outputName, vm["output_file_name"].as<std::string>().c_str(), sizeof(outputName));
        }

        if(vm.count("search_radius")) {
            searchRadius = vm["search_radius"].as<float>();
        }

        if(vm.count("interpolation_mode")) {
            std::string im(vm["interpolation_mode"].as<std::string>());
            if (im.compare("auto") == 0) {
                interpolation_mode = INTERP_AUTO;
            }
            else if (im.compare("incore") == 0) {
                interpolation_mode = INTERP_INCORE;
            }
            else if (im.compare("outcore") == 0) {
                interpolation_mode = INTERP_OUTCORE;
            }
            else if (im.compare("parallel") == 0) {
                interpolation_mode = INTERP_MPI;
            }
            else {
                throw std::logic_error("'" + im + "' is not a recognized interpolation_mode");
            }
        }

        if(type == 0)
            type = OUTPUT_TYPE_ALL;

        if(vm.count("reader_count")) {
            reader_count = vm["reader_count"].as<int>();
        }
        if(vm.count("buffer_size")) {
            buffer_size = vm["buffer_size"].as<int>();
        }
        if(vm.count("mpi_times")) {
            timer = (mpi_times *)malloc(sizeof(mpi_times));
        }

#ifdef CURL_FOUND
        // download file from URL, and set input name
        if (!((inputURL == NULL || !strcmp(inputURL, "")))) {

            CURL *curl;
            CURLcode res;

            /* get the file name from the URL */
            int i = 0;
            for(i = sizeof(inputURL); i>= 0; i--) {
                if(inputURL[i] == '/')
                    break;
            }
            strncpy(inputName, inputURL+i+1, sizeof(inputName));

            curl = curl_easy_init();
            if (!curl) {
                cout << "Can't initialize curl object to download input from: "
                     << inputURL << endl;
                exit(1);
            }

            /* set URL */
            curl_easy_setopt(curl, CURLOPT_URL, inputURL);
            curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);

            /* and write to file */
            FILE *fp;
            fp = fopen(inputName, "w");
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

            /* perform the curl request and clean up */
            res = curl_easy_perform(curl);
            curl_easy_cleanup(curl);
            fclose(fp);

            if (res != 0) {
                cout << "Error while downloading input from: " << inputURL << endl;
                exit(1);
            }
        }
#endif

        if (interpolation_mode == INTERP_MPI)
        {
            if(timer)timer->start = time(NULL);
            MPI_Init (&argc, &argv);
            MPI_Comm_size (MPI_COMM_WORLD, &process_count);
            MPI_Comm_rank (MPI_COMM_WORLD, &rank);
            if (reader_count >= process_count)
            {
                if (rank == 0)
                {
                    printf ("process count = %i is not greater than reader process count = %i.\n",
                            process_count, reader_count);
                    printf ("decrease --parallel(-p) parameter value or add processes.\n");
                }

                MPI_Finalize ();
                return 0;
            }
            MPI_Barrier(MPI_COMM_WORLD);

        }

        if (rank == 0)
        {
            cout << "Parameters ************************" << endl;
            cout << "inputName: '" << inputName << "'" << endl;
            cout << "input_format: " << input_format << endl;
            cout << "outputName: '" << outputName << "'" << endl;
            cout << "GRID_DIST_X: " << GRID_DIST_X << endl;
            cout << "GRID_DIST_Y: " << GRID_DIST_Y << endl;
            cout << "searchRadius: " << searchRadius << endl;
            cout << "output_format: " << output_format << endl;
            cout << "type: " << type << endl;
            cout << "fill window size: " << window_size << endl;
            cout << "parallel interp, reader process count: " << reader_count
                 << endl;
            cout << "parallel interp, writer buffer size: " << buffer_size
                 << endl;
            cout << "************************************" << endl;
        }
        if (interpolation_mode == INTERP_MPI)
        {
            MPI_Barrier (MPI_COMM_WORLD);
        }

    }
    catch (std::exception& e) {
        cerr << "error: " << e.what() << endl;
        cerr << "execute `" << appName << " --help` to see usage information" << endl;
        exit(1);
    }

    t0 = clock();

    if(timer)
    {
        if(rank == reader_count)printf("Allocating memory...\n");
        timer->init_start = time(NULL);
    }
    Interpolation *ip = new Interpolation(GRID_DIST_X, GRID_DIST_Y, searchRadius,
                                          window_size, interpolation_mode, rank, process_count, reader_count, buffer_size, timer);

    if(ip->init(inputName, input_format) < 0)
    {
        fprintf(stderr, "Interpolation::init() error\n");
        return -1;
    }
    if(timer)
    {
        timer->init_end = time(NULL);
    }
    t1 = clock();
    if(rank == 0)
    {
        //printf("Init + Min/Max time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);
    }
    t0 = clock();
    if(ip->interpolation(inputName, outputName, input_format, output_format, type) < 0)
    {
        fprintf(stderr, "Interpolation::interpolation() error\n");
        return -1;
    }

    t1 = clock();
    if (rank == 0 && !timer)
    {
        printf ("DEM generation + Output time: %10.2f\n",
                (double) (t1 - t0) / CLOCKS_PER_SEC);
        printf ("# of data: %d\n", ip->getDataCount ());
        printf ("dimension: %d x %d\n", ip->getGridSizeX (),
                ip->getGridSizeY ());
    }



    if ((interpolation_mode == INTERP_MPI && timer))
    {
        MPI_Barrier (MPI_COMM_WORLD);
        //int first_writer_rank = ip->getInterp ()->getReaderCount ();
        if (timer)
            timer->end = time(NULL);
        /*
         long *interp_start = (long *) malloc(sizeof(long)*process_count);

         MPI_Gather(&(timer->interp_start), 1, MPI_LONG,
         interp_start, 1, MPI_LONG, 0, MPI_COMM_WORLD);
         */
        //int i;
        //if (rank == 0)
        //{
        //for (i = 0; i < process_count; i++)
        //{
        //    printf ("interp_start %li, rank %i\n", interp_start[i], i);
        //}
        //}
        //printf("reader count %i, writer count %i\n",ip->getInterp()->getReaderCount(), ip->getInterp()->getWriterCount());
        //for(i=0; i<process_count; i++){
        //    printf("reader ranks %i writer ranks %i\n",ip->getInterp()->getReaders()[i], ip->getInterp()->getWriters()[i]);
        // }


        if (rank == reader_count)
        {
            printf("Finished, first writer process times...\n");
            printf("Total time %li seconds.\n", timer->end - timer->start);

            printf ("  Allocation: %li seconds.\n",
                    timer->init_end - timer->init_start);
            printf ("  Read and send: %li seconds.\n",
                    timer->interp_end - timer->interp_start);
            printf ("  Process cells: %li seconds.\n",
                    timer->process_end - timer->process_start);
            printf ("  Write cells: %li seconds.\n",
                    timer->output_end -   timer->output_start);

        }


    }

    if (interpolation_mode == INTERP_MPI)
    {
        MPI_Finalize ();
    }
    else
    {
        delete ip;
    }

    return 0;
}
Esempio n. 7
0
void Animation::animate()
{
	std::queue<int> temp_tasks;
	std::queue<action_t> temp_actions;
	std::queue<Interpolation> temp_interps;
	
	//will need threads?!
	while (!_controller.empty())
	{
		int task = _controller.front();

		if (task == ANIM_CTR_ACTION)
		{
			action_t action = _actions.front();
			SceneObject* obj = Scene::instance().objects()[action.obj];

			switch (action.type)
			{
				case ANIM_TRANSLATE:
					obj->set_translate(action.x, action.y, action.z);
					break;
				case ANIM_ROTATE:
					obj->set_rotate(action.x, action.y, action.z);
					break;
				case ANIM_SCALE:
					obj->set_scale(action.x, action.y, action.z);
					break;
			}

			temp_actions.push(action);
			_actions.pop();
		}
		else
		{
			Interpolation interp = _interps.front();

			interp.interpolate();
			
			temp_interps.push(interp);
			_interps.pop();
		}

		temp_tasks.push(task);
		_controller.pop();
	}

	while (!temp_tasks.empty())
	{
		_controller.push(temp_tasks.front());
		temp_tasks.pop();
	}

	while (!temp_actions.empty())
	{
		_actions.push(temp_actions.front());
		temp_actions.pop();
	}

	while (!temp_interps.empty())
	{
		_interps.push(temp_interps.front());
		temp_interps.pop();
	}
}
Esempio n. 8
0
int main ( int argc, char** argv )
{
	//Clase que maneja las operaciones
	Interpolation interpolation;

	//Carga y verifica la imagen original
	interpolation.Load();
	//Ejecuta la transformada discreta de la imagen en la imagen original
	interpolation.DiscreteFourierTrasform();
	//Muestra y salva la imagen que describe la transformada Fourier
	interpolation.PreprocessFourier(); //Operaciones para hacer la operacion visible
	interpolation.ShowFourier();
	interpolation.SaveFourier("fourier.png");
	//Agrega un padding a la transformada
	interpolation.ZeroPad(interpolation.Size());
	//Muestra y salva una vez más
	interpolation.ShowFourier();
	interpolation.SaveFourier("padding.png");
	//Aplica la transformada inversa
	interpolation.InverseDFT();
	//Muestra y salva la nueva imagen
	interpolation.ShowImage();
	interpolation.SaveImage("result.png");

}
Esempio n. 9
0
int main(int argc, char **argv)
{
    clock_t t0, t1;

    // parameters
    char inputName[1024] = {0};
    char inputURL[2048] = {0};
    char outputName[1024] = {0};

    int input_format = INPUT_LAS;
    int interpolation_mode = INTERP_AUTO;
    int output_format = 0;
    unsigned int type = 0x00000000;
    double GRID_DIST_X = 6.0;
    double GRID_DIST_Y = 6.0;
    double searchRadius = (double) sqrt(2.0) * GRID_DIST_X;
    int window_size = 0;

    // argument processing..
    po::options_description general("General options"),
       df("Data file"),
       ot("Output Type"),
       res("Resolution"),
       nf("Null Filling"),
       desc;

    general.add_options()
    ("help", "produce a help message")
    ("output_file_name,o", po::value<std::string>(), "required. name of output file without extension, i.e. if you want the output file to be test.asc, this parameter shoud be \"test\"")
    ("search_radius,r", po::value<float>(), "specifies the search radius. The default value is square root 2 of horizontal distance in a grid cell")
    ("output_format", po::value<std::string>(), "'all' generates every possible format,\n"
     "'arc' for ArcGIS format,\n"
     "'grid' for Ascii GRID format,\n"
     "the default value is --all")
    ("input_format", po::value<std::string>(), "'ascii' expects input point cloud in ASCII format\n"
     "'las' expects input point cloud in LAS format (default)")
    ("interpolation_mode", po::value<std::string>()->default_value("auto"), "'incore' stores working data in memory\n"
     "'outcore' stores working data on the filesystem\n"
     "'auto' (default) guesses based on the size of the data file");


    df.add_options()
#ifdef CURL_FOUND
    ("data_file_name,i", po::value<std::string>(), "path to unzipped plain text data file")
    ("data_file_url,l", po::value<std::string>(), "URL of unzipped plain text data file"
     "You must specify either a data_file_name or data_file_url.");
#else
    ("data_file_name,i", po::value<std::string>(), "required. path to unzipped plain text data file");
#endif

    ot.add_options()
    ("min", "the Zmin values are stored")
    ("max", "the Zmax values are stored")
    ("mean", "the Zmean values are stored")
    ("idw", "the Zidw values are stored")
    ("den", "the density values are stored")
    ("all", "all the values are stored (default)");

    res.add_options()
    ("resolution", po::value<float>(), "The resolution is set to the specified value. Use square grids.\n"
     "If no resolution options are specified, a 6ft square grid is used")
    ("resolution-x", po::value<float>(), "The X side of grid cells is set to the specified value")
    ("resolution-y", po::value<float>(), "The Y side of grid cells is set to the specified value");

    nf.add_options()
    ("fill", "fills nulls in the DEM. Default window size is 3.")
    ("fill_window_size", po::value<int>(), "The fill window is set to value. Permissible values are 3, 5 and 7.");

    desc.add(general).add(df).add(ot).add(res).add(nf);

    po::variables_map vm;

    try {
        po::store(po::parse_command_line(argc, argv, desc), vm);

        if (vm.count("help")) {
            cout << "------------------------------------------------------------------------" << endl;
            cout << "   " << appName << " (development version )" << endl;
            cout << "------------------------------------------------------------------------" << endl;
            cout << "Usage: " << appName << " [options]" << endl;
            cout << desc << endl;
            exit(0);
        }

        po::notify(vm);


        if (vm.count("output_format")) {
            std::string of = vm["output_format"].as<std::string>();
            if(of.compare("all") == 0) {
                output_format = OUTPUT_FORMAT_ALL;
            }
            else if(of.compare("arc") == 0)
                output_format = OUTPUT_FORMAT_ARC_ASCII;
            else if(of.compare("grid") == 0)
                output_format = OUTPUT_FORMAT_GRID_ASCII;
            else {
                throw std::logic_error("'" + of + "' is not a recognized output_format");
            }
        }
        // resolution
        if(vm.count("resolution")) {
            float res = vm["resolution"].as<float>();
            GRID_DIST_X = res;
            GRID_DIST_Y = res;
            if(searchRadius == sqrt(2.0) * 6.0)
                searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

            if(GRID_DIST_X == 0) {
                throw std::logic_error("resolution must not be 0");
            }
        }

        if(vm.count("resolution-x")) {
            GRID_DIST_X = vm["resolution-x"].as<float>();
            if(searchRadius == sqrt(2.0) * 6.0)
                searchRadius = (double) sqrt(2.0) * GRID_DIST_X;

            if(GRID_DIST_X == 0) {
                throw std::logic_error("resolution-x must not be 0");
            }
        }

        if(vm.count("resolution-y")) {
            GRID_DIST_Y = vm["resolution-y"].as<float>();
            if(GRID_DIST_Y == 0) {
                throw std::logic_error("resolution-y must not be 0");
            }
        }

        if(vm.count("min")) {
            type |= OUTPUT_TYPE_MIN;
        }

        if(vm.count("max")) {
            type |= OUTPUT_TYPE_MAX;
        }

        if(vm.count("mean")) {
            type |= OUTPUT_TYPE_MEAN;
        }

        if(vm.count("idw")) {
            type |= OUTPUT_TYPE_IDW;
        }

        if(vm.count("den")) {
            type |= OUTPUT_TYPE_DEN;
        }

        if(vm.count("all")) {
            type = OUTPUT_TYPE_ALL;
        }

        if(vm.count("fill")) {
            window_size = 3;
        }

        if(vm.count("fill_window_size")) {
            window_size = vm["fill_window_size"].as<int>();
            if(!((window_size == 3) || (window_size == 5) || (window_size == 7))) {
                throw std::logic_error("window-size must be either 3, 5, or 7");
            }
        }

        if(vm.count("input_format")) {
            std::string inf = vm["input_format"].as<std::string>();

            if(inf.compare("ascii") == 0)
                input_format = INPUT_ASCII;
            else if(inf.compare("las") == 0)
                input_format = INPUT_LAS;
            else {
                throw std::logic_error("'" + inf + "' is not a recognized input_format");
            }
        }


#ifdef CURL_FOUND
        if(vm.count("data_file_name")) {
            strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
        }
        if(vm.count("data_file_url")) {
            strncpy(inputURL, vm["data_file_url"].as<std::string>().c_str(), sizeof(inputURL));
        }

        if((inputName == NULL || !strcmp(inputName, "")) &&
                (inputURL == NULL || !strcmp(inputURL, "")))
        {
            throw std::logic_error("you must specify a valid data file");
        }
#else
        if(!vm.count("data_file_name")) {
            throw std::logic_error("data_file_name  must be specified");
        }
        else {
            strncpy(inputName, vm["data_file_name"].as<std::string>().c_str(), sizeof(inputName));
            if (!strcmp(inputName, "")) {
                throw std::logic_error("data_file_name must not be an empty string");
            }
        }
#endif

        if (!vm.count("output_file_name")) {
            throw std::logic_error("output_file_name must be specified");
        }
        else {
            strncpy(outputName, vm["output_file_name"].as<std::string>().c_str(), sizeof(outputName));
        }

        if(vm.count("search_radius")) {
            searchRadius = vm["search_radius"].as<float>();
        }

        if(vm.count("interpolation_mode")) {
            std::string im(vm["interpolation_mode"].as<std::string>());
            if (im.compare("auto") == 0) {
                interpolation_mode = INTERP_AUTO;
            }
            else if (im.compare("incore") == 0) {
                interpolation_mode = INTERP_INCORE;
            }
            else if (im.compare("outcore") == 0) {
                interpolation_mode = INTERP_OUTCORE;
            }
            else {
                throw std::logic_error("'" + im + "' is not a recognized interpolation_mode");
            }
        }

        if(type == 0)
            type = OUTPUT_TYPE_ALL;


#ifdef CURL_FOUND
        // download file from URL, and set input name
        if (!((inputURL == NULL || !strcmp(inputURL, "")))) {

            CURL *curl;
            CURLcode res;

            /* get the file name from the URL */
            int i = 0;
            for(i = sizeof(inputURL); i>= 0; i--) {
                if(inputURL[i] == '/')
                    break;
            }
            strncpy(inputName, inputURL+i+1, sizeof(inputName));

            curl = curl_easy_init();
            if (!curl) {
                cout << "Can't initialize curl object to download input from: "
                     << inputURL << endl;
                exit(1);
            }

            /* set URL */
            curl_easy_setopt(curl, CURLOPT_URL, inputURL);
            curl_easy_setopt(curl, CURLOPT_FAILONERROR, 1);

            /* and write to file */
            FILE *fp;
            fp = fopen(inputName, "w");
            curl_easy_setopt(curl, CURLOPT_WRITEDATA, fp);

            /* perform the curl request and clean up */
            res = curl_easy_perform(curl);
            curl_easy_cleanup(curl);
            fclose(fp);

            if (res != 0) {
                cout << "Error while downloading input from: " << inputURL << endl;
                exit(1);
            }
        }
#endif

        cout << "Parameters ************************" << endl;
        cout << "inputName: '" << inputName << "'" << endl;
        cout << "input_format: " << input_format << endl;
        cout << "outputName: '" << outputName << "'" << endl;
        cout << "GRID_DIST_X: " << GRID_DIST_X << endl;
        cout << "GRID_DIST_Y: " << GRID_DIST_Y << endl;
        cout << "searchRadius: " << searchRadius << endl;
        cout << "output_format: " << output_format << endl;
        cout << "type: " << type << endl;
        cout << "fill window size: " << window_size << endl;
        cout << "************************************" << endl;
    }
    catch (std::exception& e) {
        cerr << "error: " << e.what() << endl;
        cerr << "execute `" << appName << " --help` to see usage information" << endl;
        exit(1);
    }

    t0 = clock();

    Interpolation *ip = new Interpolation(GRID_DIST_X, GRID_DIST_Y, searchRadius,
                                          window_size, interpolation_mode);

    if(ip->init(inputName, input_format) < 0)
    {
        fprintf(stderr, "Interpolation::init() error\n");
        return -1;
    }

    t1 = clock();
    printf("Init + Min/Max time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

    t0 = clock();
    if(ip->interpolation(inputName, outputName, input_format, output_format, type) < 0)
    {
        fprintf(stderr, "Interpolation::interpolation() error\n");
        return -1;
    }

    t1 = clock();
    printf("DEM generation + Output time: %10.2f\n", (double)(t1 - t0)/CLOCKS_PER_SEC);

    printf("# of data: %d\n", ip->getDataCount());
    printf("dimension: %d x %d\n", ip->getGridSizeX(), ip->getGridSizeY());

    delete ip;

    return 0;
}
Esempio n. 10
0
// the program starts here
void AppMain() {
    // initialise GLFW
    glfwSetErrorCallback(OnError);
    if(!glfwInit())
        throw std::runtime_error("glfwInit failed");

    // open a window with GLFW
    glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
    glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 3);

	glfwWindowHint(GLFW_RESIZABLE, GL_FALSE);
	gWindow = glfwCreateWindow((int)SCREEN_SIZE.x, (int)SCREEN_SIZE.y, "Mek", NULL /*glfwGetPrimaryMonitor()*/, NULL);
	if (!gWindow)
		throw std::runtime_error("glfwCreateWindow failed. Can your hardware handle OpenGL 3.3?");

    // GLFW settings
    glfwSetInputMode(gWindow, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
    glfwSetCursorPos(gWindow, 0, 0);
    glfwSetScrollCallback(gWindow, OnScroll);
    glfwMakeContextCurrent(gWindow);

	// required or we crash on VAO creation
	glewExperimental = GL_TRUE;
    // initialise GLEW
	if (glewInit() != GLEW_OK)
	{
        throw std::runtime_error("glewInit failed");
	}

    // GLEW throws some errors so discard all the errors so far
    while(glGetError() != GL_NO_ERROR) {}

	// Init DevIL
	ilInit();

	// enable vsync using windows only code
#ifdef _WIN32
	// Turn on vertical screen sync under Windows.
	typedef BOOL(WINAPI *PFNWGLSWAPINTERVALEXTPROC)(int interval);
	PFNWGLSWAPINTERVALEXTPROC wglSwapIntervalEXT = NULL;
	wglSwapIntervalEXT = (PFNWGLSWAPINTERVALEXTPROC)wglGetProcAddress("wglSwapIntervalEXT");
	if (wglSwapIntervalEXT)
		wglSwapIntervalEXT(1);
#endif

    // print out some info about the graphics drivers
    std::cout << "OpenGL version: " << glGetString(GL_VERSION) << std::endl;
    std::cout << "GLSL version: " << glGetString(GL_SHADING_LANGUAGE_VERSION) << std::endl;
    std::cout << "Vendor: " << glGetString(GL_VENDOR) << std::endl;
    std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;

    // make sure OpenGL version 3.2 API is available
    if(!GLEW_VERSION_3_3)
        throw std::runtime_error("OpenGL 3.3 API is not available.");

    // OpenGL settings
    glEnable(GL_DEPTH_TEST);
    glDepthFunc(GL_LESS);
    glEnable(GL_BLEND);
    glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);

    // initialise the gWoodenCrate asset
    LoadWoodenCrateAsset();

    // create all the instances in the 3D scene based on the gWoodenCrate asset
    CreateInstances();

    // setup Camera::getInstance()
    Camera::getInstance().setPosition(glm::vec3(1100, 75, 0));
    Camera::getInstance().setViewportAspectRatio(SCREEN_SIZE.x / SCREEN_SIZE.y);
	Camera::getInstance().setNearAndFarPlanes(1.f, 500.0f);
	Camera::getInstance().setFieldOfView(179);

	crosshair = new twodOverlay("crosshair.png", 0, 0, 1);
	skull = new twodOverlayAnim("killSkull.png", 5, 0.5);
	startscreen = new twodOverlay("pressStart.png", 0, 0, 10);
	skull->updatePos(-0.85f, -0.75f, 4);
	skull ->cycle = true;
	//MODEL INITS

	prepProjectiles();

	model = new GameObject(0);
	model->SetName("Moving");
	gModel = new ComponentGraphics();
	gModel->setOwner(model);
	gModel->loadModel("models/TallCube.dae");
	Component* gp = gModel;
	model->AddComponent(GRAPHICS, gp);
	gCol = new ComponentCollision();
	gCol->setCollisionMask(gModel->getScene());
	gCol->setOwner(model);
	model->pos = glm::vec3(7.5, 0.5, -11);
	model->vel = 0.01;
	model->dir = glm::vec3(1, 0, 0);
	model->scale = glm::vec3(5, 5, 5);
	gCol->type = MOVING;
	gCol->createHitboxRender();
	gp = gCol;
	model->AddComponent(PHYSICS, gp);
	ComponentInput* ci = new ComponentInput(0.05,0.05);
	gp = ci;
	model->AddComponent(CONTROLLER, gp);
	
	//PROPER INIT
	for (int i = 0; i < 22; i++)
	{
		if (i != 3 && i != 0 && i != 4 && i != 8 && i != 18 && i != 19 && i != 20 && i !=21)
		{
			GameObject *gObject = new GameObject(goVec.size());
			ComponentGraphics *cModel = new ComponentGraphics();
			ComponentCollision *cCollision = new ComponentCollision();
			Component *c;

			if (i == 0)
			{
				gObject->SetName("Spawn Container 1");
				cModel->loadModel("models/Container.dae");

				gObject->scale = glm::vec3(0.7, 0.7, 0.7);
				gObject->pos = glm::vec3(60, 0, -110);
			}
			else if (i == 1)
			{
				gObject->SetName("Water Tower");
				cModel->loadModel("models/Watertower.dae");

				gObject->scale = glm::vec3(3, 3, 3);
				gObject->pos = glm::vec3(-65, 0, -90);
			}
			else if (i == 2)
			{
				gObject->SetName("MenuScene");
				cModel->loadModel("models/Warehouse_One_mesh_No_roof.dae");

				gObject->scale = glm::vec3(1, 1, 1);// glm::vec3(1.6, 1.6, 1.6);
				gObject->pos = glm::vec3(10000, 0, 0);
			}
			else if (i == 3)
			{
				gObject->SetName("Spawn Container 2");
				cModel->loadModel("models/Container90.dae");

				gObject->scale = glm::vec3(0.7, 0.7, 0.7);
				gObject->pos = glm::vec3(85, 0, -75);
			}
			else if (i == 4)
			{
				gObject->SetName("Middle Plus");
				cModel->loadModel("models/Container.dae");

				gObject->scale = glm::vec3(0.7, 0.7, 0.7);
				gObject->pos = glm::vec3(15, 0, -20);
			}
			else if (i == 5)
			{
				gObject->SetName("North Wall");
				cModel->loadModel("models/Container_Wal_LPl.dae");

				gObject->scale = glm::vec3(0.7, 0.70, 0.70);
				gObject->pos = glm::vec3(100, 0, 165);
			}
			else if (i == 6)
			{
				gObject->SetName("Dumbster");//Crane
				cModel->loadModel("models/Dumspter2.dae");
				gObject->pos = glm::vec3(0, 0, -140);
				gObject->scale = glm::vec3(0.4, 0.4, 0.4);
			}
			else if (i == 7)
			{
				gObject->SetName("Shack");
				cModel->loadModel("models/Shack.dae");

				gObject->scale = glm::vec3(0.75, 0.75, 0.75);
				gObject->pos = glm::vec3(0, 0, 120);
			}
			else if (i == 8)
			{
				gObject->SetName("Middle Plus");
				cModel->loadModel("models/Container.dae");

				gObject->scale = glm::vec3(0.7, 0.7, 0.7);
				gObject->pos = glm::vec3(-5, 0, -20);
			}
			else if (i == 9)
			{
				gObject->SetName("Container 2");
				cModel->loadModel("models/Container.dae");

				gObject->scale = glm::vec3(0.70, 0.70, 0.70);
				gObject->pos = glm::vec3(80, 0, 100);
			}
			else if (i == 10)
			{
				gObject->SetName("South Wall");
				cModel->loadModel("models/Container_Wal_LPl.dae");

				gObject->scale = glm::vec3(0.7, 0.70, 0.70);
				gObject->pos = glm::vec3(-100, 0, 165);
			}
			else if (i == 11)
			{
				gObject->SetName("East Wall");
				cModel->loadModel("models/Container_Wal_LP90.dae");

				gObject->scale = glm::vec3(0.7, 0.70, 0.70);
				gObject->pos = glm::vec3(50, 0, 145);
			}
			else if (i == 12)
			{
				gObject->SetName("West Wall");
				cModel->loadModel("models/Container_Wal_LP90.dae");

				gObject->scale = glm::vec3(0.7, 0.70, 0.70);
				gObject->pos = glm::vec3(50, 0, -125);
			}
			else if (i == 13)
			{
				gObject->SetName("Container 2");
				cModel->loadModel("models/Container.dae");

				gObject->scale = glm::vec3(0.70, 0.70, 0.70);
				gObject->pos = glm::vec3(60, 0, 100);
			}
			else if (i == 14)
			{
				gObject->SetName("Container 90");
				cModel->loadModel("models/Container90.dae");

				gObject->scale = glm::vec3(0.70, 0.70, 0.70);
				gObject->pos = glm::vec3(70, 0, 70);
			}
			else if (i == 15)
			{
				gObject->SetName("Shack");
				cModel->loadModel("models/Shack.dae");

				gObject->scale = glm::vec3(0.75, 0.75, 0.75);
				gObject->pos = glm::vec3(-30, 0, 120);
			}
			else if (i == 16)
			{
				gObject->SetName("Shack");
				cModel->loadModel("models/Shack.dae");

				gObject->scale = glm::vec3(0.75, 0.75, 0.75);
				gObject->pos = glm::vec3(30, 0, 120);
			}
			else if (i == 17)
			{
				gObject->SetName("Shack");
				cModel->loadModel("models/Shack.dae");

				gObject->scale = glm::vec3(0.75, 0.75, 0.75);
				gObject->pos = glm::vec3(-60, 0, 120);
			}
			else if (i == 18)
			{
				gObject->SetName("Middle Plus North");
				cModel->loadModel("models/Container90.dae");

				gObject->scale = glm::vec3(0.7, 0.7, 0.7);
				gObject->pos = glm::vec3(27, 0, -5);
			}
			else if (i == 19)
			{
				gObject->SetName("Middle Plus North");
				cModel->loadModel("models/Container90.dae");

				gObject->scale = glm::vec3(0.7, 0.7, 0.7);
				gObject->pos = glm::vec3(27, 0, 15);
			}
			else if (i == 20)
			{
				gObject->SetName("Middle Plus North");
				cModel->loadModel("models/Container90.dae");

				gObject->scale = glm::vec3(0.7, 0.7, 0.7);
				gObject->pos = glm::vec3(-20, 0, 15);
			}
			else if (i == 21)
			{
				gObject->SetName("Middle Plus North");
				cModel->loadModel("models/Container90.dae");

				gObject->scale = glm::vec3(0.7, 0.7, 0.7);
				gObject->pos = glm::vec3(-20, 0, -5);
			}

			gObject->pos /= 10.f;

			cModel->setOwner(gObject);
			c = cModel;
			gObject->AddComponent(GRAPHICS, c);
			cCollision->setOwner(gObject);
			cCollision->setCollisionMask(cModel->getScene());
			cCollision->type = STATIC;
			cCollision->setCollisionElip(glm::vec3(1, 1, 1));
			cCollision->createHitboxRender();
			gObject->AddComponent(PHYSICS, cCollision);
			goVec.push_back(gObject);
		}
	}

	LoadTargets();
	

	spotLightColour = glm::normalize(spotLightColour);
	for (int i = 0; i < 6; i++)
	{
		LightComponent* light;
		if (i == 0)
		{
			light = new LightComponent(lSPOT);
			SpotLight* lc = new SpotLight;
			lc->Base.Base.Color = spotLightColour;
			lc->Base.Base.AmbientIntensity = 0.1f;
			lc->Base.Base.DiffuseIntensity = 0.1f;
			
			lc->Base.Atten.Constant = 0.1f;
			lc->Base.Atten.Exp = 0.1f;
			lc->Base.Atten.Linear = 0.1f;
			
			lc->Cutoff = 0.75f;
			lc->Base.Position = glm::vec3(-6, 1, 11);
			lc->Direction = glm::vec3(0, 0, -1);
			
			light->SetVars(lSPOT, lc);
		}
		if (i == 1)
		{
			light = new LightComponent(lSPOT);
			SpotLight* lc = new SpotLight;
			lc->Base.Base.Color = spotLightColour;
			lc->Base.Base.AmbientIntensity = 0.5f;
			lc->Base.Base.DiffuseIntensity = 0.5f;
			
			lc->Base.Atten.Constant = 0.5f;
			lc->Base.Atten.Exp = 0.5f;
			lc->Base.Atten.Linear = 0.5f;
			
			lc->Cutoff = 0.75f;
			lc->Base.Position = glm::vec3(3, 1, 11);
			lc->Direction = (glm::vec3(0, 0, 10));
			
			light->SetVars(lSPOT, lc);
		}
		if (i == 2)
		{
			//light = new LightComponent(lSPOT);
			//SpotLight* lc = new SpotLight;
			//lc->Base.Base.Color = glm::vec3(0,0.1,0);
			//lc->Base.Base.AmbientIntensity = 0.5f;
			//lc->Base.Base.DiffuseIntensity = 0.5f;
			//
			//lc->Base.Atten.Constant = 0.5f;
			//lc->Base.Atten.Exp = 0.5f;
			//lc->Base.Atten.Linear = 0.5f;
			//
			//lc->Cutoff = 0.75f;
			//lc->Base.Position = glm::vec3(-3, 1, 11);
			//lc->Direction = (glm::vec3(-3, 0, 12));
			//
			//light->SetVars(lSPOT, lc);
		}
		if (i == 3)
		{
			//light = new LightComponent(lSPOT);
			//SpotLight* lc = new SpotLight;
			//lc->Base.Base.Color = spotLightColour;
			//lc->Base.Base.AmbientIntensity = 0.5f;
			//lc->Base.Base.DiffuseIntensity = 0.5f;
			//
			//lc->Base.Atten.Constant = 0.5f;
			//lc->Base.Atten.Exp = 0.5f;
			//lc->Base.Atten.Linear = 0.5f;
			//
			//lc->Cutoff = 0.75f;
			//lc->Base.Position = glm::vec3(-6, 1, 11);
			//lc->Direction = (glm::vec3(-6, 1, 12));
			//
			//light->SetVars(lSPOT, lc);
		}
		if (i == 4)
		{
			//light = new LightComponent(lSPOT);
			//SpotLight* lc = new SpotLight;
			//lc->Base.Base.Color = spotLightColour;
			//lc->Base.Base.AmbientIntensity = 0.1f;
			//lc->Base.Base.DiffuseIntensity = 0.1f;
			//
			//lc->Base.Atten.Constant = 0.1f;
			//lc->Base.Atten.Exp = 0.1f;
			//lc->Base.Atten.Linear = 0.1f;
			//
			//lc->Cutoff = 0.75f;
			//lc->Base.Position = glm::vec3(0, 1, 0);
			//lc->Direction = glm::vec3(0, -1, 0);
			//
			//light->SetVars(lSPOT, lc);
		}
		if (i == 5)
		{
			light = new LightComponent(lSPOT);
			SpotLight* lc = new SpotLight;
			lc->Base.Base.Color = spotLightColour;
			lc->Base.Base.AmbientIntensity = 0.5f;
			lc->Base.Base.DiffuseIntensity = 0.5f;

			lc->Base.Atten.Constant = 0.5f;
			lc->Base.Atten.Exp = 0.5f;
			lc->Base.Atten.Linear = 0.5f;

			lc->Cutoff = 0.5f;
			lc->Base.Position = glm::vec3(1000, 1, 0);//4 1 0
			lc->Direction = glm::vec3(0, -1, 0);// 5 0 0

			light->SetVars(lSPOT, lc);
		}
	}

	animatedMech = new GameObject(100);
	animatedMechGC = new ComponentGraphics();
	animatedMechGC->loadModel("models/Test_Animation_DAE.dae");
	Component* c = animatedMechGC;
	animatedMech->AddComponent(GRAPHICS, c);
	animatedMech->pos = glm::vec3(0, 0, 0);
	animatedMech->scale = glm::vec3(1, 1, 1);

	//END MODEL INITS
	camInterp.points.push_back(glm::vec3(1025, 1, 0));
	camInterp.points.push_back(glm::vec3(1000, 1, 25));
	camInterp.points.push_back(glm::vec3(975, 1, 0));
	camInterp.points.push_back(glm::vec3(1000, 1, -25));
	camInterp.points.push_back(glm::vec3(1025, 1, 0));
	camInterp.state = SLERP;
	camInterp.buildCurve();

	TextRendering::getInstance().initText2D("MekFont.bmp");
	fontColour = glm::normalize(fontColour);

	wglSwapIntervalEXT(1);


    // run while the window is open
    double lastTime = glfwGetTime();
    while(!glfwWindowShouldClose(gWindow)){
        // process pending events
        glfwPollEvents();

        // update the scene based on the time elapsed since last update
        double thisTime = glfwGetTime();
        Update((float)(thisTime - lastTime));
        lastTime = thisTime;

        // draw one frame
        Render();

        // check for errors
        GLenum error = glGetError();
		if (error != GL_NO_ERROR)
		{
			std::cerr << "OpenGL Error " << error << " - " << glewGetErrorString(error) << std::endl;
		}

        //exit program if escape key is pressed
        if(glfwGetKey(gWindow, GLFW_KEY_ESCAPE))
            glfwSetWindowShouldClose(gWindow, GL_TRUE);
    }

    // clean up and exit
    glfwTerminate();
}