<commit_before>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct SynthXilinxPass : public ScriptPass
{
	SynthXilinxPass() : ScriptPass("synth_xilinx", "synthesis for Xilinx FPGAs") { }

	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    synth_xilinx [options]\n");
		log("\n");
		log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n");
		log("partly selected designs. At the moment this command creates netlists that are\n");
		log("compatible with 7-Series Xilinx devices.\n");
		log("\n");
		log("    -top <module>\n");
		log("        use the specified module as top module\n");
		log("\n");
		log("    -arch {xcup|xcu|xc7|xc6s}\n");
		log("        run synthesis for the specified Xilinx architecture\n");
		log("        default: xc7\n");
		log("\n");
		log("    -edif <file>\n");
		log("        write the design to the specified edif file. writing of an output file\n");
		log("        is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -blif <file>\n");
		log("        write the design to the specified BLIF file. writing of an output file\n");
		log("        is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -vpr\n");
		log("        generate an output netlist (and BLIF file) suitable for VPR\n");
		log("        (this feature is experimental and incomplete)\n");
		log("\n");
		log("    -nocarry\n");
		log("        disable inference of carry chains\n");
		log("\n");
		log("    -nobram\n");
		log("        disable inference of block rams\n");
		log("\n");
		log("    -nodram\n");
		log("        disable inference of distributed rams\n");
		log("\n");
		log("    -nosrl\n");
		log("        disable inference of shift registers\n");
		log("\n");
		log("    -nomux\n");
		log("        disable inference of wide multiplexers\n");
		log("\n");
		log("    -run <from_label>:<to_label>\n");
		log("        only run the commands between the labels (see below). an empty\n");
		log("        from label is synonymous to 'begin', and empty to label is\n");
		log("        synonymous to the end of the command list.\n");
		log("\n");
		log("    -flatten\n");
		log("        flatten design before synthesis\n");
		log("\n");
		log("    -retime\n");
		log("        run 'abc' with -dff option\n");
		log("\n");
		log("    -abc9\n");
		log("        use abc9 instead of abc\n");
		log("\n");
		log("\n");
		log("The following commands are executed by this synthesis command:\n");
		help_script();
		log("\n");
	}

	std::string top_opt, edif_file, blif_file, abc, arch;
	bool flatten, retime, vpr, nocarry, nobram, nodram, nosrl, nomux;

	void clear_flags() YS_OVERRIDE
	{
		top_opt = "-auto-top";
		edif_file.clear();
		blif_file.clear();
		abc = "abc";
		flatten = false;
		retime = false;
		vpr = false;
		nocarry = false;
		nobram = false;
		nodram = false;
		nosrl = false;
		nomux = false;
		arch = "xc7";
	}

	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		std::string run_from, run_to;
		clear_flags();

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-top" && argidx+1 < args.size()) {
				top_opt = "-top " + args[++argidx];
				continue;
			}
			if (args[argidx] == "-arch" && argidx+1 < args.size()) {
				arch = args[++argidx];
				continue;
			}
			if (args[argidx] == "-edif" && argidx+1 < args.size()) {
				edif_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-blif" && argidx+1 < args.size()) {
				blif_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-run" && argidx+1 < args.size()) {
				size_t pos = args[argidx+1].find(':');
				if (pos == std::string::npos)
					break;
				run_from = args[++argidx].substr(0, pos);
				run_to = args[argidx].substr(pos+1);
				continue;
			}
			if (args[argidx] == "-flatten") {
				flatten = true;
				continue;
			}
			if (args[argidx] == "-retime") {
				retime = true;
				continue;
			}
			if (args[argidx] == "-vpr") {
				vpr = true;
				continue;
			}
			if (args[argidx] == "-nocarry") {
				nocarry = true;
				continue;
			}
			if (args[argidx] == "-nobram") {
				nobram = true;
				continue;
			}
			if (args[argidx] == "-nodram") {
				nodram = true;
				continue;
			}
			if (args[argidx] == "-nosrl") {
				nosrl = true;
				continue;
			}
			if (args[argidx] == "-nomux") {
				nomux = true;
				continue;
			}
			if (args[argidx] == "-abc9") {
				abc = "abc9";
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		if (arch != "xcup" && arch != "xcu" && arch != "xc7" && arch != "xc6s")
			log_cmd_error("Invalid Xilinx -arch setting: %s\n", arch.c_str());

		if (!design->full_selection())
			log_cmd_error("This command only operates on fully selected designs!\n");

		log_header(design, "Executing SYNTH_XILINX pass.\n");
		log_push();

		run_script(design, run_from, run_to);

		log_pop();
	}

	void script() YS_OVERRIDE
	{
		if (check_label("begin")) {
			if (vpr)
				run("read_verilog -lib -D_ABC -D_EXPLICIT_CARRY +/xilinx/cells_sim.v");
			else
				run("read_verilog -lib -D_ABC +/xilinx/cells_sim.v");

			run("read_verilog -lib +/xilinx/cells_xtra.v");

			if (!nobram || help_mode)
				run("read_verilog -lib +/xilinx/brams_bb.v", "(skip if '-nobram')");

			run(stringf("hierarchy -check %s", top_opt.c_str()));
		}

		if (check_label("flatten", "(with '-flatten' only)")) {
			if (flatten || help_mode) {
				run("proc");
				run("flatten");
			}
		}

		if (check_label("coarse")) {
			run("synth -run coarse");

			// shregmap -tech xilinx can cope with $shiftx and $mux
			//   cells for identifying variable-length shift registers,
			//   so attempt to convert $pmux-es to the former
			// Also: wide multiplexer inference benefits from this too
			if (!(nosrl && nomux) || help_mode)
				run("pmux2shiftx", "(skip if '-nosrl' and '-nomux')");

			// Run a number of peephole optimisations, including one
			//   that optimises $mul cells driving $shiftx's B input
			//   and that aids wide mux analysis
			run("peepopt");
		}

		if (check_label("bram", "(skip if '-nobram')")) {
			if (!nobram || help_mode) {
				run("memory_bram -rules +/xilinx/brams.txt");
				run("techmap -map +/xilinx/brams_map.v");
			}
		}

		if (check_label("dram", "(skip if '-nodram')")) {
			if (!nodram || help_mode) {
				run("memory_bram -rules +/xilinx/drams.txt");
				run("techmap -map +/xilinx/drams_map.v");
			}
		}

		if (check_label("fine")) {
			run("opt -fast -full");
			run("memory_map");
			run("dffsr2dff");
			run("dff2dffe");
			run("opt -full");

			if (!nosrl || help_mode) {
				// shregmap operates on bit-level flops, not word-level,
				//   so break those down here
				run("simplemap t:$dff t:$dffe", "(skip if '-nosrl')");
				// shregmap with '-tech xilinx' infers variable length shift regs
				run("shregmap -tech xilinx -minlen 3", "(skip if '-nosrl')");
			}

			if (vpr && !nocarry && !help_mode)
				run("techmap -map +/techmap.v -map +/xilinx/arith_map.v -D _EXPLICIT_CARRY");
			else if (abc == "abc9" && !nocarry && !help_mode)
				run("techmap -map +/techmap.v -map +/xilinx/arith_map.v -D _CLB_CARRY");
			else if (!nocarry || help_mode)
				run("techmap -map +/techmap.v -map +/xilinx/arith_map.v", "(skip if '-nocarry')");
			else
				run("techmap -map +/techmap.v");

			run("opt -fast");
		}

		if (check_label("map_cells")) {
			run("techmap -map +/techmap.v -map +/xilinx/cells_map.v -map +/xilinx/ff_map.v ");
			run("dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT "
					"-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT");
			run("clean");
		}

		if (check_label("map_luts")) {
			if (abc == "abc9")
				run(abc + " -lut +/xilinx/abc.lut -box +/xilinx/abc.box" + string(retime ? " -dff" : ""));
			else if (help_mode)
				run(abc + " -luts 2:2,3,6:5,10,20 [-dff]");
			else
				run(abc + " -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : ""));
			run("clean");

			// This shregmap call infers fixed length shift registers after abc
			//   has performed any necessary retiming
			if (!nosrl || help_mode)
				run("shregmap -minlen 3 -init -params -enpol any_or_none", "(skip if '-nosrl')");
			run("techmap -map +/xilinx/lut_map.v -map +/xilinx/cells_map.v");
			run("clean");
		}

		if (check_label("check")) {
			run("hierarchy -check");
			run("stat -tech xilinx");
			run("check -noinit");
		}

		if (check_label("edif")) {
			if (!edif_file.empty() || help_mode)
				run(stringf("write_edif -pvector bra %s", edif_file.c_str()));
		}

		if (check_label("blif")) {
			if (!blif_file.empty() || help_mode)
				run(stringf("write_blif %s", edif_file.c_str()));
		}
	}
} SynthXilinxPass;

PRIVATE_NAMESPACE_END
<commit_msg>Move ff_map back after ABC for shregmap<commit_after>/*
 *  yosys -- Yosys Open SYnthesis Suite
 *
 *  Copyright (C) 2012  Clifford Wolf <clifford@clifford.at>
 *
 *  Permission to use, copy, modify, and/or distribute this software for any
 *  purpose with or without fee is hereby granted, provided that the above
 *  copyright notice and this permission notice appear in all copies.
 *
 *  THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 *  WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 *  MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 *  ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 *  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 *  ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 *  OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 *
 */

#include "kernel/register.h"
#include "kernel/celltypes.h"
#include "kernel/rtlil.h"
#include "kernel/log.h"

USING_YOSYS_NAMESPACE
PRIVATE_NAMESPACE_BEGIN

struct SynthXilinxPass : public ScriptPass
{
	SynthXilinxPass() : ScriptPass("synth_xilinx", "synthesis for Xilinx FPGAs") { }

	void help() YS_OVERRIDE
	{
		//   |---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|---v---|
		log("\n");
		log("    synth_xilinx [options]\n");
		log("\n");
		log("This command runs synthesis for Xilinx FPGAs. This command does not operate on\n");
		log("partly selected designs. At the moment this command creates netlists that are\n");
		log("compatible with 7-Series Xilinx devices.\n");
		log("\n");
		log("    -top <module>\n");
		log("        use the specified module as top module\n");
		log("\n");
		log("    -arch {xcup|xcu|xc7|xc6s}\n");
		log("        run synthesis for the specified Xilinx architecture\n");
		log("        default: xc7\n");
		log("\n");
		log("    -edif <file>\n");
		log("        write the design to the specified edif file. writing of an output file\n");
		log("        is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -blif <file>\n");
		log("        write the design to the specified BLIF file. writing of an output file\n");
		log("        is omitted if this parameter is not specified.\n");
		log("\n");
		log("    -vpr\n");
		log("        generate an output netlist (and BLIF file) suitable for VPR\n");
		log("        (this feature is experimental and incomplete)\n");
		log("\n");
		log("    -nocarry\n");
		log("        disable inference of carry chains\n");
		log("\n");
		log("    -nobram\n");
		log("        disable inference of block rams\n");
		log("\n");
		log("    -nodram\n");
		log("        disable inference of distributed rams\n");
		log("\n");
		log("    -nosrl\n");
		log("        disable inference of shift registers\n");
		log("\n");
		log("    -nomux\n");
		log("        disable inference of wide multiplexers\n");
		log("\n");
		log("    -run <from_label>:<to_label>\n");
		log("        only run the commands between the labels (see below). an empty\n");
		log("        from label is synonymous to 'begin', and empty to label is\n");
		log("        synonymous to the end of the command list.\n");
		log("\n");
		log("    -flatten\n");
		log("        flatten design before synthesis\n");
		log("\n");
		log("    -retime\n");
		log("        run 'abc' with -dff option\n");
		log("\n");
		log("    -abc9\n");
		log("        use abc9 instead of abc\n");
		log("\n");
		log("\n");
		log("The following commands are executed by this synthesis command:\n");
		help_script();
		log("\n");
	}

	std::string top_opt, edif_file, blif_file, abc, arch;
	bool flatten, retime, vpr, nocarry, nobram, nodram, nosrl, nomux;

	void clear_flags() YS_OVERRIDE
	{
		top_opt = "-auto-top";
		edif_file.clear();
		blif_file.clear();
		abc = "abc";
		flatten = false;
		retime = false;
		vpr = false;
		nocarry = false;
		nobram = false;
		nodram = false;
		nosrl = false;
		nomux = false;
		arch = "xc7";
	}

	void execute(std::vector<std::string> args, RTLIL::Design *design) YS_OVERRIDE
	{
		std::string run_from, run_to;
		clear_flags();

		size_t argidx;
		for (argidx = 1; argidx < args.size(); argidx++)
		{
			if (args[argidx] == "-top" && argidx+1 < args.size()) {
				top_opt = "-top " + args[++argidx];
				continue;
			}
			if (args[argidx] == "-arch" && argidx+1 < args.size()) {
				arch = args[++argidx];
				continue;
			}
			if (args[argidx] == "-edif" && argidx+1 < args.size()) {
				edif_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-blif" && argidx+1 < args.size()) {
				blif_file = args[++argidx];
				continue;
			}
			if (args[argidx] == "-run" && argidx+1 < args.size()) {
				size_t pos = args[argidx+1].find(':');
				if (pos == std::string::npos)
					break;
				run_from = args[++argidx].substr(0, pos);
				run_to = args[argidx].substr(pos+1);
				continue;
			}
			if (args[argidx] == "-flatten") {
				flatten = true;
				continue;
			}
			if (args[argidx] == "-retime") {
				retime = true;
				continue;
			}
			if (args[argidx] == "-vpr") {
				vpr = true;
				continue;
			}
			if (args[argidx] == "-nocarry") {
				nocarry = true;
				continue;
			}
			if (args[argidx] == "-nobram") {
				nobram = true;
				continue;
			}
			if (args[argidx] == "-nodram") {
				nodram = true;
				continue;
			}
			if (args[argidx] == "-nosrl") {
				nosrl = true;
				continue;
			}
			if (args[argidx] == "-nomux") {
				nomux = true;
				continue;
			}
			if (args[argidx] == "-abc9") {
				abc = "abc9";
				continue;
			}
			break;
		}
		extra_args(args, argidx, design);

		if (arch != "xcup" && arch != "xcu" && arch != "xc7" && arch != "xc6s")
			log_cmd_error("Invalid Xilinx -arch setting: %s\n", arch.c_str());

		if (!design->full_selection())
			log_cmd_error("This command only operates on fully selected designs!\n");

		log_header(design, "Executing SYNTH_XILINX pass.\n");
		log_push();

		run_script(design, run_from, run_to);

		log_pop();
	}

	void script() YS_OVERRIDE
	{
		if (check_label("begin")) {
			if (vpr)
				run("read_verilog -lib -D_ABC -D_EXPLICIT_CARRY +/xilinx/cells_sim.v");
			else
				run("read_verilog -lib -D_ABC +/xilinx/cells_sim.v");

			run("read_verilog -lib +/xilinx/cells_xtra.v");

			if (!nobram || help_mode)
				run("read_verilog -lib +/xilinx/brams_bb.v", "(skip if '-nobram')");

			run(stringf("hierarchy -check %s", top_opt.c_str()));
		}

		if (check_label("flatten", "(with '-flatten' only)")) {
			if (flatten || help_mode) {
				run("proc");
				run("flatten");
			}
		}

		if (check_label("coarse")) {
			run("synth -run coarse");

			// shregmap -tech xilinx can cope with $shiftx and $mux
			//   cells for identifying variable-length shift registers,
			//   so attempt to convert $pmux-es to the former
			// Also: wide multiplexer inference benefits from this too
			if (!(nosrl && nomux) || help_mode)
				run("pmux2shiftx", "(skip if '-nosrl' and '-nomux')");

			// Run a number of peephole optimisations, including one
			//   that optimises $mul cells driving $shiftx's B input
			//   and that aids wide mux analysis
			run("peepopt");
		}

		if (check_label("bram", "(skip if '-nobram')")) {
			if (!nobram || help_mode) {
				run("memory_bram -rules +/xilinx/brams.txt");
				run("techmap -map +/xilinx/brams_map.v");
			}
		}

		if (check_label("dram", "(skip if '-nodram')")) {
			if (!nodram || help_mode) {
				run("memory_bram -rules +/xilinx/drams.txt");
				run("techmap -map +/xilinx/drams_map.v");
			}
		}

		if (check_label("fine")) {
			run("opt -fast -full");
			run("memory_map");
			run("dffsr2dff");
			run("dff2dffe");
			run("opt -full");

			if (!nosrl || help_mode) {
				// shregmap operates on bit-level flops, not word-level,
				//   so break those down here
				run("simplemap t:$dff t:$dffe", "(skip if '-nosrl')");
				// shregmap with '-tech xilinx' infers variable length shift regs
				run("shregmap -tech xilinx -minlen 3", "(skip if '-nosrl')");
			}

			if (vpr && !nocarry && !help_mode)
				run("techmap -map +/techmap.v -map +/xilinx/arith_map.v -D _EXPLICIT_CARRY");
			else if (abc == "abc9" && !nocarry && !help_mode)
				run("techmap -map +/techmap.v -map +/xilinx/arith_map.v -D _CLB_CARRY");
			else if (!nocarry || help_mode)
				run("techmap -map +/techmap.v -map +/xilinx/arith_map.v", "(skip if '-nocarry')");
			else
				run("techmap -map +/techmap.v");

			run("opt -fast");
		}

		if (check_label("map_cells")) {
			run("techmap -map +/techmap.v -map +/xilinx/cells_map.v");
			run("clean");
		}

		if (check_label("map_luts")) {
			if (abc == "abc9")
				run(abc + " -lut +/xilinx/abc.lut -box +/xilinx/abc.box" + string(retime ? " -dff" : ""));
			else if (help_mode)
				run(abc + " -luts 2:2,3,6:5,10,20 [-dff]");
			else
				run(abc + " -luts 2:2,3,6:5,10,20" + string(retime ? " -dff" : ""));
			run("clean");

			// This shregmap call infers fixed length shift registers after abc
			//   has performed any necessary retiming
			if (!nosrl || help_mode)
				run("shregmap -minlen 3 -init -params -enpol any_or_none", "(skip if '-nosrl')");
			run("techmap -map +/xilinx/lut_map.v -map +/xilinx/cells_map.v -map +/xilinx/ff_map.v");
			run("dffinit -ff FDRE Q INIT -ff FDCE Q INIT -ff FDPE Q INIT -ff FDSE Q INIT "
					"-ff FDRE_1 Q INIT -ff FDCE_1 Q INIT -ff FDPE_1 Q INIT -ff FDSE_1 Q INIT");
			run("clean");
		}

		if (check_label("check")) {
			run("hierarchy -check");
			run("stat -tech xilinx");
			run("check -noinit");
		}

		if (check_label("edif")) {
			if (!edif_file.empty() || help_mode)
				run(stringf("write_edif -pvector bra %s", edif_file.c_str()));
		}

		if (check_label("blif")) {
			if (!blif_file.empty() || help_mode)
				run(stringf("write_blif %s", edif_file.c_str()));
		}
	}
} SynthXilinxPass;

PRIVATE_NAMESPACE_END
<|endoftext|>


<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// Tracked vehicle model built from subsystems.
//  Location of subsystems hard-coded for M113 vehicle
//  TODO: specify this w/ JSON input data file
//
// =============================================================================

#include <cstdio>

#include "physics/ChGlobal.h"

#include "TrackVehicle.h"

#include "subsys/trackSystem/TrackSystem.h"
#include "subsys/driveline/TrackDriveline.h"

#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"

namespace chrono {

// -----------------------------------------------------------------------------
// Static variables
const ChVector<> TrackVehicle::m_trackPos_Right(0.23644, -0.4780, 0.83475); // relative to chassis COG
const ChVector<> TrackVehicle::m_trackPos_Left(0.23644, -0.4780, -0.83475); // relative to chassis COG

const double     TrackVehicle::m_mass = 5489.2;   // chassis sprung mass
const ChVector<> TrackVehicle::m_COM = ChVector<>(0., 0.0, 0.);  // COM location, relative to body Csys REF frame
const ChVector<> TrackVehicle::m_inertia(1786.9, 10449.7, 10721.2);  // chassis inertia (roll,yaw,pitch)

const ChCoordsys<> TrackVehicle::m_driverCsys(ChVector<>(0.0, 0.5, 1.2), ChQuaternion<>(1, 0, 0, 0));

/// constructor sets the basic integrator settings for this ChSystem, as well as the usual stuff
TrackVehicle::TrackVehicle(const std::string& name,
                           VisualizationType chassisVis,
                           CollisionType chassisCollide)
  :ChTrackVehicle(),
  m_num_tracks(2)
{
  // ---------------------------------------------------------------------------
  // Set the base class variables
  m_vis = chassisVis;
  m_collide = chassisCollide;
  m_meshName = "M113_chassis";
  m_meshFile = utils::GetModelDataFile("M113/Chassis_XforwardYup.obj");
  m_chassisBoxSize = ChVector<>(2.0, 0.6, 0.75);

  // create the chassis body
  m_chassis = ChSharedPtr<ChBodyAuxRef>(new ChBodyAuxRef);
  m_chassis->SetIdentifier(0);
  m_chassis->SetNameString(name);
  m_chassis->SetFrame_COG_to_REF(ChFrame<>(m_COM, ChQuaternion<>(1, 0, 0, 0)));
  // basic body info
  m_chassis->SetMass(m_mass);
  m_chassis->SetInertiaXX(m_inertia);

  // add visualization assets to the chassis
  AddVisualization();

  // m_chassis->SetBodyFixed(true);
  // add the chassis body to the system
  m_system->Add(m_chassis);

  // resize all vectors for the number of track systems
  m_TrackSystems.resize(m_num_tracks);
  m_TrackSystem_locs.resize(m_num_tracks);
  // Right and Left track System relative locations, respectively
  m_TrackSystem_locs[0] = m_trackPos_Right;
  m_TrackSystem_locs[1] = m_trackPos_Left;

  // two drive Gears, like a 2WD driven vehicle.
  m_num_engines = 1;
  m_drivelines.resize(m_num_engines);
  m_ptrains.resize(m_num_engines);

  // create track systems
  for (int i = 0; i < m_num_tracks; i++) {
    m_TrackSystems[i] = ChSharedPtr<TrackSystem>(new TrackSystem("track chain "+std::to_string(i), i) );
  }

  // create the powertrain and drivelines
  for (int j = 0; j < m_num_engines; j++)
  {
    m_drivelines[j] = ChSharedPtr<TrackDriveline>(new TrackDriveline("driveline "+std::to_string(j)) );
    m_ptrains[j] = ChSharedPtr<TrackPowertrain>(new TrackPowertrain("powertrain "+std::to_string(j)) );
  }

  // TODO: add brakes. Perhaps they are a part of the suspension subsystem?

}

TrackVehicle::~TrackVehicle()
{
  if(m_ownsSystem)
    delete m_system;
}

// Set any collision geometry on the hull, then Initialize() all subsystems
void TrackVehicle::Initialize(const ChCoordsys<>& chassis_Csys)
{
  // move the chassis REF frame to the specified initial position/orientation
  m_chassis->SetFrame_REF_to_abs(ChFrame<>(chassis_Csys));

  // add collision geometry to the chassis
  AddCollisionGeometry();

  // initialize the subsystems with the initial c-sys and specified offsets
  for (int i = 0; i < m_num_tracks; i++)
  {
    m_TrackSystems[i]->Initialize(m_chassis, m_TrackSystem_locs[i]);
  }

  // initialize the powertrain, drivelines
  for (int j = 0; j < m_num_engines; j++)
  {
    size_t driveGear_R_idx = 2*j;
    size_t driveGear_L_idx = 2*j + 1;
    m_drivelines[j]->Initialize(m_chassis,
      m_TrackSystems[driveGear_R_idx]->GetDriveGear(),
      m_TrackSystems[driveGear_L_idx]->GetDriveGear());
    m_ptrains[j]->Initialize(m_chassis, m_drivelines[j]->GetDriveshaft());
  }

}

void TrackVehicle::Update(double	time,
                          const std::vector<double>&  throttle,
                          const std::vector<double>&  braking)
{
  assert( throttle.size() >= m_num_tracks);
  assert( braking.size() >= m_num_tracks );
  // update left and right powertrains, with the new left and right throttle/shaftspeed
  for(int i = 0; i < m_num_engines; i++)
  {
    m_ptrains[i]->Update(time, throttle[i], m_drivelines[0]->GetDriveshaftSpeed() );
  }

}

void TrackVehicle::Advance(double step)
{
  double t = 0;
  double settlePhaseA = 0.5;
  double settlePhaseB = 0.8;
  while (t < step) {
    double h = std::min<>(m_stepsize, step - t);
    if( m_system->GetChTime() < settlePhaseA )
    {
      h = 4e-4;
    } else if ( m_system->GetChTime() < settlePhaseB )
    {
      h = 6e-4;
    }
    m_system->DoStepDynamics(h);
    t += h;
  }
}

double TrackVehicle::GetIdlerForce(size_t side) const
{
  assert(side < m_num_tracks);
  ChVector<> out_force = m_TrackSystems[side]->Get_idler_spring_react();

  return out_force.Length();
}

double TrackVehicle::GetDriveshaftSpeed(size_t idx) const
{
  assert(idx < m_drivelines.size() );
  return m_drivelines[idx]->GetDriveshaftSpeed();
}

const ChSharedPtr<TrackPowertrain> TrackVehicle::GetPowertrain(size_t idx) const
{
  assert( idx < m_num_engines );
  return  m_ptrains[idx];
}

} // end namespace chrono
<commit_msg>use new base constructor<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Justin Madsen
// =============================================================================
//
// Tracked vehicle model built from subsystems.
//  Location of subsystems hard-coded for M113 vehicle
//  TODO: specify this w/ JSON input data file
//
// =============================================================================

#include <cstdio>

#include "physics/ChGlobal.h"

#include "TrackVehicle.h"

#include "subsys/trackSystem/TrackSystem.h"
#include "subsys/driveline/TrackDriveline.h"

#include "utils/ChUtilsInputOutput.h"
#include "utils/ChUtilsData.h"

namespace chrono {

// -----------------------------------------------------------------------------
// Static variables
const ChVector<> TrackVehicle::m_trackPos_Right(0.23644, -0.4780, 0.83475); // relative to chassis COG
const ChVector<> TrackVehicle::m_trackPos_Left(0.23644, -0.4780, -0.83475); // relative to chassis COG

const double     TrackVehicle::m_mass = 5489.2;   // chassis sprung mass
const ChVector<> TrackVehicle::m_COM = ChVector<>(0., 0.0, 0.);  // COM location, relative to body Csys REF frame
const ChVector<> TrackVehicle::m_inertia(1786.9, 10449.7, 10721.2);  // chassis inertia (roll,yaw,pitch)

const ChCoordsys<> TrackVehicle::m_driverCsys(ChVector<>(0.0, 0.5, 1.2), ChQuaternion<>(1, 0, 0, 0));

/// constructor sets the basic integrator settings for this ChSystem, as well as the usual stuff
TrackVehicle::TrackVehicle(const std::string& name,
                           VisualizationType chassisVis,
                           CollisionType chassisCollide)
  :ChTrackVehicle(1e-3, 1, chassisVis, chassisCollide),
  m_num_tracks(2)
{
  // ---------------------------------------------------------------------------
  // Set the base class variables
  m_meshName = "M113_chassis";
  m_meshFile = utils::GetModelDataFile("M113/Chassis_XforwardYup.obj");
  m_chassisBoxSize = ChVector<>(2.0, 0.6, 0.75);

  // create the chassis body
  m_chassis = ChSharedPtr<ChBodyAuxRef>(new ChBodyAuxRef);
  m_chassis->SetIdentifier(0);
  m_chassis->SetNameString(name);
  m_chassis->SetFrame_COG_to_REF(ChFrame<>(m_COM, ChQuaternion<>(1, 0, 0, 0)));
  // basic body info
  m_chassis->SetMass(m_mass);
  m_chassis->SetInertiaXX(m_inertia);

  // add visualization assets to the chassis
  AddVisualization();

  // m_chassis->SetBodyFixed(true);
  // add the chassis body to the system
  m_system->Add(m_chassis);

  // resize all vectors for the number of track systems
  m_TrackSystems.resize(m_num_tracks);
  m_TrackSystem_locs.resize(m_num_tracks);
  // Right and Left track System relative locations, respectively
  m_TrackSystem_locs[0] = m_trackPos_Right;
  m_TrackSystem_locs[1] = m_trackPos_Left;

  // two drive Gears, like a 2WD driven vehicle.
  m_num_engines = 1;
  m_drivelines.resize(m_num_engines);
  m_ptrains.resize(m_num_engines);

  // create track systems
  for (int i = 0; i < m_num_tracks; i++) {
    m_TrackSystems[i] = ChSharedPtr<TrackSystem>(new TrackSystem("track chain "+std::to_string(i), i) );
  }

  // create the powertrain and drivelines
  for (int j = 0; j < m_num_engines; j++)
  {
    m_drivelines[j] = ChSharedPtr<TrackDriveline>(new TrackDriveline("driveline "+std::to_string(j)) );
    m_ptrains[j] = ChSharedPtr<TrackPowertrain>(new TrackPowertrain("powertrain "+std::to_string(j)) );
  }

  // TODO: add brakes. Perhaps they are a part of the suspension subsystem?

}

TrackVehicle::~TrackVehicle()
{
  if(m_ownsSystem)
    delete m_system;
}

// Set any collision geometry on the hull, then Initialize() all subsystems
void TrackVehicle::Initialize(const ChCoordsys<>& chassis_Csys)
{
  // move the chassis REF frame to the specified initial position/orientation
  m_chassis->SetFrame_REF_to_abs(ChFrame<>(chassis_Csys));

  // add collision geometry to the chassis
  AddCollisionGeometry();

  // initialize the subsystems with the initial c-sys and specified offsets
  for (int i = 0; i < m_num_tracks; i++)
  {
    m_TrackSystems[i]->Initialize(m_chassis, m_TrackSystem_locs[i]);
  }

  // initialize the powertrain, drivelines
  for (int j = 0; j < m_num_engines; j++)
  {
    size_t driveGear_R_idx = 2*j;
    size_t driveGear_L_idx = 2*j + 1;
    m_drivelines[j]->Initialize(m_chassis,
      m_TrackSystems[driveGear_R_idx]->GetDriveGear(),
      m_TrackSystems[driveGear_L_idx]->GetDriveGear());
    m_ptrains[j]->Initialize(m_chassis, m_drivelines[j]->GetDriveshaft());
  }

}

void TrackVehicle::Update(double	time,
                          const std::vector<double>&  throttle,
                          const std::vector<double>&  braking)
{
  assert( throttle.size() >= m_num_tracks);
  assert( braking.size() >= m_num_tracks );
  // update left and right powertrains, with the new left and right throttle/shaftspeed
  for(int i = 0; i < m_num_engines; i++)
  {
    m_ptrains[i]->Update(time, throttle[i], m_drivelines[0]->GetDriveshaftSpeed() );
  }

}

void TrackVehicle::Advance(double step)
{
  double t = 0;
  double settlePhaseA = 0.5;
  double settlePhaseB = 0.8;
  while (t < step) {
    double h = std::min<>(m_stepsize, step - t);
    if( m_system->GetChTime() < settlePhaseA )
    {
      h = 4e-4;
    } else if ( m_system->GetChTime() < settlePhaseB )
    {
      h = 6e-4;
    }
    m_system->DoStepDynamics(h);
    t += h;
  }
}

double TrackVehicle::GetIdlerForce(size_t side) const
{
  assert(side < m_num_tracks);
  ChVector<> out_force = m_TrackSystems[side]->Get_idler_spring_react();

  return out_force.Length();
}

double TrackVehicle::GetDriveshaftSpeed(size_t idx) const
{
  assert(idx < m_drivelines.size() );
  return m_drivelines[idx]->GetDriveshaftSpeed();
}

const ChSharedPtr<TrackPowertrain> TrackVehicle::GetPowertrain(size_t idx) const
{
  assert( idx < m_num_engines );
  return  m_ptrains[idx];
}

} // end namespace chrono
<|endoftext|>


<commit_before>/*
    This file is part of KOrganizer.

    Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qwidget.h>

#include <kaboutdata.h>
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <kcmdlineargs.h>

#include "alarmdialog.h"

int main(int argc,char **argv)
{
  KAboutData aboutData("testkabc",I18N_NOOP("TestKabc"),"0.1");
  KCmdLineArgs::init(argc,argv,&aboutData);

  KApplication app;

  Event *e = new Event;
  e->setSummary( "This is a summary." );
  e->setDtStart( QDateTime::currentDateTime() );
  e->setDtEnd( QDateTime::currentDateTime().addDays( 1 ) );

  Alarm *a = e->newAlarm();
//  a->setProcedureAlarm( "/usr/X11R6/bin/xeyes" );
  a->setAudioAlarm( "/opt/kde/share/apps/korganizer/sounds/spinout.wav" );

  AlarmDialog dlg;
  app.setMainWidget( &dlg );
  dlg.setIncidence( e );
  dlg.show();
  dlg.eventNotification();

  app.exec();
}
<commit_msg>fix make check<commit_after>/*
    This file is part of KOrganizer.

    Copyright (c) 2002 Cornelius Schumacher <schumacher@kde.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.

    As a special exception, permission is given to link this program
    with any edition of Qt, and distribute the resulting executable,
    without including the source code for Qt in the source distribution.
*/

#include <qwidget.h>

#include <kaboutdata.h>
#include <kapplication.h>
#include <kdebug.h>
#include <klocale.h>
#include <kcmdlineargs.h>

#include "alarmdialog.h"

int main(int argc,char **argv)
{
  KAboutData aboutData("testkabc",I18N_NOOP("TestKabc"),"0.1");
  KCmdLineArgs::init(argc,argv,&aboutData);

  KApplication app;

  Event *e = new Event;
  e->setSummary( "This is a summary." );
  e->setDtStart( QDateTime::currentDateTime() );
  e->setDtEnd( QDateTime::currentDateTime().addDays( 1 ) );

  Alarm *a = e->newAlarm();
//  a->setProcedureAlarm( "/usr/X11R6/bin/xeyes" );
  a->setAudioAlarm( "/opt/kde/share/apps/korganizer/sounds/spinout.wav" );

  AlarmDialog dlg;
  app.setMainWidget( &dlg );
  dlg.addIncidence( e, QDateTime::currentDateTime() );
  dlg.show();
  dlg.eventNotification();

  app.exec();
}
<|endoftext|>


<commit_before>/*
    This file is part of Magnum.

    Original authors — credit is appreciated but not required:

        2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 —
            Vladimír Vondruš <mosra@centrum.cz>
        2013 — Jan Dupal <dupal.j@gmail.com>

    This is free and unencumbered software released into the public domain.

    Anyone is free to copy, modify, publish, use, compile, sell, or distribute
    this software, either in source code form or as a compiled binary, for any
    purpose, commercial or non-commercial, and by any means.

    In jurisdictions that recognize copyright laws, the author or authors of
    this software dedicate any and all copyright interest in the software to
    the public domain. We make this dedication for the benefit of the public
    at large and to the detriment of our heirs and successors. We intend this
    dedication to be an overt act of relinquishment in perpetuity of all
    present and future rights to this software under copyright law.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
    IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
    CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <btBulletDynamicsCommon.h>
#include <Corrade/Containers/Optional.h>
#include <Magnum/Timeline.h>
#include <Magnum/BulletIntegration/Integration.h>
#include <Magnum/BulletIntegration/MotionState.h>
#include <Magnum/BulletIntegration/DebugDraw.h>
#include <Magnum/GL/DefaultFramebuffer.h>
#include <Magnum/GL/Mesh.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/Math/Constants.h>
#include <Magnum/MeshTools/Compile.h>
#include <Magnum/MeshTools/Transform.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/Primitives/Cube.h>
#include <Magnum/Primitives/UVSphere.h>
#include <Magnum/SceneGraph/Camera.h>
#include <Magnum/SceneGraph/Drawable.h>
#include <Magnum/SceneGraph/MatrixTransformation3D.h>
#include <Magnum/SceneGraph/Scene.h>
#include <Magnum/Shaders/Phong.h>
#include <Magnum/Trade/MeshData3D.h>

namespace Magnum { namespace Examples {

using namespace Math::Literals;

typedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D;
typedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D;

class BulletExample: public Platform::Application {
    public:
        explicit BulletExample(const Arguments& arguments);

    private:
        void drawEvent() override;
        void keyPressEvent(KeyEvent& event) override;
        void mousePressEvent(MouseEvent& event) override;

        btRigidBody* createRigidBody(Object3D& object, Float mass, btCollisionShape* bShape);

        GL::Mesh _box{NoCreate}, _sphere{NoCreate};
        Shaders::Phong _shader{NoCreate};
        BulletIntegration::DebugDraw _debugDraw{NoCreate};

        Scene3D _scene;
        SceneGraph::Camera3D* _camera;
        SceneGraph::DrawableGroup3D _drawables;
        Timeline _timeline;

        Object3D *_cameraRig, *_cameraObject;
        btDiscreteDynamicsWorld* _bWorld;
        btCollisionShape *_bBoxShape, *_bSphereShape;
        btRigidBody* _bGround;

        bool _drawCubes{true}, _drawDebug{true}, _shootBox{true};
};

class ColoredDrawable: public SceneGraph::Drawable3D {
    public:
        explicit ColoredDrawable(Object3D& object, Shaders::Phong& shader, GL::Mesh& mesh, const Color4& color, const Matrix4& primitiveTransformation, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _shader(shader), _mesh(mesh), _color{color}, _primitiveTransformation{primitiveTransformation} {}

    private:
        void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) override {
            _shader.setDiffuseColor(_color)
                .setTransformationMatrix(transformation*_primitiveTransformation)
                .setProjectionMatrix(camera.projectionMatrix())
                .setNormalMatrix(transformation.rotationScaling());
            _mesh.draw(_shader);
        }

        Shaders::Phong& _shader;
        GL::Mesh& _mesh;
        Color4 _color;
        Matrix4 _primitiveTransformation;
};

BulletExample::BulletExample(const Arguments& arguments): Platform::Application(arguments, NoCreate) {
    /* Try 8x MSAA, fall back to zero samples if not possible. Enable only 2x
       MSAA if we have enough DPI. */
    {
        const Vector2 dpiScaling = this->dpiScaling({});
        Configuration conf;
        conf.setTitle("Magnum Bullet Integration Example")
            .setSize(conf.size(), dpiScaling);
        GLConfiguration glConf;
        glConf.setSampleCount(dpiScaling.max() < 2.0f ? 8 : 2);
        if(!tryCreate(conf, glConf))
            create(conf, glConf.setSampleCount(0));
    }

    /* Camera setup */
    (*(_cameraRig = new Object3D{&_scene}))
        .translate(Vector3::yAxis(3.0f))
        .rotateY(40.0_degf);
    (*(_cameraObject = new Object3D{_cameraRig}))
        .translate(Vector3::zAxis(20.0f))
        .rotateX(-25.0_degf);
    (_camera = new SceneGraph::Camera3D(*_cameraObject))
        ->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend)
        .setProjectionMatrix(Matrix4::perspectiveProjection(35.0_degf, 1.0f, 0.001f, 100.0f))
        .setViewport(GL::defaultFramebuffer.viewport().size());

    /* Drawing setup */
    _box = MeshTools::compile(Primitives::cubeSolid());
    _sphere = MeshTools::compile(Primitives::uvSphereSolid(16, 32));
    _shader = Shaders::Phong{};
    _shader.setAmbientColor(0x111111_rgbf)
           .setSpecularColor(0x330000_rgbf)
           .setLightPosition({10.0f, 15.0f, 5.0f});
    _debugDraw = BulletIntegration::DebugDraw{};
    _debugDraw.setMode(BulletIntegration::DebugDraw::Mode::DrawWireframe);

    /* Setup the renderer so we can draw the debug lines on top */
    GL::Renderer::enable(GL::Renderer::Feature::DepthTest);
    GL::Renderer::enable(GL::Renderer::Feature::FaceCulling);
    GL::Renderer::enable(GL::Renderer::Feature::PolygonOffsetFill);
    GL::Renderer::setPolygonOffset(2.0f, 0.5f);

    /* Bullet setup */
    auto* broadphase = new btDbvtBroadphase;
    auto* collisionConfiguration = new btDefaultCollisionConfiguration;
    auto* dispatcher = new btCollisionDispatcher{collisionConfiguration};
    auto* solver = new btSequentialImpulseConstraintSolver;
    _bWorld = new btDiscreteDynamicsWorld{dispatcher, broadphase, solver, collisionConfiguration};
    _bWorld->setGravity({0.0f, -10.0f, 0.0f});
    _bWorld->setDebugDrawer(&_debugDraw);
    _bBoxShape = new btBoxShape{{0.5f, 0.5f, 0.5f}};
    _bSphereShape = new btSphereShape{0.25f};

    /* Create the ground */
    auto* ground = new Object3D{&_scene};
    _bGround = createRigidBody(*ground, 0.0f, new btBoxShape{{4.0f, 0.5f, 4.0f}});
    new ColoredDrawable{*ground, _shader, _box, 0xffffff_rgbf,
        Matrix4::scaling({4.0f, 0.5f, 4.0f}), _drawables};

    /* Create boxes with random colors */
    Deg hue = 42.0_degf;
    for(Int i = 0; i != 5; ++i) {
        for(Int j = 0; j != 5; ++j) {
            for(Int k = 0; k != 5; ++k) {
                auto* o = new Object3D{&_scene};
                o->translate({i - 2.0f, j + 4.0f, k - 2.0f});
                new ColoredDrawable{*o, _shader, _box,
                    Color3::fromHsv(hue += 137.5_degf, 0.75f, 0.9f),
                    Matrix4::scaling(Vector3{0.5f}), _drawables};
                createRigidBody(*o, 1.0f, _bBoxShape);
            }
        }
    }

    /* Loop at 60 Hz max */
    setSwapInterval(1);
    setMinimalLoopPeriod(16);
    _timeline.start();
}

btRigidBody* BulletExample::createRigidBody(Object3D& object, Float mass, btCollisionShape* bShape) {
    /* Calculate inertia so the object reacts as it should with rotation and
       everything */
    btVector3 bInertia(0.0f, 0.0f, 0.0f);
    if(mass != 0.0f) bShape->calculateLocalInertia(mass, bInertia);

    /* Bullet rigid body setup */
    auto* motionState = new BulletIntegration::MotionState{object};
    auto* bRigidBody = new btRigidBody{btRigidBody::btRigidBodyConstructionInfo{
        mass, &motionState->btMotionState(), bShape, bInertia}};
    bRigidBody->forceActivationState(DISABLE_DEACTIVATION);
    _bWorld->addRigidBody(bRigidBody);

    return bRigidBody;
}

void BulletExample::drawEvent() {
    GL::defaultFramebuffer.clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth);

    /* Step bullet simulation */
    _bWorld->stepSimulation(_timeline.previousFrameDuration(), 5);

    /* Draw the cubes */
    if(_drawCubes) _camera->draw(_drawables);

    /* Debug draw. If drawing on top of cubes, avoid flickering by setting
       depth function to <= instead of just <. */
    if(_drawDebug) {
        if(_drawCubes)
            GL::Renderer::setDepthFunction(GL::Renderer::DepthFunction::LessOrEqual);

        _debugDraw.setTransformationProjectionMatrix(
            _camera->projectionMatrix()*_camera->cameraMatrix());
        _bWorld->debugDrawWorld();

        if(_drawCubes)
            GL::Renderer::setDepthFunction(GL::Renderer::DepthFunction::Less);
    }

    swapBuffers();
    _timeline.nextFrame();
    redraw();
}

void BulletExample::keyPressEvent(KeyEvent& event) {
    /* Movement */
    if(event.key() == KeyEvent::Key::Down) {
        _cameraObject->rotateX(5.0_degf);
    } else if(event.key() == KeyEvent::Key::Up) {
        _cameraObject->rotateX(-5.0_degf);
    } else if(event.key() == KeyEvent::Key::Left) {
        _cameraRig->rotateY(-5.0_degf);
    } else if(event.key() == KeyEvent::Key::Right) {
        _cameraRig->rotateY(5.0_degf);

    /* Toggling draw modes */
    } else if(event.key() == KeyEvent::Key::D) {
        if(_drawCubes && _drawDebug) {
            _drawDebug = false;
        } else if(_drawCubes && !_drawDebug) {
            _drawCubes = false;
            _drawDebug = true;
        } else if(!_drawCubes && _drawDebug) {
            _drawCubes = true;
            _drawDebug = true;
        }

    /* What to shoot */
    } else if(event.key() == KeyEvent::Key::S) {
        _shootBox ^= true;
    } else return;

    event.setAccepted();
}

void BulletExample::mousePressEvent(MouseEvent& event) {
    /* Shoot an object on click */
    if(event.button() == MouseEvent::Button::Left) {
        const Vector2 clickPoint = Vector2::yScale(-1.0f)*(Vector2{event.position()}/Vector2{GL::defaultFramebuffer.viewport().size()} - Vector2{0.5f})* _camera->projectionSize();
        const Vector3 direction = (_cameraObject->absoluteTransformation().rotationScaling()*Vector3{clickPoint, -1.0f}).normalized();

        Object3D* o = new Object3D(&_scene);
        o->translate(_cameraObject->absoluteTransformation().translation());

        /* Create either a box or a sphere */
        new ColoredDrawable{*o, _shader, _shootBox ? _box : _sphere,
            _shootBox ? 0x880000_rgbf : 0x220000_rgbf,
            Matrix4::scaling(Vector3{_shootBox ? 0.5f : 0.25f}), _drawables};
        createRigidBody(*o,
            _shootBox ? 1.0f : 5.0f,
            _shootBox ? _bBoxShape : _bSphereShape)
                ->setLinearVelocity(btVector3{direction*25.f});

        event.setAccepted();
    }
}

}}

MAGNUM_APPLICATION_MAIN(Magnum::Examples::BulletExample)
<commit_msg>bullet: fix memory leaks related to Bullet<commit_after>/*
    This file is part of Magnum.

    Original authors — credit is appreciated but not required:

        2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 —
            Vladimír Vondruš <mosra@centrum.cz>
        2013 — Jan Dupal <dupal.j@gmail.com>

    This is free and unencumbered software released into the public domain.

    Anyone is free to copy, modify, publish, use, compile, sell, or distribute
    this software, either in source code form or as a compiled binary, for any
    purpose, commercial or non-commercial, and by any means.

    In jurisdictions that recognize copyright laws, the author or authors of
    this software dedicate any and all copyright interest in the software to
    the public domain. We make this dedication for the benefit of the public
    at large and to the detriment of our heirs and successors. We intend this
    dedication to be an overt act of relinquishment in perpetuity of all
    present and future rights to this software under copyright law.

    THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
    THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
    IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
    CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include <btBulletDynamicsCommon.h>
#include <Corrade/Containers/Optional.h>
#include <Corrade/Containers/Pointer.h>
#include <Magnum/Timeline.h>
#include <Magnum/BulletIntegration/Integration.h>
#include <Magnum/BulletIntegration/MotionState.h>
#include <Magnum/BulletIntegration/DebugDraw.h>
#include <Magnum/GL/DefaultFramebuffer.h>
#include <Magnum/GL/Mesh.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/Math/Constants.h>
#include <Magnum/MeshTools/Compile.h>
#include <Magnum/MeshTools/Transform.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/Primitives/Cube.h>
#include <Magnum/Primitives/UVSphere.h>
#include <Magnum/SceneGraph/Camera.h>
#include <Magnum/SceneGraph/Drawable.h>
#include <Magnum/SceneGraph/MatrixTransformation3D.h>
#include <Magnum/SceneGraph/Scene.h>
#include <Magnum/Shaders/Phong.h>
#include <Magnum/Trade/MeshData3D.h>

namespace Magnum { namespace Examples {

using namespace Math::Literals;

typedef SceneGraph::Object<SceneGraph::MatrixTransformation3D> Object3D;
typedef SceneGraph::Scene<SceneGraph::MatrixTransformation3D> Scene3D;

class BulletExample: public Platform::Application {
    public:
        explicit BulletExample(const Arguments& arguments);

    private:
        void drawEvent() override;
        void keyPressEvent(KeyEvent& event) override;
        void mousePressEvent(MouseEvent& event) override;

        GL::Mesh _box{NoCreate}, _sphere{NoCreate};
        Shaders::Phong _shader{NoCreate};
        BulletIntegration::DebugDraw _debugDraw{NoCreate};

        btDbvtBroadphase _bBroadphase;
        btDefaultCollisionConfiguration _bCollisionConfig;
        btCollisionDispatcher _bDispatcher{&_bCollisionConfig};
        btSequentialImpulseConstraintSolver _bSolver;
        btDiscreteDynamicsWorld _bWorld{&_bDispatcher, &_bBroadphase, &_bSolver, &_bCollisionConfig};

        Scene3D _scene;
        SceneGraph::Camera3D* _camera;
        SceneGraph::DrawableGroup3D _drawables;
        Timeline _timeline;

        Object3D *_cameraRig, *_cameraObject;

        btBoxShape _bBoxShape{{0.5f, 0.5f, 0.5f}};
        btSphereShape _bSphereShape{0.25f};
        btBoxShape _bGroundShape{{4.0f, 0.5f, 4.0f}};

        bool _drawCubes{true}, _drawDebug{true}, _shootBox{true};
};

class ColoredDrawable: public SceneGraph::Drawable3D {
    public:
        explicit ColoredDrawable(Object3D& object, Shaders::Phong& shader, GL::Mesh& mesh, const Color4& color, const Matrix4& primitiveTransformation, SceneGraph::DrawableGroup3D& drawables): SceneGraph::Drawable3D{object, &drawables}, _shader(shader), _mesh(mesh), _color{color}, _primitiveTransformation{primitiveTransformation} {}

    private:
        void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) override {
            _shader.setDiffuseColor(_color)
                .setTransformationMatrix(transformation*_primitiveTransformation)
                .setProjectionMatrix(camera.projectionMatrix())
                .setNormalMatrix(transformation.rotationScaling());
            _mesh.draw(_shader);
        }

        Shaders::Phong& _shader;
        GL::Mesh& _mesh;
        Color4 _color;
        Matrix4 _primitiveTransformation;
};

class RigidBody: public Object3D {
    public:
        RigidBody(Object3D* parent, Float mass, btCollisionShape* bShape, btDynamicsWorld& bWorld): Object3D{parent}, _bWorld{bWorld} {
            /* Calculate inertia so the object reacts as it should with
               rotation and everything */
            btVector3 bInertia(0.0f, 0.0f, 0.0f);
            if(mass != 0.0f) bShape->calculateLocalInertia(mass, bInertia);

            /* Bullet rigid body setup */
            auto* motionState = new BulletIntegration::MotionState{*this};
            _bRigidBody.emplace(btRigidBody::btRigidBodyConstructionInfo{
                mass, &motionState->btMotionState(), bShape, bInertia});
            _bRigidBody->forceActivationState(DISABLE_DEACTIVATION);
            bWorld.addRigidBody(_bRigidBody.get());
        }

        ~RigidBody() {
            _bWorld.removeRigidBody(_bRigidBody.get());
        }

        btRigidBody& rigidBody() { return *_bRigidBody; }

        /* needed after changing the pose from Magnum side */
        void syncPose() {
            _bRigidBody->setWorldTransform(btTransform(transformationMatrix()));
        }

    private:
        btDynamicsWorld& _bWorld;
        Containers::Pointer<btRigidBody> _bRigidBody;
};

BulletExample::BulletExample(const Arguments& arguments): Platform::Application(arguments, NoCreate) {
    /* Try 8x MSAA, fall back to zero samples if not possible. Enable only 2x
       MSAA if we have enough DPI. */
    {
        const Vector2 dpiScaling = this->dpiScaling({});
        Configuration conf;
        conf.setTitle("Magnum Bullet Integration Example")
            .setSize(conf.size(), dpiScaling);
        GLConfiguration glConf;
        glConf.setSampleCount(dpiScaling.max() < 2.0f ? 8 : 2);
        if(!tryCreate(conf, glConf))
            create(conf, glConf.setSampleCount(0));
    }

    /* Camera setup */
    (*(_cameraRig = new Object3D{&_scene}))
        .translate(Vector3::yAxis(3.0f))
        .rotateY(40.0_degf);
    (*(_cameraObject = new Object3D{_cameraRig}))
        .translate(Vector3::zAxis(20.0f))
        .rotateX(-25.0_degf);
    (_camera = new SceneGraph::Camera3D(*_cameraObject))
        ->setAspectRatioPolicy(SceneGraph::AspectRatioPolicy::Extend)
        .setProjectionMatrix(Matrix4::perspectiveProjection(35.0_degf, 1.0f, 0.001f, 100.0f))
        .setViewport(GL::defaultFramebuffer.viewport().size());

    /* Drawing setup */
    _box = MeshTools::compile(Primitives::cubeSolid());
    _sphere = MeshTools::compile(Primitives::uvSphereSolid(16, 32));
    _shader = Shaders::Phong{};
    _shader.setAmbientColor(0x111111_rgbf)
           .setSpecularColor(0x330000_rgbf)
           .setLightPosition({10.0f, 15.0f, 5.0f});
    _debugDraw = BulletIntegration::DebugDraw{};
    _debugDraw.setMode(BulletIntegration::DebugDraw::Mode::DrawWireframe);

    /* Setup the renderer so we can draw the debug lines on top */
    GL::Renderer::enable(GL::Renderer::Feature::DepthTest);
    GL::Renderer::enable(GL::Renderer::Feature::FaceCulling);
    GL::Renderer::enable(GL::Renderer::Feature::PolygonOffsetFill);
    GL::Renderer::setPolygonOffset(2.0f, 0.5f);

    /* Bullet setup */
    _bWorld.setGravity({0.0f, -10.0f, 0.0f});
    _bWorld.setDebugDrawer(&_debugDraw);

    /* Create the ground */
    auto* ground = new RigidBody{&_scene, 0.0f, &_bGroundShape, _bWorld};
    new ColoredDrawable{*ground, _shader, _box, 0xffffff_rgbf,
        Matrix4::scaling({4.0f, 0.5f, 4.0f}), _drawables};

    /* Create boxes with random colors */
    Deg hue = 42.0_degf;
    for(Int i = 0; i != 5; ++i) {
        for(Int j = 0; j != 5; ++j) {
            for(Int k = 0; k != 5; ++k) {
                auto* o = new RigidBody{&_scene, 1.0f, &_bBoxShape, _bWorld};
                o->translate({i - 2.0f, j + 4.0f, k - 2.0f});
                o->syncPose();
                new ColoredDrawable{*o, _shader, _box,
                    Color3::fromHsv(hue += 137.5_degf, 0.75f, 0.9f),
                    Matrix4::scaling(Vector3{0.5f}), _drawables};
            }
        }
    }

    /* Loop at 60 Hz max */
    setSwapInterval(1);
    setMinimalLoopPeriod(16);
    _timeline.start();
}

void BulletExample::drawEvent() {
    GL::defaultFramebuffer.clear(GL::FramebufferClear::Color|GL::FramebufferClear::Depth);

    /* Housekeeping: remove any objects which are far away from the origin */
    for(Object3D* obj = _scene.children().first(); obj; )
    {
        Object3D* next = obj->nextSibling();
        if(obj->transformation().translation().dot() > 100*100)
            delete obj;

        obj = next;
    }

    /* Step bullet simulation */
    _bWorld.stepSimulation(_timeline.previousFrameDuration(), 5);

    /* Draw the cubes */
    if(_drawCubes) _camera->draw(_drawables);

    /* Debug draw. If drawing on top of cubes, avoid flickering by setting
       depth function to <= instead of just <. */
    if(_drawDebug) {
        if(_drawCubes)
            GL::Renderer::setDepthFunction(GL::Renderer::DepthFunction::LessOrEqual);

        _debugDraw.setTransformationProjectionMatrix(
            _camera->projectionMatrix()*_camera->cameraMatrix());
        _bWorld.debugDrawWorld();

        if(_drawCubes)
            GL::Renderer::setDepthFunction(GL::Renderer::DepthFunction::Less);
    }

    swapBuffers();
    _timeline.nextFrame();
    redraw();
}

void BulletExample::keyPressEvent(KeyEvent& event) {
    /* Movement */
    if(event.key() == KeyEvent::Key::Down) {
        _cameraObject->rotateX(5.0_degf);
    } else if(event.key() == KeyEvent::Key::Up) {
        _cameraObject->rotateX(-5.0_degf);
    } else if(event.key() == KeyEvent::Key::Left) {
        _cameraRig->rotateY(-5.0_degf);
    } else if(event.key() == KeyEvent::Key::Right) {
        _cameraRig->rotateY(5.0_degf);

    /* Toggling draw modes */
    } else if(event.key() == KeyEvent::Key::D) {
        if(_drawCubes && _drawDebug) {
            _drawDebug = false;
        } else if(_drawCubes && !_drawDebug) {
            _drawCubes = false;
            _drawDebug = true;
        } else if(!_drawCubes && _drawDebug) {
            _drawCubes = true;
            _drawDebug = true;
        }

    /* What to shoot */
    } else if(event.key() == KeyEvent::Key::S) {
        _shootBox ^= true;
    } else return;

    event.setAccepted();
}

void BulletExample::mousePressEvent(MouseEvent& event) {
    /* Shoot an object on click */
    if(event.button() == MouseEvent::Button::Left) {
        const Vector2 clickPoint = Vector2::yScale(-1.0f)*(Vector2{event.position()}/Vector2{GL::defaultFramebuffer.viewport().size()} - Vector2{0.5f})* _camera->projectionSize();
        const Vector3 direction = (_cameraObject->absoluteTransformation().rotationScaling()*Vector3{clickPoint, -1.0f}).normalized();

        auto* object = new RigidBody{
            &_scene,
            _shootBox ? 1.0f : 5.0f,
            _shootBox ? static_cast<btCollisionShape*>(&_bBoxShape) : &_bSphereShape,
            _bWorld};
        object->translate(_cameraObject->absoluteTransformation().translation());
        object->syncPose();

        /* Create either a box or a sphere */
        new ColoredDrawable{*object, _shader, _shootBox ? _box : _sphere,
            _shootBox ? 0x880000_rgbf : 0x220000_rgbf,
            Matrix4::scaling(Vector3{_shootBox ? 0.5f : 0.25f}), _drawables};

        /* Give it an initial velocity */
        object->rigidBody().setLinearVelocity(btVector3{direction*25.f});

        event.setAccepted();
    }
}

}}

MAGNUM_APPLICATION_MAIN(Magnum::Examples::BulletExample)
<|endoftext|>


<commit_before>/*
 * This file is part of the Yildiz-Engine project, licenced under the MIT License  (MIT)
 *
 * Copyright (c) 2019 Grégory Van den Borre
 *
 * More infos available: https://engine.yildiz-games.be
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
 * OR COPYRIGHT  HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  SOFTWARE.
 */

#include <OgreArchive.h>
#include <OgreString.h>
#include <yz_physfs_File.hpp>

namespace yz {

namespace ogre {

namespace vfs {

/**
* Ogre Archive implementation for a VFS.
*@author Grégory Van den Borre
*/
class Archive: public Ogre::Archive {

public:

    Archive(yz::physfs::Wrapper* vfs, const Ogre::String& name, const Ogre::String& type) : Ogre::Archive(name, type), this->vfs(vfs) {
        LOG_FUNCTION
    }

    /** PhysFS is case sensitive in general */
    bool isCaseSensitive() const {
        LOG_FUNCTION
        return true;
    }

    /**
     * Loading is handled by the VFS.
     */
    void load() {
        LOG_FUNCTION
    }

    /**
     * Unloading is handled by the VFS.
     */
    void unload() {
        LOG_FUNCTION
    }

    inline time_t getModifiedTime(const Ogre::String& file) const {
        LOG_FUNCTION
        return this->vfs->getLastModTime(file);
    }

    Ogre::DataStreamPtr open(const Ogre::String& filename, bool append) const;

    Ogre::StringVectorPtr list(bool recursive = true, bool dirs = false) const;

    Ogre::FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false) const;

    Ogre::StringVectorPtr find(const Ogre::String& pattern, bool recursive = true, bool dirs = false) const;

    bool exists(const Ogre::String& filename) const;

    Ogre::FileInfoListPtr findFileInfo(const Ogre::String& pattern, bool recursive = true, bool dirs = false) const;

private:

    void listInfoRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::FileInfoListPtr fileInfoList) const;

    void listRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::StringVectorPtr fileList) const;

    yz::physfs::Wrapper* vfs;
};
}}}
<commit_msg>[WIP] Use Vfs module.<commit_after>/*
 * This file is part of the Yildiz-Engine project, licenced under the MIT License  (MIT)
 *
 * Copyright (c) 2019 Grégory Van den Borre
 *
 * More infos available: https://engine.yildiz-games.be
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated
 * documentation files (the "Software"), to deal in the Software without restriction, including without
 * limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
 * of the Software, and to permit persons to whom the Software is furnished to do so,
 * subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all copies or substantial
 * portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS
 * OR COPYRIGHT  HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE  SOFTWARE.
 */

#include <OgreArchive.h>
#include <OgreString.h>
#include <yz_physfs_File.hpp>

namespace yz {

namespace ogre {

namespace vfs {

/**
* Ogre Archive implementation for a VFS.
*@author Grégory Van den Borre
*/
class Archive: public Ogre::Archive {

public:

    Archive(yz::physfs::Wrapper* vfs, const Ogre::String& name, const Ogre::String& type) : Ogre::Archive(name, type), vfs(vfs) {
        LOG_FUNCTION
    }

    /** PhysFS is case sensitive in general */
    bool isCaseSensitive() const {
        LOG_FUNCTION
        return true;
    }

    /**
     * Loading is handled by the VFS.
     */
    void load() {
        LOG_FUNCTION
    }

    /**
     * Unloading is handled by the VFS.
     */
    void unload() {
        LOG_FUNCTION
    }

    inline time_t getModifiedTime(const Ogre::String& file) const {
        LOG_FUNCTION
        return this->vfs->getLastModTime(file);
    }

    Ogre::DataStreamPtr open(const Ogre::String& filename, bool append) const;

    Ogre::StringVectorPtr list(bool recursive = true, bool dirs = false) const;

    Ogre::FileInfoListPtr listFileInfo(bool recursive = true, bool dirs = false) const;

    Ogre::StringVectorPtr find(const Ogre::String& pattern, bool recursive = true, bool dirs = false) const;

    bool exists(const Ogre::String& filename) const;

    Ogre::FileInfoListPtr findFileInfo(const Ogre::String& pattern, bool recursive = true, bool dirs = false) const;

private:

    void listInfoRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::FileInfoListPtr fileInfoList) const;

    void listRecursive(const Ogre::String& base, bool recursive, bool dirs, Ogre::StringVectorPtr fileList) const;

    yz::physfs::Wrapper* vfs;
};
}}}
<|endoftext|>


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

/*
 * warm_start_ipopt_interface.cc
 */

#include "modules/planning/planner/open_space/warm_start_ipopt_interface.h"

#include <math.h>
#include <utility>

#include "modules/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

constexpr std::size_t N = 80;

WarmStartIPOPTInterface::WarmStartIPOPTInterface(
    int num_of_variables, int num_of_constraints, std::size_t horizon, float ts,
    float wheelbase_length, Eigen::MatrixXd x0, Eigen::MatrixXd xf,
    Eigen::MatrixXd XYbounds)
    : num_of_variables_(num_of_variables),
      num_of_constraints_(num_of_constraints),
      horizon_(horizon),
      ts_(ts),
      wheelbase_length_(wheelbase_length),
      x0_(x0),
      xf_(xf),
      XYbounds_(XYbounds) {}

void WarmStartIPOPTInterface::get_optimization_results() const {}

bool WarmStartIPOPTInterface::get_nlp_info(int& n, int& m, int& nnz_jac_g,
                                           int& nnz_h_lag,
                                           IndexStyleEnum& index_style) {
  // number of variables
  n = num_of_variables_;

  // number of constraints

  m = num_of_constraints_;

  // number of nonzero hessian and lagrangian.

  // TODO(QiL) : Update nnz_jac_g;
  nnz_jac_g = 0;

  // TOdo(QiL) : Update nnz_h_lag;
  nnz_h_lag = 0;

  index_style = IndexStyleEnum::C_STYLE;
  return true;
}

bool WarmStartIPOPTInterface::get_bounds_info(int n, double* x_l, double* x_u,
                                              int m, double* g_l, double* g_u) {
  // here, the n and m we gave IPOPT in get_nlp_info are passed back to us.
  // If desired, we could assert to make sure they are what we think they are.
  CHECK(n == num_of_variables_) << "num_of_variables_ mismatch, n: " << n
                                << ", num_of_variables_: " << num_of_variables_;
  CHECK(m == num_of_constraints_)
      << "num_of_constraints_ mismatch, n: " << n
      << ", num_of_constraints_: " << num_of_constraints_;

  // Variables: includes u and sample time

  /*
  for (std::size_t i = 0; i < horizon_; ++i) {
    variable_index = i * 3;

    // steer command
    x_l[variable_index] = -0.6;
    x_u[variable_index] = 0.6;

    // acceleration
    x_l[variable_index + 1] = -1;
    x_u[variable_index + 1] = 1;

    // sampling time;
    x_l[variable_index + 2] = 0.5;
    x_u[variable_index + 2] = 2.5;
  }
*/
  // 1. state variables
  // start point pose
  std::size_t variable_index = 0;
  for (std::size_t i = 0; i < 4; ++i) {
    x_l[i] = x0_(i, 0);
    x_u[i] = x0_(i, 0);
  }
  variable_index += 4;

  // During horizons
  for (std::size_t i = 1; i < horizon_ - 1; ++i) {
    // x
    x_l[variable_index] = XYbounds_(0, 0);
    x_u[variable_index] = XYbounds_(1, 0);

    // y
    x_l[variable_index + 1] = XYbounds_(2, 0);
    x_u[variable_index + 1] = XYbounds_(3, 0);

    // phi
    // TODO(QiL): Change this to configs
    x_l[variable_index + 2] = -7;
    x_u[variable_index + 2] = 7;

    // v
    // TODO(QiL) : Change this to configs
    x_l[variable_index + 3] = -1;
    x_u[variable_index + 3] = 2;

    variable_index += 4;
  }

  // end point pose
  for (std::size_t i = 0; i < 4; ++i) {
    x_l[variable_index + i] = xf_(i, 0);
    x_u[variable_index + i] = xf_(i, 0);
  }
  variable_index += 4;
  ADEBUG << "variable_index after adding state constraints : "
         << variable_index;

  // 2. input constraints
  for (std::size_t i = 1; i < horizon_; ++i) {
    // u1
    x_l[variable_index] = -0.6;
    x_u[variable_index] = 0.6;

    // u2
    x_l[variable_index + 1] = -1;
    x_u[variable_index + 1] = 1;

    variable_index += 2;
  }
  ADEBUG << "variable_index after adding input constraints : "
         << variable_index;

  // 3. sampling time constraints
  for (std::size_t i = 1; i < horizon_; ++i) {
    x_l[variable_index] = -0.6;
    x_u[variable_index] = 0.6;

    ++variable_index;
  }

  ADEBUG << "variable_index : " << variable_index;

  // Constraints

  // 1. state constraints
  // start point pose
  std::size_t constraint_index = 0;
  for (std::size_t i = 0; i < 4; ++i) {
    g_l[i] = x0_(i, 0);
    g_u[i] = x0_(i, 0);
  }
  constraint_index += 4;

  // During horizons
  for (std::size_t i = 1; i < horizon_ - 1; ++i) {
    // x
    g_l[constraint_index] = XYbounds_(0, 0);
    g_u[constraint_index] = XYbounds_(1, 0);

    // y
    g_l[constraint_index + 1] = XYbounds_(2, 0);
    g_u[constraint_index + 1] = XYbounds_(3, 0);

    // phi
    // TODO(QiL): Change this to configs
    g_l[constraint_index + 2] = -7;
    g_u[constraint_index + 2] = 7;

    // v
    // TODO(QiL) : Change this to configs
    g_l[constraint_index + 3] = -1;
    g_u[constraint_index + 3] = 2;

    constraint_index += 4;
  }

  // end point pose
  for (std::size_t i = 0; i < 4; ++i) {
    g_l[constraint_index + i] = xf_(i, 0);
    g_u[constraint_index + i] = xf_(i, 0);
  }
  constraint_index += 4;
  ADEBUG << "constraint_index after adding state constraints : "
         << constraint_index;

  // 2. input constraints
  for (std::size_t i = 1; i < horizon_; ++i) {
    // u1
    g_l[constraint_index] = -0.6;
    g_u[constraint_index] = 0.6;

    // u2
    g_l[constraint_index + 1] = -1;
    g_u[constraint_index + 1] = 1;

    constraint_index += 2;
  }
  ADEBUG << "constraint_index after adding input constraints : "
         << constraint_index;

  // 3. sampling time constraints
  for (std::size_t i = 1; i < horizon_; ++i) {
    g_l[constraint_index] = -0.6;
    g_u[constraint_index] = 0.6;

    ++constraint_index;
  }
  ADEBUG << "constraint_index after adding sampling time constraints : "
         << constraint_index;

  return true;
}

bool WarmStartIPOPTInterface::eval_g(int n, const double* x, bool new_x, int m,
                                     double* g) {
  return true;
}

bool WarmStartIPOPTInterface::eval_jac_g(int n, const double* x, bool new_x,
                                         int m, int nele_jac, int* iRow,
                                         int* jCol, double* values) {
  return true;
}

bool WarmStartIPOPTInterface::eval_h(int n, const double* x, bool new_x,
                                     double obj_factor, int m,
                                     const double* lambda, bool new_lambda,
                                     int nele_hess, int* iRow, int* jCol,
                                     double* values) {
  return true;
}

bool WarmStartIPOPTInterface::get_starting_point(int n, bool init_x, double* x,
                                                 bool init_z, double* z_L,
                                                 double* z_U, int m,
                                                 bool init_lambda,
                                                 double* lambda) {
  CHECK(n == num_of_variables_) << "No. of variables wrong. n : " << n;
  CHECK(init_x == true) << "Warm start init_x setting failed";
  CHECK(init_z == false) << "Warm start init_z setting failed";
  CHECK(init_lambda == false) << "Warm start init_lambda setting failed";

  // 1. state variables linspace initialization

  std::vector<std::vector<double>> x_guess(4, std::vector<double>(horizon_));

  for (std::size_t i = 0; i < 4; ++i) {
    ::apollo::common::util::uniform_slice(x0_(i, 0), xf_(i, 0), horizon_,
                                          &x_guess[i]);
  }

  for (std::size_t i = 0; i <= horizon_; ++i) {
    for (std::size_t j = 0; j < 4; ++j) {
      x[i * 4 + j] = x_guess[j][i];
    }
  }

  // 2. input initialization
  for (std::size_t i = 0; i <= 2 * horizon_; ++i) {
    x[i] = 0.6;
  }

  // 3. sampling time constraints
  for (std::size_t i = 0; i <= horizon_; ++i) {
    x[i] = 0.5;
  }

  return true;
}

}  // namespace planning
}  // namespace apollo
<commit_msg>Planning : update warm start objective function<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

/*
 * warm_start_ipopt_interface.cc
 */

#include "modules/planning/planner/open_space/warm_start_ipopt_interface.h"

#include <math.h>
#include <utility>

#include "modules/common/log.h"
#include "modules/common/math/math_utils.h"
#include "modules/common/util/util.h"
#include "modules/planning/common/planning_gflags.h"

namespace apollo {
namespace planning {

constexpr std::size_t N = 80;

WarmStartIPOPTInterface::WarmStartIPOPTInterface(
    int num_of_variables, int num_of_constraints, std::size_t horizon, float ts,
    float wheelbase_length, Eigen::MatrixXd x0, Eigen::MatrixXd xf,
    Eigen::MatrixXd XYbounds)
    : num_of_variables_(num_of_variables),
      num_of_constraints_(num_of_constraints),
      horizon_(horizon),
      ts_(ts),
      wheelbase_length_(wheelbase_length),
      x0_(x0),
      xf_(xf),
      XYbounds_(XYbounds) {}

void WarmStartIPOPTInterface::get_optimization_results() const {}

bool WarmStartIPOPTInterface::get_nlp_info(int& n, int& m, int& nnz_jac_g,
                                           int& nnz_h_lag,
                                           IndexStyleEnum& index_style) {
  // number of variables
  n = num_of_variables_;

  // number of constraints

  m = num_of_constraints_;

  // number of nonzero hessian and lagrangian.

  // TODO(QiL) : Update nnz_jac_g;
  nnz_jac_g = 0;

  // TOdo(QiL) : Update nnz_h_lag;
  nnz_h_lag = 0;

  index_style = IndexStyleEnum::C_STYLE;
  return true;
}

bool WarmStartIPOPTInterface::get_bounds_info(int n, double* x_l, double* x_u,
                                              int m, double* g_l, double* g_u) {
  // here, the n and m we gave IPOPT in get_nlp_info are passed back to us.
  // If desired, we could assert to make sure they are what we think they are.
  CHECK(n == num_of_variables_) << "num_of_variables_ mismatch, n: " << n
                                << ", num_of_variables_: " << num_of_variables_;
  CHECK(m == num_of_constraints_)
      << "num_of_constraints_ mismatch, n: " << n
      << ", num_of_constraints_: " << num_of_constraints_;

  // Variables: includes u and sample time

  // 1. state variables
  // start point pose
  std::size_t variable_index = 0;
  for (std::size_t i = 0; i < 4; ++i) {
    x_l[i] = x0_(i, 0);
    x_u[i] = x0_(i, 0);
  }
  variable_index += 4;

  // During horizons
  for (std::size_t i = 1; i < horizon_ - 1; ++i) {
    // x
    x_l[variable_index] = XYbounds_(0, 0);
    x_u[variable_index] = XYbounds_(1, 0);

    // y
    x_l[variable_index + 1] = XYbounds_(2, 0);
    x_u[variable_index + 1] = XYbounds_(3, 0);

    // phi
    // TODO(QiL): Change this to configs
    x_l[variable_index + 2] = -7;
    x_u[variable_index + 2] = 7;

    // v
    // TODO(QiL) : Change this to configs
    x_l[variable_index + 3] = -1;
    x_u[variable_index + 3] = 2;

    variable_index += 4;
  }

  // end point pose
  for (std::size_t i = 0; i < 4; ++i) {
    x_l[variable_index + i] = xf_(i, 0);
    x_u[variable_index + i] = xf_(i, 0);
  }
  variable_index += 4;
  ADEBUG << "variable_index after adding state constraints : "
         << variable_index;

  // 2. input constraints
  for (std::size_t i = 1; i < horizon_; ++i) {
    // u1
    x_l[variable_index] = -0.6;
    x_u[variable_index] = 0.6;

    // u2
    x_l[variable_index + 1] = -1;
    x_u[variable_index + 1] = 1;

    variable_index += 2;
  }
  ADEBUG << "variable_index after adding input constraints : "
         << variable_index;

  // 3. sampling time constraints
  for (std::size_t i = 1; i < horizon_; ++i) {
    x_l[variable_index] = -0.6;
    x_u[variable_index] = 0.6;

    ++variable_index;
  }

  ADEBUG << "variable_index : " << variable_index;

  // Constraints

  // 1. state constraints
  // start point pose
  std::size_t constraint_index = 0;
  for (std::size_t i = 0; i < 4; ++i) {
    g_l[i] = x0_(i, 0);
    g_u[i] = x0_(i, 0);
  }
  constraint_index += 4;

  // During horizons
  for (std::size_t i = 1; i < horizon_ - 1; ++i) {
    // x
    g_l[constraint_index] = XYbounds_(0, 0);
    g_u[constraint_index] = XYbounds_(1, 0);

    // y
    g_l[constraint_index + 1] = XYbounds_(2, 0);
    g_u[constraint_index + 1] = XYbounds_(3, 0);

    // phi
    // TODO(QiL): Change this to configs
    g_l[constraint_index + 2] = -7;
    g_u[constraint_index + 2] = 7;

    // v
    // TODO(QiL) : Change this to configs
    g_l[constraint_index + 3] = -1;
    g_u[constraint_index + 3] = 2;

    constraint_index += 4;
  }

  // end point pose
  for (std::size_t i = 0; i < 4; ++i) {
    g_l[constraint_index + i] = xf_(i, 0);
    g_u[constraint_index + i] = xf_(i, 0);
  }
  constraint_index += 4;
  ADEBUG << "constraint_index after adding state constraints : "
         << constraint_index;

  // 2. input constraints
  for (std::size_t i = 1; i < horizon_; ++i) {
    // u1
    g_l[constraint_index] = -0.6;
    g_u[constraint_index] = 0.6;

    // u2
    g_l[constraint_index + 1] = -1;
    g_u[constraint_index + 1] = 1;

    constraint_index += 2;
  }
  ADEBUG << "constraint_index after adding input constraints : "
         << constraint_index;

  // 3. sampling time constraints
  for (std::size_t i = 1; i < horizon_; ++i) {
    g_l[constraint_index] = -0.6;
    g_u[constraint_index] = 0.6;

    ++constraint_index;
  }
  ADEBUG << "constraint_index after adding sampling time constraints : "
         << constraint_index;

  return true;
}

bool WarmStartIPOPTInterface::eval_g(int n, const double* x, bool new_x, int m,
                                     double* g) {
  return true;
}

bool WarmStartIPOPTInterface::eval_jac_g(int n, const double* x, bool new_x,
                                         int m, int nele_jac, int* iRow,
                                         int* jCol, double* values) {
  return true;
}

bool WarmStartIPOPTInterface::eval_h(int n, const double* x, bool new_x,
                                     double obj_factor, int m,
                                     const double* lambda, bool new_lambda,
                                     int nele_hess, int* iRow, int* jCol,
                                     double* values) {
  return true;
}

bool WarmStartIPOPTInterface::get_starting_point(int n, bool init_x, double* x,
                                                 bool init_z, double* z_L,
                                                 double* z_U, int m,
                                                 bool init_lambda,
                                                 double* lambda) {
  CHECK(n == num_of_variables_) << "No. of variables wrong. n : " << n;
  CHECK(init_x == true) << "Warm start init_x setting failed";
  CHECK(init_z == false) << "Warm start init_z setting failed";
  CHECK(init_lambda == false) << "Warm start init_lambda setting failed";

  // 1. state variables linspace initialization

  std::vector<std::vector<double>> x_guess(4, std::vector<double>(horizon_));

  for (std::size_t i = 0; i < 4; ++i) {
    ::apollo::common::util::uniform_slice(x0_(i, 0), xf_(i, 0), horizon_,
                                          &x_guess[i]);
  }

  for (std::size_t i = 0; i <= horizon_; ++i) {
    for (std::size_t j = 0; j < 4; ++j) {
      x[i * 4 + j] = x_guess[j][i];
    }
  }

  // 2. input initialization
  for (std::size_t i = 0; i <= 2 * horizon_; ++i) {
    x[i] = 0.6;
  }

  // 3. sampling time constraints
  for (std::size_t i = 0; i <= horizon_; ++i) {
    x[i] = 0.5;
  }

  return true;
}

bool WarmStartIPOPTInterface::eval_f(int n, const double* x, bool new_x,
                                     double& obj_value) {
  // first (horizon_ + 1) * 4 is state, then next horizon_ * 2 is control input,
  // then last horizon_ + 1 is sampling time
  std::size_t start_index = (horizon_ + 1) * 4;
  std::size_t time_start_index = start_index + horizon_ * 2;
  for (std::size_t i = 0; i < horizon_; ++i) {
    obj_value += 0.1 * x[start_index + i] * x[start_index + i] +
                 x[start_index + i] * x[start_index + i + 1] +
                 0.5 * x[time_start_index + i] +
                 x[time_start_index + i] * x[time_start_index + i];
  }
  obj_value += 0.5 * x[time_start_index + horizon_] +
               x[time_start_index + horizon_] * x[time_start_index + horizon_];
  return true;
}

}  // namespace planning
}  // namespace apollo
<|endoftext|>


<commit_before>/**
 * Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin-explorer.
 *
 * libbitcoin-explorer is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <bitcoin/explorer/primitives/ec_public.hpp>

#include <iostream>
#include <sstream>
#include <string>
#include <boost/program_options.hpp>
#include <bitcoin/bitcoin.hpp>
#include <bitcoin/explorer/define.hpp>
#include <bitcoin/explorer/primitives/base16.hpp>

using namespace po;

namespace libbitcoin {
namespace explorer {
namespace primitives {

// ec_point format is currently private to bx.
static bool decode_point(ec_point& point, const std::string& encoded)
{
    data_chunk result;
    if (!decode_base16(result, encoded) || result.size() != point.size())
        return false;

    if (verify_public_key_fast(ec_point(result)))
        return false;

    point.assign(result.begin(), result.end());
    return true;
}

static std::string encode_point(const ec_point& point)
{
    return encode_base16(point);
}

ec_public::ec_public()
    : value_()
{
}

ec_public::ec_public(const std::string& hexcode)
{
    std::stringstream(hexcode) >> *this;
}

ec_public::ec_public(const bc::ec_point& value)
    : value_(value)
{
}

ec_public::ec_public(const ec_public& other)
    : ec_public(other.value_)
{
}

ec_public::ec_public(const hd_private_key& value)
    : ec_public(value.public_key())
{
}

ec_public::ec_public(const hd_public_key& value)
    : ec_public(value.public_key())
{
}

ec_point& ec_public::data()
{
    return value_;
}

ec_public::operator const ec_point&() const
{
    return value_;
}

ec_public::operator data_slice() const
{
    return value_;
}

std::istream& operator>>(std::istream& input, ec_public& argument)
{
    std::string hexcode;
    input >> hexcode;

    if (!decode_point(argument.value_, hexcode))
        BOOST_THROW_EXCEPTION(invalid_option_value(hexcode));

    return input;
}

std::ostream& operator<<(std::ostream& output, const ec_public& argument)
{
    output << encode_point(argument.value_);
    return output;
}

} // namespace explorer
} // namespace primitives
} // namespace libbitcoin
<commit_msg>Restore ec_public functionality<commit_after>/**
 * Copyright (c) 2011-2014 libbitcoin developers (see AUTHORS)
 *
 * This file is part of libbitcoin-explorer.
 *
 * libbitcoin-explorer is free software: you can redistribute it and/or
 * modify it under the terms of the GNU Affero General Public License with
 * additional permissions to the one published by the Free Software
 * Foundation, either version 3 of the License, or (at your option)
 * any later version. For more information see LICENSE.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
#include <bitcoin/explorer/primitives/ec_public.hpp>

#include <iostream>
#include <sstream>
#include <string>
#include <boost/program_options.hpp>
#include <bitcoin/bitcoin.hpp>
#include <bitcoin/explorer/define.hpp>
#include <bitcoin/explorer/primitives/base16.hpp>

using namespace po;

namespace libbitcoin {
namespace explorer {
namespace primitives {

// ec_point format is currently private to bx.
static bool decode_point(ec_point& point, const std::string& encoded)
{
    data_chunk result;
    if (!decode_base16(result, encoded))
        return false;

    if (!verify_public_key_fast(ec_point(result)))
        return false;

    point.assign(result.begin(), result.end());
    return true;
}

static std::string encode_point(const ec_point& point)
{
    return encode_base16(point);
}

ec_public::ec_public()
    : value_()
{
}

ec_public::ec_public(const std::string& hexcode)
{
    std::stringstream(hexcode) >> *this;
}

ec_public::ec_public(const bc::ec_point& value)
    : value_(value)
{
}

ec_public::ec_public(const ec_public& other)
    : ec_public(other.value_)
{
}

ec_public::ec_public(const hd_private_key& value)
    : ec_public(value.public_key())
{
}

ec_public::ec_public(const hd_public_key& value)
    : ec_public(value.public_key())
{
}

ec_point& ec_public::data()
{
    return value_;
}

ec_public::operator const ec_point&() const
{
    return value_;
}

ec_public::operator data_slice() const
{
    return value_;
}

std::istream& operator>>(std::istream& input, ec_public& argument)
{
    std::string hexcode;
    input >> hexcode;

    if (!decode_point(argument.value_, hexcode))
        BOOST_THROW_EXCEPTION(invalid_option_value(hexcode));

    return input;
}

std::ostream& operator<<(std::ostream& output, const ec_public& argument)
{
    output << encode_point(argument.value_);
    return output;
}

} // namespace explorer
} // namespace primitives
} // namespace libbitcoin
<|endoftext|>


<commit_before>#include "FilesDecisionModel.h"

FilesDecisionModel::FilesDecisionModel(TreeRootItem* root) :
	m_rootItem(root)
{

}

FilesDecisionModel::~FilesDecisionModel()
{
	if (m_rootItem) delete m_rootItem;
}

void FilesDecisionModel::setFilesInfo(TreeRootItem* rootItem)
{
	m_rootItem = rootItem;
}

QModelIndex FilesDecisionModel::index(int row, int column, const QModelIndex& parent) const
{
	if (!hasIndex(row, column, parent))
	{
		return QModelIndex();
	}

	if (!parent.isValid())
	{
		if (row < m_rootItem->childCount())
		{
			return createIndex(row, column, nullptr);
		}
		else
		{
			return QModelIndex();
		}
	}
	else
	{
		if (parent.internalPointer() == nullptr)
		{
			TreeInnerItem *childItem = m_rootItem->child(parent.row());

			if (childItem)
			{
				return createIndex(row, column, childItem);
			}
			else
			{
				return QModelIndex();
			}
		}
	}

	return QModelIndex();
}

QModelIndex FilesDecisionModel::parent(const QModelIndex& child) const
{
	if (!child.isValid())
	{
		return QModelIndex();
	}

	if (child.internalPointer() == nullptr)
	{
		return QModelIndex();
	}

	TreeInnerItem *childItem = static_cast<TreeInnerItem*>(child.internalPointer());
	return createIndex(childItem->row(), 0, nullptr);
}

int FilesDecisionModel::rowCount(const QModelIndex& parent) const
{
	if (parent.column() > 0)
	{
		return 0;
	}

	if (!parent.isValid())
	{
		return m_rootItem->dataCount();
	}
	else
	{
		if (parent.internalPointer() == nullptr)
		{
			if (parent.row() < m_rootItem->childItems().size())
			{
				int count = m_rootItem->child(parent.row())->dataCount();
				return count;
			}
			else
			{
				return 0;
			}
		}
		else
		{
			return 0;
		}
	}
}

int FilesDecisionModel::columnCount(const QModelIndex& parent) const
{
	Q_UNUSED(parent);
	return 1;
}

QVariant FilesDecisionModel::data(const QModelIndex& index, int role) const
{
	if (!index.isValid())
	{
		return QVariant();
	}

	if (role != Qt::DisplayRole)
	{
		return QVariant();
	}

	if (index.internalPointer() == nullptr)
	{
		return m_rootItem->data(index.row());
	}
	else
	{
		TreeInnerItem *item = static_cast<TreeInnerItem*>(index.internalPointer());
		return item->data(index.row());
	}
}

Qt::ItemFlags FilesDecisionModel::flags(const QModelIndex& index) const
{
	Q_UNUSED(index);
	return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
<commit_msg>[*] minor model changes<commit_after>#include "FilesDecisionModel.h"

FilesDecisionModel::FilesDecisionModel(TreeRootItem* root) :
	m_rootItem(root)
{

}

FilesDecisionModel::~FilesDecisionModel()
{
	if (m_rootItem) delete m_rootItem;
}

void FilesDecisionModel::setFilesInfo(TreeRootItem* rootItem)
{
	m_rootItem = rootItem;
}

QModelIndex FilesDecisionModel::index(int row, int column, const QModelIndex& parent) const
{
	if (!hasIndex(row, column, parent))
	{
		return QModelIndex();
	}

	if (!parent.isValid())
	{
		return createIndex(row, column, nullptr);
	}
	else
	{
		if (parent.internalPointer() == nullptr)
		{
			TreeInnerItem *childItem = m_rootItem->child(parent.row());

			if (childItem)
			{
				return createIndex(row, column, childItem);
			}
		}
	}

	return QModelIndex();
}

QModelIndex FilesDecisionModel::parent(const QModelIndex& child) const
{
	if (!child.isValid())
	{
		return QModelIndex();
	}

	if (child.internalPointer() == nullptr)
	{
		return QModelIndex();
	}

	TreeInnerItem *childItem = static_cast<TreeInnerItem*>(child.internalPointer());
	return createIndex(childItem->row(), 0, nullptr);
}

int FilesDecisionModel::rowCount(const QModelIndex& parent) const
{
	if (parent.column() > 0)
	{
		return 0;
	}

	if (!parent.isValid())
	{
		return m_rootItem->dataCount();
	}
	else
	{
		if (parent.internalPointer() == nullptr)
		{
			if (parent.row() < m_rootItem->childItems().size())
			{
				return m_rootItem->child(parent.row())->dataCount();
			}
		}
	}

	return 0;
}

int FilesDecisionModel::columnCount(const QModelIndex& parent) const
{
	Q_UNUSED(parent);
	return 1;
}

QVariant FilesDecisionModel::data(const QModelIndex& index, int role) const
{
	if (!index.isValid())
	{
		return QVariant();
	}

	if (role != Qt::DisplayRole)
	{
		return QVariant();
	}

	if (index.internalPointer() == nullptr)
	{
		return m_rootItem->data(index.row());
	}
	else
	{
		TreeInnerItem *item = static_cast<TreeInnerItem*>(index.internalPointer());
		return item->data(index.row());
	}
}

Qt::ItemFlags FilesDecisionModel::flags(const QModelIndex& index) const
{
	Q_UNUSED(index);
	return Qt::ItemIsEnabled | Qt::ItemIsSelectable;
}
<|endoftext|>