<commit_before>#pragma once
#ifndef SIMRANK_HPP
#define SIMRANK_HPP

#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cmath>
#include <algorithm>
#include <iterator>

template<typename T, typename I>
class Iterator_Wrapper {
private:
	const T &collection_;
public:
	inline Iterator_Wrapper(const T &collection) : collection_(collection) {}
	inline const I begin(void) const { return I(collection_.begin()); }
	inline const I end(void) const { return I(collection_.end()); }
	inline Iterator_Wrapper &operator=(const Iterator_Wrapper &) { return *this; }
};

template<typename T>
class Key_Iterator {
private:
	typename T::const_iterator pos_;
public:
	inline Key_Iterator(typename T::const_iterator pos) : pos_(pos) {}
	inline typename T::key_type operator*() { return pos_->first; }
	inline bool operator!=(const Key_Iterator &other) const { return pos_ != other.pos_; }
	inline const Key_Iterator &operator++() { ++pos_; return *this; }
};

template<typename T>
using Key_Iterator_Wrapper = Iterator_Wrapper<T, Key_Iterator<T>>;

template<typename T>
using Const_Iterator_Wrapper = Iterator_Wrapper<T, typename T::const_iterator>;

template<typename K, typename V>
using umap = std::unordered_map<K, V>;

template<typename T>
using uset = std::unordered_set<T>;

template<typename node_t, typename float_t>
class SimRank {
public:
	SimRank(size_t K = 6, float_t C = 0.6, float_t D = 0.05);
	~SimRank();

	// Reserve space in memory for at least n nodes
	void reserve(size_t n);
	// Add an edge to the graph
	void add_edge(node_t head, node_t tail, float_t weight = 1);
	// Calculate SimRank scores after adding all the edges
	void calculate_simrank(void);
	// Return the similarity score between nodes a and b
	float_t similarity(node_t a, node_t b) const;

	// Return the number of iterations
	inline size_t K(void) const { return K_; }
	// Return the decay factor
	inline float_t C(void) const { return C_; }
	// Return the delta for threshold sieving
	inline float_t D(void) const { return D_; }

	// Return the number of nodes in the graph
	inline size_t num_nodes(void) const { return node_properties_.size(); }
	// Return the number of nodes with out-degree > 0
	inline size_t num_heads(void) const { return edge_weights_.size(); }
	// Return the number of nodes with in-degree > 0
	inline size_t num_tails(void) const { return in_neighbors_.size(); }

	// Edge data accessible via edges()
	struct edge_t {
		node_t head, tail;
		float_t weight;
		inline edge_t(node_t head, node_t tail, float_t weight) : head(head), tail(tail), weight(weight) {}
	};

	struct node_prop_t;
	// Iterate over all nodes, e.g. "for (node_t x : simrank.nodes()) { ... }"
	inline const Key_Iterator_Wrapper<umap<node_t, node_prop_t>> nodes(void) const {
		return Key_Iterator_Wrapper<umap<node_t, node_prop_t>>(node_properties_);
	}
	class edge_iterable;
	// Iterate over all edges, e.g. "for (SimRank::edge_t e : simrank.edges()) { ... }"
	inline const edge_iterable edges(void) const { return edge_iterable(edge_weights_); }

	// Return the out-degree of node x (the sum of the outgoing edges' weights)
	inline float_t out_degree(node_t x) { return node_properties_[x].out_degree; }
	// Return the in-degree of node x (the sum of the incoming edges' weights)
	inline float_t in_degree(node_t x) { return node_properties_[x].in_degree; }

	// Iterate over the out-neighbors of node x, e.g. "for (node_t y : simrank.out_neighbors(x)) { ... }"
	inline const Key_Iterator_Wrapper<umap<node_t, float_t>> out_neighbors(node_t x) {
		return Key_Iterator_Wrapper<umap<node_t, float_t>>(edge_weights_[x]);
	}
	// Iterate over the in-neighbors of node x, e.g. "for (node_t y : simrank.in_neighbors(x)) { ... }"
	inline const Const_Iterator_Wrapper<uset<node_t>> in_neighbors(node_t x) {
		return Const_Iterator_Wrapper<uset<node_t>>(in_neighbors_[x]);
	}

	// Return the weight of the edge from a to b (normalized after calling calculate_simrank())
	inline float_t edge_weight(node_t a, node_t b) { return edge_weights_[a][b]; }

private:
	struct node_prop_t {
		umap<node_t, float_t> simrank;
		float_t partial_sum;
		float_t in_degree, out_degree;
		inline node_prop_t(void) : simrank(), partial_sum(), in_degree(), out_degree() {}
	};

	size_t K_;
	float_t C_;
	float_t D_;

	umap<node_t, node_prop_t>           node_properties_; // {node1 -> <{node2 -> SimRank}, etc>} (node1 <= node2)
	umap<node_t, uset<node_t>>          in_neighbors_;    // {node -> {in-neighbors}}
	umap<node_t, umap<node_t, float_t>> edge_weights_;    // {head -> {tail -> weight}}

	std::vector<node_t> temp_nodes_;      // temporary node storage for calculating essential paired nodes
	std::vector<node_t> essential_nodes_; // essential paired nodes (reused in each update iteration)

	float_t *delta_; // deltas for threshold sieving

	void normalize_edges(void);
	void update_simrank_scores(node_t a, int k);

public:
	class edge_iterator {
		typedef typename umap<node_t, umap<node_t, float_t>>::const_iterator pos_iterator;
		typedef typename umap<node_t, float_t>::const_iterator subpos_iterator;
	private:
		pos_iterator pos_, pos_end_;
		subpos_iterator subpos_, subpos_end_;
	public:
		inline edge_iterator(pos_iterator pos, subpos_iterator subpos, pos_iterator pos_end, subpos_iterator subpos_end) :
			pos_(pos), subpos_(subpos), pos_end_(pos_end), subpos_end_(subpos_end) {}
		inline edge_t operator*() { return edge_t(pos_->first, subpos_->first, subpos_->second); }
		inline bool operator!=(const edge_iterator &other) const { return pos_ != other.pos_ || subpos_ != other.subpos_; }
		inline const edge_iterator &operator++(void) {
			++subpos_;
			if (subpos_ == pos_->second.end()) {
				++pos_;
				subpos_ = pos_ == pos_end_ ? subpos_end_ : pos_->second.begin();
			}
			return *this;
		}
	};

	class edge_iterable {
	private:
		const umap<node_t, umap<node_t, float_t>> &edges_;
	public:
		inline edge_iterable(const umap<node_t, umap<node_t, float_t>> &edges) : edges_(edges) {}
		inline const edge_iterator begin(void) const {
			return edge_iterator(edges_.begin(), edges_.begin()->second.begin(), edges_.end(), edges_.begin()->second.end());
		}
		inline const edge_iterator end(void) const {
			return edge_iterator(edges_.end(), edges_.begin()->second.end(), edges_.end(), edges_.begin()->second.end());
		}
		inline edge_iterable &operator=(const edge_iterable &) { return *this; }
	};
};

template<typename node_t, typename float_t>
SimRank<node_t, float_t>::SimRank(size_t K, float_t C, float_t D) : K_(K), C_(C), D_(D),
	node_properties_(), in_neighbors_(), edge_weights_(), temp_nodes_(), essential_nodes_() {
	delta_ = new float_t[K];
}

template<typename node_t, typename float_t>
SimRank<node_t, float_t>::~SimRank() {
	delete [] delta_;
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::reserve(size_t n) {
	node_properties_.reserve(n);
	edge_weights_.reserve(n);
	in_neighbors_.reserve(n);
	temp_nodes_.reserve(n);
	essential_nodes_.reserve(n);
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::add_edge(node_t head, node_t tail, float_t weight) {
	node_properties_[head].out_degree += weight;
	node_properties_[tail].in_degree += weight;
	in_neighbors_[tail].insert(head);
	edge_weights_[head][tail] += weight;
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::calculate_simrank() {
	normalize_edges();
	// Calculate deltas for threshold sieving
	for (int m = 0; m < K_; m++) {
		delta_[m] = (float_t)(D_ / (K_ * pow(C_, K_ - m + 1)));
	}
	// Initialize similarity scores
	for (auto const &a_aps_p : node_properties_) {
		node_t a = a_aps_p.first;
		node_properties_[a].simrank.clear();
	}
	// Main loop: update scores for K iterations
	for (int k = 0; k < K_; k++) {
		for (auto const &a_aps_p : node_properties_) {
			node_t a = a_aps_p.first;
			float_t a_od = a_aps_p.second.out_degree;
			if (a_od == 0 && k < K_ - 1) { continue; }
			update_simrank_scores(a, k);
		}
	}
}

template<typename node_t, typename float_t>
float_t SimRank<node_t, float_t>::similarity(node_t a, node_t b) const {
	// similarity(a, a) == 1
	if (a == b) { return 1; }
	// similarity(a, b) == similarity(b, a), so standardize on a < b
	if (a > b) { std::swap(a, b); }
	auto a_props = node_properties_.at(a);
	auto a_b_simrank = a_props.simrank.find(b);
	if (a_b_simrank == a_props.simrank.end()) { return 0; }
	return a_b_simrank->second;
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::normalize_edges() {
	// Divide each edge from a to b by the in-degree of b
	for (auto &a_bws_p : edge_weights_) {
		node_t a = a_bws_p.first;
		auto &bws = a_bws_p.second;
		for (auto &b_w_p : bws) {
			node_t b = b_w_p.first;
			float_t w = b_w_p.second;
			edge_weights_[a][b] = w / node_properties_[b].in_degree;
		}
	}
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::update_simrank_scores(node_t a, int k) {
	// Calculate partial sums for node a's in-neighbors
	for (auto &u_ups_p : node_properties_) {
		node_t u = u_ups_p.first;
		float_t partial_sum_u = 0;
		for (node_t i : in_neighbors_[a]) {
			partial_sum_u += similarity(i, u) * edge_weights_[i][a];
		}
		node_properties_[u].partial_sum = partial_sum_u;
	}
	// Calculate essential paired nodes for node a
	essential_nodes_.clear();
	// Construct set of temporary nodes
	temp_nodes_.clear();
	for (auto const &v_vps_p : node_properties_) {
		node_t v = v_vps_p.first;
		for (node_t u : in_neighbors_[a]) {
			if (similarity(u, v) > 0) {
				temp_nodes_.push_back(v);
				break;
			}
		}
	}
	// Construct set of essential paired nodes
	for (auto const &b_bps_p : node_properties_) {
		node_t b = b_bps_p.first;
		for (node_t v : temp_nodes_) {
			if (in_neighbors_[b].find(v) != in_neighbors_[b].end()) {
				essential_nodes_.push_back(b);
				break;
			}
		}
	}
	// Main loop: account for node b's in-neighbors
	for (node_t b : essential_nodes_) {
		float_t score_a_b = 0;
		for (node_t j : in_neighbors_[b]) {
			score_a_b += node_properties_[j].partial_sum * edge_weights_[j][b];
		}
		score_a_b *= C_;
		if (score_a_b > delta_[k] || similarity(a, b) > 0) {
			node_properties_[a].simrank[b] = score_a_b;
		}
	}
}

#endif
<commit_msg>Make forward declaration of node_prop_t private.<commit_after>#pragma once
#ifndef SIMRANK_HPP
#define SIMRANK_HPP

#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <cmath>
#include <algorithm>
#include <iterator>

template<typename T, typename I>
class Iterator_Wrapper {
private:
	const T &collection_;
public:
	inline Iterator_Wrapper(const T &collection) : collection_(collection) {}
	inline const I begin(void) const { return I(collection_.begin()); }
	inline const I end(void) const { return I(collection_.end()); }
	inline Iterator_Wrapper &operator=(const Iterator_Wrapper &) { return *this; }
};

template<typename T>
class Key_Iterator {
private:
	typename T::const_iterator pos_;
public:
	inline Key_Iterator(typename T::const_iterator pos) : pos_(pos) {}
	inline typename T::key_type operator*() { return pos_->first; }
	inline bool operator!=(const Key_Iterator &other) const { return pos_ != other.pos_; }
	inline const Key_Iterator &operator++() { ++pos_; return *this; }
};

template<typename T>
using Key_Iterator_Wrapper = Iterator_Wrapper<T, Key_Iterator<T>>;

template<typename T>
using Const_Iterator_Wrapper = Iterator_Wrapper<T, typename T::const_iterator>;

template<typename K, typename V>
using umap = std::unordered_map<K, V>;

template<typename T>
using uset = std::unordered_set<T>;

template<typename node_t, typename float_t>
class SimRank {
public:
	SimRank(size_t K = 6, float_t C = 0.6, float_t D = 0.05);
	~SimRank();

	// Reserve space in memory for at least n nodes
	void reserve(size_t n);
	// Add an edge to the graph
	void add_edge(node_t head, node_t tail, float_t weight = 1);
	// Calculate SimRank scores after adding all the edges
	void calculate_simrank(void);
	// Return the similarity score between nodes a and b
	float_t similarity(node_t a, node_t b) const;

	// Return the number of iterations
	inline size_t K(void) const { return K_; }
	// Return the decay factor
	inline float_t C(void) const { return C_; }
	// Return the delta for threshold sieving
	inline float_t D(void) const { return D_; }

	// Return the number of nodes in the graph
	inline size_t num_nodes(void) const { return node_properties_.size(); }
	// Return the number of nodes with out-degree > 0
	inline size_t num_heads(void) const { return edge_weights_.size(); }
	// Return the number of nodes with in-degree > 0
	inline size_t num_tails(void) const { return in_neighbors_.size(); }

	// Edge data accessible via edges()
	struct edge_t {
		node_t head, tail;
		float_t weight;
		inline edge_t(node_t head, node_t tail, float_t weight) : head(head), tail(tail), weight(weight) {}
	};

private:
	struct node_prop_t;
public:
	// Iterate over all nodes, e.g. "for (node_t x : simrank.nodes()) { ... }"
	inline const Key_Iterator_Wrapper<umap<node_t, node_prop_t>> nodes(void) const {
		return Key_Iterator_Wrapper<umap<node_t, node_prop_t>>(node_properties_);
	}
	class edge_iterable;
	// Iterate over all edges, e.g. "for (SimRank::edge_t e : simrank.edges()) { ... }"
	inline const edge_iterable edges(void) const { return edge_iterable(edge_weights_); }

	// Return the out-degree of node x (the sum of the outgoing edges' weights)
	inline float_t out_degree(node_t x) { return node_properties_[x].out_degree; }
	// Return the in-degree of node x (the sum of the incoming edges' weights)
	inline float_t in_degree(node_t x) { return node_properties_[x].in_degree; }

	// Iterate over the out-neighbors of node x, e.g. "for (node_t y : simrank.out_neighbors(x)) { ... }"
	inline const Key_Iterator_Wrapper<umap<node_t, float_t>> out_neighbors(node_t x) {
		return Key_Iterator_Wrapper<umap<node_t, float_t>>(edge_weights_[x]);
	}
	// Iterate over the in-neighbors of node x, e.g. "for (node_t y : simrank.in_neighbors(x)) { ... }"
	inline const Const_Iterator_Wrapper<uset<node_t>> in_neighbors(node_t x) {
		return Const_Iterator_Wrapper<uset<node_t>>(in_neighbors_[x]);
	}

	// Return the weight of the edge from a to b (normalized after calling calculate_simrank())
	inline float_t edge_weight(node_t a, node_t b) { return edge_weights_[a][b]; }

private:
	struct node_prop_t {
		umap<node_t, float_t> simrank;
		float_t partial_sum;
		float_t in_degree, out_degree;
		inline node_prop_t(void) : simrank(), partial_sum(), in_degree(), out_degree() {}
	};

	size_t K_;
	float_t C_;
	float_t D_;

	umap<node_t, node_prop_t>           node_properties_; // {node1 -> <{node2 -> SimRank}, etc>} (node1 <= node2)
	umap<node_t, uset<node_t>>          in_neighbors_;    // {node -> {in-neighbors}}
	umap<node_t, umap<node_t, float_t>> edge_weights_;    // {head -> {tail -> weight}}

	std::vector<node_t> temp_nodes_;      // temporary node storage for calculating essential paired nodes
	std::vector<node_t> essential_nodes_; // essential paired nodes (reused in each update iteration)

	float_t *delta_; // deltas for threshold sieving

	void normalize_edges(void);
	void update_simrank_scores(node_t a, int k);

public:
	class edge_iterator {
		typedef typename umap<node_t, umap<node_t, float_t>>::const_iterator pos_iterator;
		typedef typename umap<node_t, float_t>::const_iterator subpos_iterator;
	private:
		pos_iterator pos_, pos_end_;
		subpos_iterator subpos_, subpos_end_;
	public:
		inline edge_iterator(pos_iterator pos, subpos_iterator subpos, pos_iterator pos_end, subpos_iterator subpos_end) :
			pos_(pos), subpos_(subpos), pos_end_(pos_end), subpos_end_(subpos_end) {}
		inline edge_t operator*() { return edge_t(pos_->first, subpos_->first, subpos_->second); }
		inline bool operator!=(const edge_iterator &other) const { return pos_ != other.pos_ || subpos_ != other.subpos_; }
		inline const edge_iterator &operator++(void) {
			++subpos_;
			if (subpos_ == pos_->second.end()) {
				++pos_;
				subpos_ = pos_ == pos_end_ ? subpos_end_ : pos_->second.begin();
			}
			return *this;
		}
	};

	class edge_iterable {
	private:
		const umap<node_t, umap<node_t, float_t>> &edges_;
	public:
		inline edge_iterable(const umap<node_t, umap<node_t, float_t>> &edges) : edges_(edges) {}
		inline const edge_iterator begin(void) const {
			return edge_iterator(edges_.begin(), edges_.begin()->second.begin(), edges_.end(), edges_.begin()->second.end());
		}
		inline const edge_iterator end(void) const {
			return edge_iterator(edges_.end(), edges_.begin()->second.end(), edges_.end(), edges_.begin()->second.end());
		}
		inline edge_iterable &operator=(const edge_iterable &) { return *this; }
	};
};

template<typename node_t, typename float_t>
SimRank<node_t, float_t>::SimRank(size_t K, float_t C, float_t D) : K_(K), C_(C), D_(D),
	node_properties_(), in_neighbors_(), edge_weights_(), temp_nodes_(), essential_nodes_() {
	delta_ = new float_t[K];
}

template<typename node_t, typename float_t>
SimRank<node_t, float_t>::~SimRank() {
	delete [] delta_;
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::reserve(size_t n) {
	node_properties_.reserve(n);
	edge_weights_.reserve(n);
	in_neighbors_.reserve(n);
	temp_nodes_.reserve(n);
	essential_nodes_.reserve(n);
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::add_edge(node_t head, node_t tail, float_t weight) {
	node_properties_[head].out_degree += weight;
	node_properties_[tail].in_degree += weight;
	in_neighbors_[tail].insert(head);
	edge_weights_[head][tail] += weight;
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::calculate_simrank() {
	normalize_edges();
	// Calculate deltas for threshold sieving
	for (int m = 0; m < K_; m++) {
		delta_[m] = (float_t)(D_ / (K_ * pow(C_, K_ - m + 1)));
	}
	// Initialize similarity scores
	for (auto const &a_aps_p : node_properties_) {
		node_t a = a_aps_p.first;
		node_properties_[a].simrank.clear();
	}
	// Main loop: update scores for K iterations
	for (int k = 0; k < K_; k++) {
		for (auto const &a_aps_p : node_properties_) {
			node_t a = a_aps_p.first;
			float_t a_od = a_aps_p.second.out_degree;
			if (a_od == 0 && k < K_ - 1) { continue; }
			update_simrank_scores(a, k);
		}
	}
}

template<typename node_t, typename float_t>
float_t SimRank<node_t, float_t>::similarity(node_t a, node_t b) const {
	// similarity(a, a) == 1
	if (a == b) { return 1; }
	// similarity(a, b) == similarity(b, a), so standardize on a < b
	if (a > b) { std::swap(a, b); }
	auto a_props = node_properties_.at(a);
	auto a_b_simrank = a_props.simrank.find(b);
	if (a_b_simrank == a_props.simrank.end()) { return 0; }
	return a_b_simrank->second;
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::normalize_edges() {
	// Divide each edge from a to b by the in-degree of b
	for (auto &a_bws_p : edge_weights_) {
		node_t a = a_bws_p.first;
		auto &bws = a_bws_p.second;
		for (auto &b_w_p : bws) {
			node_t b = b_w_p.first;
			float_t w = b_w_p.second;
			edge_weights_[a][b] = w / node_properties_[b].in_degree;
		}
	}
}

template<typename node_t, typename float_t>
void SimRank<node_t, float_t>::update_simrank_scores(node_t a, int k) {
	// Calculate partial sums for node a's in-neighbors
	for (auto &u_ups_p : node_properties_) {
		node_t u = u_ups_p.first;
		float_t partial_sum_u = 0;
		for (node_t i : in_neighbors_[a]) {
			partial_sum_u += similarity(i, u) * edge_weights_[i][a];
		}
		node_properties_[u].partial_sum = partial_sum_u;
	}
	// Calculate essential paired nodes for node a
	essential_nodes_.clear();
	// Construct set of temporary nodes
	temp_nodes_.clear();
	for (auto const &v_vps_p : node_properties_) {
		node_t v = v_vps_p.first;
		for (node_t u : in_neighbors_[a]) {
			if (similarity(u, v) > 0) {
				temp_nodes_.push_back(v);
				break;
			}
		}
	}
	// Construct set of essential paired nodes
	for (auto const &b_bps_p : node_properties_) {
		node_t b = b_bps_p.first;
		for (node_t v : temp_nodes_) {
			if (in_neighbors_[b].find(v) != in_neighbors_[b].end()) {
				essential_nodes_.push_back(b);
				break;
			}
		}
	}
	// Main loop: account for node b's in-neighbors
	for (node_t b : essential_nodes_) {
		float_t score_a_b = 0;
		for (node_t j : in_neighbors_[b]) {
			score_a_b += node_properties_[j].partial_sum * edge_weights_[j][b];
		}
		score_a_b *= C_;
		if (score_a_b > delta_[k] || similarity(a, b) > 0) {
			node_properties_[a].simrank[b] = score_a_b;
		}
	}
}

#endif
<|endoftext|>


<commit_before>#include "lexer.h"
#include "parser.h"
#include "binary.h"
#include "types.h"
#include <iostream>
#include <fstream>
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Support/raw_os_ostream.h"
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/JIT.h>
#include <llvm/Analysis/Passes.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Transforms/Scalar.h>

static std::string ErrStr;
llvm::FunctionPassManager* fpm;
static llvm::ExecutionEngine* theExecutionEngine;
llvm::Module* theModule = new llvm::Module("TheModule", llvm::getGlobalContext());
Types types;

void DumpModule(llvm::Module* module)
{
    module->dump();
}

llvm::Module* CodeGen(ExprAST* ast)
{
    for(auto a = ast; a; a = a->Next())
    {
	llvm::Value* v = a->CodeGen();
	if (!v)
	{
	    std::cerr << "Sorry, something went wrong here..." << std::endl;
	    a->Dump(std::cerr);
	    return 0;
	}
    }
    return theModule;
}

void OptimizerInit()
{
    fpm = new llvm::FunctionPassManager(theModule);

    llvm::InitializeNativeTarget();

    theExecutionEngine = llvm::EngineBuilder(theModule).setErrorStr(&ErrStr).create();
    if (!theExecutionEngine) {
	std::cerr << "Could not create ExecutionEngine:" << ErrStr << std::endl;
	exit(1);
    }

    // Set up the optimizer pipeline.  Start with registering info about how the
    // target lays out data structures.
    fpm->add(new llvm::DataLayout(*theExecutionEngine->getDataLayout()));
    // Promote allocas to registers.
    fpm->add(llvm::createPromoteMemoryToRegisterPass());
    // Provide basic AliasAnalysis support for GVN.
    fpm->add(llvm::createBasicAliasAnalysisPass());
    // Do simple "peephole" optimizations and bit-twiddling optzns.
    fpm->add(llvm::createInstructionCombiningPass());
    // Reassociate expressions.
    fpm->add(llvm::createReassociatePass());
    // Eliminate Common SubExpressions.
    fpm->add(llvm::createGVNPass());
    // Simplify the control flow graph (deleting unreachable blocks, etc).
    fpm->add(llvm::createCFGSimplificationPass());
}

std::string replace_ext(const std::string &origName, const std::string& expectedExt, const std::string& newExt)
{
    if (origName.substr(origName.size() - expectedExt.size()) != expectedExt)
    {
	std::cerr << "Could not find extension..." << std::endl;
	exit(1);
	return "";
    }
    return origName.substr(0, origName.size() - expectedExt.size()) + newExt;
}

static void Compile(const std::string& filename)
{
    try
    {
	ExprAST* ast;
	Lexer l(filename, types);
	Parser p(l, types);
	OptimizerInit();

	ast = p.Parse();
	int e = p.GetErrors();
	if (e > 0)
	{
	    std::cout << "Errors in parsing: " << e << ". Exiting..." << std::endl;
	    return;
	}
	llvm::Module* module = CodeGen(ast);
	DumpModule(module);
	CreateBinary(module,   replace_ext(filename, ".pas", ".o"), replace_ext(filename, ".pas", ""));
    }
    catch(std::exception e)
    {
	std::cerr << "Exception: " << e.what() << std::endl;
    }
    catch(...)
    {
	std::cerr << "Unknown Exception - this should not happen??? " << std::endl;
    }
}

int main(int argc, char** argv)
{
    for(int i = 1; i < argc; i++)
    {
	Compile(argv[i]);
    }
}
<commit_msg>Revert changes to lacsap.cpp<commit_after>#include "lexer.h"
#include "parser.h"
#include "binary.h"
#include <iostream>
#include <fstream>
#include "llvm/Bitcode/ReaderWriter.h"
#include "llvm/Support/raw_os_ostream.h"
#include <llvm/ExecutionEngine/ExecutionEngine.h>
#include <llvm/ExecutionEngine/JIT.h>
#include <llvm/Analysis/Passes.h>
#include <llvm/IR/LLVMContext.h>
#include <llvm/IR/DataLayout.h>
#include <llvm/Support/TargetSelect.h>
#include <llvm/Transforms/Scalar.h>

static std::string ErrStr;
llvm::FunctionPassManager* fpm;
static llvm::ExecutionEngine* theExecutionEngine;
llvm::Module* theModule = new llvm::Module("TheModule", llvm::getGlobalContext());

void DumpModule(llvm::Module* module)
{
    module->dump();
}

llvm::Module* CodeGen(ExprAST* ast)
{
    for(auto a = ast; a; a = a->Next())
    {
	llvm::Value* v = a->CodeGen();
	if (!v)
	{
	    std::cerr << "Sorry, something went wrong here..." << std::endl;
	    a->Dump(std::cerr);
	    return 0;
	}
    }
    return theModule;
}

void OptimizerInit()
{
    fpm = new llvm::FunctionPassManager(theModule);

    llvm::InitializeNativeTarget();

    theExecutionEngine = llvm::EngineBuilder(theModule).setErrorStr(&ErrStr).create();
    if (!theExecutionEngine) {
	std::cerr << "Could not create ExecutionEngine:" << ErrStr << std::endl;
	exit(1);
    }

    // Set up the optimizer pipeline.  Start with registering info about how the
    // target lays out data structures.
    fpm->add(new llvm::DataLayout(*theExecutionEngine->getDataLayout()));
    // Promote allocas to registers.
    fpm->add(llvm::createPromoteMemoryToRegisterPass());
    // Provide basic AliasAnalysis support for GVN.
    fpm->add(llvm::createBasicAliasAnalysisPass());
    // Do simple "peephole" optimizations and bit-twiddling optzns.
    fpm->add(llvm::createInstructionCombiningPass());
    // Reassociate expressions.
    fpm->add(llvm::createReassociatePass());
    // Eliminate Common SubExpressions.
    fpm->add(llvm::createGVNPass());
    // Simplify the control flow graph (deleting unreachable blocks, etc).
    fpm->add(llvm::createCFGSimplificationPass());
}

std::string replace_ext(const std::string &origName, const std::string& expectedExt, const std::string& newExt)
{
    if (origName.substr(origName.size() - expectedExt.size()) != expectedExt)
    {
	std::cerr << "Could not find extension..." << std::endl;
	exit(1);
	return "";
    }
    return origName.substr(0, origName.size() - expectedExt.size()) + newExt;
}

static void Compile(const std::string& filename)
{
    try
    {
	ExprAST* ast;
	Types types;
	Lexer l(filename, types);
	Parser p(l, types);
	OptimizerInit();

	ast = p.Parse();
	int e = p.GetErrors();
	if (e > 0)
	{
	    std::cout << "Errors in parsing: " << e << ". Exiting..." << std::endl;
	    return;
	}
	llvm::Module* module = CodeGen(ast);
	DumpModule(module);
	CreateBinary(module,   replace_ext(filename, ".pas", ".o"), replace_ext(filename, ".pas", ""));
    }
    catch(std::exception e)
    {
	std::cerr << "Exception: " << e.what() << std::endl;
    }
    catch(...)
    {
	std::cerr << "Unknown Exception - this should not happen??? " << std::endl;
    }
}

int main(int argc, char** argv)
{
    for(int i = 1; i < argc; i++)
    {
	Compile(argv[i]);
    }
}
<|endoftext|>


<commit_before>#include "framework/logger.h"
#include "game/state/tileview/collision.h"
#include "game/state/tileview/tile.h"
#include "library/voxel.h"

using namespace OpenApoc;

class FakeSceneryTileObject : public TileObject
{
  public:
	Vec3<float> position;
	sp<VoxelMap> voxel;

	Vec3<float> getPosition() const override { return this->position; }
	sp<VoxelMap> getVoxelMap(Vec3<int>) override { return this->voxel; }

	FakeSceneryTileObject(TileMap &map, Vec3<float> bounds, sp<VoxelMap> voxelMap)
	    : TileObject(map, Type::Scenery, bounds), position(0, 0, 0), voxel(voxelMap)
	{
		this->name = "FAKE_SCENERY";
	}
	~FakeSceneryTileObject() override = default;

	void setPosition(Vec3<float> newPosition) override
	{
		this->position = newPosition;
		TileObject::setPosition(newPosition);
	}
	void draw(Renderer &, TileTransform &, Vec2<float>, TileViewMode, int) override
	{
		LogError("DRAW CALLED ON FAKE SCENERY??");
		exit(EXIT_FAILURE);
	}
};

static void test_collision(const TileMap &map, Vec3<float> line_start, Vec3<float> line_end,
                           sp<TileObject> expected_collision)
{
	auto collision = map.findCollision(line_start, line_end);
	if (collision.obj != expected_collision)
	{
		LogError("Line between {%f,%f,%f} and {%f,%f,%f} collided with %s, expected %s",
		         line_start.x, line_start.y, line_start.z, line_end.x, line_end.y, line_end.z,
		         collision.obj ? collision.obj->getName().cStr() : "NONE",
		         expected_collision ? expected_collision->getName().cStr() : "NONE");
		exit(EXIT_FAILURE);
	}
}

int main(int, char **)
{
	auto filled_slice_32_32 = mksp<VoxelSlice>(Vec2<int>{32, 32});
	for (int y = 0; y < 32; y++)
	{
		for (int x = 0; x < 32; x++)
		{
			filled_slice_32_32->setBit({x, y}, true);
		}
	}

	auto empty_tilemap_32_32_16 = mksp<VoxelMap>(Vec3<int>{32, 32, 16});
	auto filled_tilemap_32_32_16 = mksp<VoxelMap>(Vec3<int>{32, 32, 16});
	for (int z = 0; z < 16; z++)
	{
		filled_tilemap_32_32_16->setSlice(z, filled_slice_32_32);
	}

	// LayerMap is only used for drawing
	TileMap map{{100, 100, 10}, {1, 1, 1}, {32, 32, 16}, {{TileObject::Type::Scenery}}};

	// Spawn some objects
	std::vector<std::pair<Vec3<float>, sp<TileObject>>> objects = {
	    {Vec3<float>{2.5, 2.5, 2.5},
	     mksp<FakeSceneryTileObject>(map, Vec3<float>{1, 1, 1}, filled_tilemap_32_32_16)},
	    {Vec3<float>{99.5, 99.5, 9.5},
	     mksp<FakeSceneryTileObject>(map, Vec3<float>{1, 1, 1}, filled_tilemap_32_32_16)},
	};

	for (auto &object : objects)
	{
		auto initialPosition = object.first;
		object.second->setPosition(initialPosition);
		if (initialPosition != object.second->getPosition())
		{
			LogError("Object %s moved from {%f,%f,%f} to {%f,%f,%f}",
			         object.second->getName().cStr(), initialPosition.x, initialPosition.y,
			         initialPosition.z, object.second->getPosition().x,
			         object.second->getPosition().y, object.second->getPosition().z);
			exit(EXIT_FAILURE);
		}
	}

	// Compare some expected collisions
	//{{line_start,line_end},expected_object}
	std::vector<std::pair<std::array<Vec3<float>, 2>, sp<TileObject>>> collisions = {
	    {{{Vec3<float>{0, 0, 0}, Vec3<float>{1, 1, 1}}}, nullptr},
	    {{{Vec3<float>{2.1, 2.1, 0}, Vec3<float>{2.1, 2.1, 4}}}, objects[0].second},
	    {{{Vec3<float>{2.6, 2.6, 0}, Vec3<float>{2.6, 2.6, 4}}}, objects[0].second},
	    {{{Vec3<float>{2.6, 0, 2.1}, Vec3<float>{2.6, 4, 2.1}}}, objects[0].second},
	    {{{Vec3<float>{2.6, 0, 2.6}, Vec3<float>{2.6, 4, 2.6}}}, objects[0].second},
	    {{{Vec3<float>{0, 2.1, 2.1}, Vec3<float>{4, 2.1, 2.1}}}, objects[0].second},
	    {{{Vec3<float>{0, 2.6, 2.6}, Vec3<float>{4, 2.6, 2.6}}}, objects[0].second},
	    {{{Vec3<float>{2.1, 2.1, 0}, Vec3<float>{2.1, 2.6, 4}}}, objects[0].second},
	    {{{Vec3<float>{2.6, 2.6, 0}, Vec3<float>{2.1, 2.6, 4}}}, objects[0].second},
	    {{{Vec3<float>{2.6, 0, 2.1}, Vec3<float>{2.1, 4, 2.1}}}, objects[0].second},
	    {{{Vec3<float>{2.1, 0, 2.6}, Vec3<float>{2.6, 4, 2.6}}}, objects[0].second},
	    {{{Vec3<float>{0, 2.6, 2.6}, Vec3<float>{4, 2.1, 2.6}}}, objects[0].second},
	    {{{Vec3<float>{0, 2.1, 2.6}, Vec3<float>{4, 2.6, 2.6}}}, objects[0].second},
	};

	for (auto &collision : collisions)
	{
		test_collision(map, collision.first[0], collision.first[1], collision.second);
	}

	return EXIT_SUCCESS;
}
<commit_msg>travis nth fix<commit_after>#include "framework/logger.h"
#include "game/state/tileview/collision.h"
#include "game/state/tileview/tile.h"
#include "library/voxel.h"

using namespace OpenApoc;

class FakeSceneryTileObject : public TileObject
{
  public:
	Vec3<float> position;
	sp<VoxelMap> voxel;

	Vec3<float> getPosition() const override { return this->position; }
	bool hasVoxelMap() override { return true; }
	sp<VoxelMap> getVoxelMap(Vec3<int>) override { return this->voxel; }

	FakeSceneryTileObject(TileMap &map, Vec3<float> bounds, sp<VoxelMap> voxelMap)
	    : TileObject(map, Type::Scenery, bounds), position(0, 0, 0), voxel(voxelMap)
	{
		this->name = "FAKE_SCENERY";
	}
	~FakeSceneryTileObject() override = default;

	void setPosition(Vec3<float> newPosition) override
	{
		this->position = newPosition;
		TileObject::setPosition(newPosition);
	}
	void draw(Renderer &, TileTransform &, Vec2<float>, TileViewMode, int) override
	{
		LogError("DRAW CALLED ON FAKE SCENERY??");
		exit(EXIT_FAILURE);
	}
};

static void test_collision(const TileMap &map, Vec3<float> line_start, Vec3<float> line_end,
                           sp<TileObject> expected_collision)
{
	auto collision = map.findCollision(line_start, line_end);
	if (collision.obj != expected_collision)
	{
		LogError("Line between {%f,%f,%f} and {%f,%f,%f} collided with %s, expected %s",
		         line_start.x, line_start.y, line_start.z, line_end.x, line_end.y, line_end.z,
		         collision.obj ? collision.obj->getName().cStr() : "NONE",
		         expected_collision ? expected_collision->getName().cStr() : "NONE");
		exit(EXIT_FAILURE);
	}
}

int main(int, char **)
{
	auto filled_slice_32_32 = mksp<VoxelSlice>(Vec2<int>{32, 32});
	for (int y = 0; y < 32; y++)
	{
		for (int x = 0; x < 32; x++)
		{
			filled_slice_32_32->setBit({x, y}, true);
		}
	}

	auto empty_tilemap_32_32_16 = mksp<VoxelMap>(Vec3<int>{32, 32, 16});
	auto filled_tilemap_32_32_16 = mksp<VoxelMap>(Vec3<int>{32, 32, 16});
	for (int z = 0; z < 16; z++)
	{
		filled_tilemap_32_32_16->setSlice(z, filled_slice_32_32);
	}

	// LayerMap is only used for drawing
	TileMap map{{100, 100, 10}, {1, 1, 1}, {32, 32, 16}, {{TileObject::Type::Scenery}}};

	// Spawn some objects
	std::vector<std::pair<Vec3<float>, sp<TileObject>>> objects = {
	    {Vec3<float>{2.5, 2.5, 2.5},
	     mksp<FakeSceneryTileObject>(map, Vec3<float>{1, 1, 1}, filled_tilemap_32_32_16)},
	    {Vec3<float>{99.5, 99.5, 9.5},
	     mksp<FakeSceneryTileObject>(map, Vec3<float>{1, 1, 1}, filled_tilemap_32_32_16)},
	};

	for (auto &object : objects)
	{
		auto initialPosition = object.first;
		object.second->setPosition(initialPosition);
		if (initialPosition != object.second->getPosition())
		{
			LogError("Object %s moved from {%f,%f,%f} to {%f,%f,%f}",
			         object.second->getName().cStr(), initialPosition.x, initialPosition.y,
			         initialPosition.z, object.second->getPosition().x,
			         object.second->getPosition().y, object.second->getPosition().z);
			exit(EXIT_FAILURE);
		}
	}

	// Compare some expected collisions
	//{{line_start,line_end},expected_object}
	std::vector<std::pair<std::array<Vec3<float>, 2>, sp<TileObject>>> collisions = {
	    {{{Vec3<float>{0, 0, 0}, Vec3<float>{1, 1, 1}}}, nullptr},
	    {{{Vec3<float>{2.1, 2.1, 0}, Vec3<float>{2.1, 2.1, 4}}}, objects[0].second},
	    {{{Vec3<float>{2.6, 2.6, 0}, Vec3<float>{2.6, 2.6, 4}}}, objects[0].second},
	    {{{Vec3<float>{2.6, 0, 2.1}, Vec3<float>{2.6, 4, 2.1}}}, objects[0].second},
	    {{{Vec3<float>{2.6, 0, 2.6}, Vec3<float>{2.6, 4, 2.6}}}, objects[0].second},
	    {{{Vec3<float>{0, 2.1, 2.1}, Vec3<float>{4, 2.1, 2.1}}}, objects[0].second},
	    {{{Vec3<float>{0, 2.6, 2.6}, Vec3<float>{4, 2.6, 2.6}}}, objects[0].second},
	    {{{Vec3<float>{2.1, 2.1, 0}, Vec3<float>{2.1, 2.6, 4}}}, objects[0].second},
	    {{{Vec3<float>{2.6, 2.6, 0}, Vec3<float>{2.1, 2.6, 4}}}, objects[0].second},
	    {{{Vec3<float>{2.6, 0, 2.1}, Vec3<float>{2.1, 4, 2.1}}}, objects[0].second},
	    {{{Vec3<float>{2.1, 0, 2.6}, Vec3<float>{2.6, 4, 2.6}}}, objects[0].second},
	    {{{Vec3<float>{0, 2.6, 2.6}, Vec3<float>{4, 2.1, 2.6}}}, objects[0].second},
	    {{{Vec3<float>{0, 2.1, 2.6}, Vec3<float>{4, 2.6, 2.6}}}, objects[0].second},
	};

	for (auto &collision : collisions)
	{
		test_collision(map, collision.first[0], collision.first[1], collision.second);
	}

	return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2021 Baldur Karlsson
 *
 * 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 "ComputeDebugSelector.h"
#include "Code/QRDUtils.h"
#include "ui_ComputeDebugSelector.h"

ComputeDebugSelector::ComputeDebugSelector(QWidget *parent)
    : QDialog(parent), ui(new Ui::ComputeDebugSelector)
{
  ui->setupUi(this);

  m_threadGroupSize[0] = m_threadGroupSize[1] = m_threadGroupSize[2] = 1;

  setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);

  ui->groupX->setFont(Formatter::PreferredFont());
  ui->groupY->setFont(Formatter::PreferredFont());
  ui->groupZ->setFont(Formatter::PreferredFont());
  ui->threadX->setFont(Formatter::PreferredFont());
  ui->threadY->setFont(Formatter::PreferredFont());
  ui->threadZ->setFont(Formatter::PreferredFont());
  ui->dispatchX->setFont(Formatter::PreferredFont());
  ui->dispatchY->setFont(Formatter::PreferredFont());
  ui->dispatchZ->setFont(Formatter::PreferredFont());

  // A threadgroup's size in any dimension can be up to 1024, but a dispatch can be 65535
  // threadgroups for a dimension. Use that upper bound to fix the min size of all fields.
  ui->groupX->setMaximum(65535);
  int sizeHint = ui->groupX->minimumSizeHint().width();
  ui->groupX->setMinimumWidth(sizeHint);
  ui->groupY->setMinimumWidth(sizeHint);
  ui->groupZ->setMinimumWidth(sizeHint);
  ui->threadX->setMinimumWidth(sizeHint);
  ui->threadY->setMinimumWidth(sizeHint);
  ui->threadZ->setMinimumWidth(sizeHint);
  ui->dispatchX->setMinimumWidth(sizeHint);
  ui->dispatchY->setMinimumWidth(sizeHint);
  ui->dispatchZ->setMinimumWidth(sizeHint);
}

ComputeDebugSelector::~ComputeDebugSelector()
{
  delete ui;
}

void ComputeDebugSelector::SetThreadBounds(const rdcfixedarray<uint32_t, 3> &group,
                                           const rdcfixedarray<uint32_t, 3> &thread)
{
  // Set maximums for CS debugging
  ui->groupX->setMaximum(group[0] - 1);
  ui->groupY->setMaximum(group[1] - 1);
  ui->groupZ->setMaximum(group[2] - 1);

  ui->threadX->setMaximum(thread[0] - 1);
  ui->threadY->setMaximum(thread[1] - 1);
  ui->threadZ->setMaximum(thread[2] - 1);

  ui->dispatchX->setMaximum(group[0] * thread[0] - 1);
  ui->dispatchY->setMaximum(group[1] * thread[1] - 1);
  ui->dispatchZ->setMaximum(group[2] * thread[2] - 1);

  m_threadGroupSize = thread;
}

void ComputeDebugSelector::SyncGroupThreadValue()
{
  ui->dispatchX->setValue(ui->groupX->value() * m_threadGroupSize[0] + ui->threadX->value());
  ui->dispatchY->setValue(ui->groupY->value() * m_threadGroupSize[1] + ui->threadY->value());
  ui->dispatchZ->setValue(ui->groupZ->value() * m_threadGroupSize[2] + ui->threadZ->value());
}

void ComputeDebugSelector::SyncDispatchThreadValue()
{
  uint32_t group[3] = {ui->dispatchX->value() / m_threadGroupSize[0],
                       ui->dispatchY->value() / m_threadGroupSize[1],
                       ui->dispatchZ->value() / m_threadGroupSize[2]};
  uint32_t thread[3] = {ui->dispatchX->value() % m_threadGroupSize[0],
                        ui->dispatchY->value() % m_threadGroupSize[1],
                        ui->dispatchZ->value() % m_threadGroupSize[2]};

  ui->groupX->setValue(group[0]);
  ui->groupY->setValue(group[1]);
  ui->groupZ->setValue(group[2]);
  ui->threadX->setValue(thread[0]);
  ui->threadY->setValue(thread[1]);
  ui->threadZ->setValue(thread[2]);
}

void ComputeDebugSelector::on_beginDebug_clicked()
{
  // The dispatch thread IDs and the group/thread IDs are synced on editing either set, so we can
  // choose either one to begin debugging.
  uint32_t group[3] = {(uint32_t)ui->groupX->value(), (uint32_t)ui->groupY->value(),
                       (uint32_t)ui->groupZ->value()};
  uint32_t thread[3] = {(uint32_t)ui->threadX->value(), (uint32_t)ui->threadY->value(),
                        (uint32_t)ui->threadZ->value()};
  emit beginDebug(group, thread);
  close();
}

void ComputeDebugSelector::on_cancelDebug_clicked()
{
  close();
}
<commit_msg>Prevent focus reset when typing in the compute debug selector<commit_after>/******************************************************************************
 * The MIT License (MIT)
 *
 * Copyright (c) 2021 Baldur Karlsson
 *
 * 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 "ComputeDebugSelector.h"
#include "Code/QRDUtils.h"
#include "ui_ComputeDebugSelector.h"

ComputeDebugSelector::ComputeDebugSelector(QWidget *parent)
    : QDialog(parent), ui(new Ui::ComputeDebugSelector)
{
  ui->setupUi(this);

  m_threadGroupSize[0] = m_threadGroupSize[1] = m_threadGroupSize[2] = 1;

  setWindowFlags(windowFlags() & ~Qt::WindowContextHelpButtonHint);

  ui->groupX->setFont(Formatter::PreferredFont());
  ui->groupY->setFont(Formatter::PreferredFont());
  ui->groupZ->setFont(Formatter::PreferredFont());
  ui->threadX->setFont(Formatter::PreferredFont());
  ui->threadY->setFont(Formatter::PreferredFont());
  ui->threadZ->setFont(Formatter::PreferredFont());
  ui->dispatchX->setFont(Formatter::PreferredFont());
  ui->dispatchY->setFont(Formatter::PreferredFont());
  ui->dispatchZ->setFont(Formatter::PreferredFont());

  // A threadgroup's size in any dimension can be up to 1024, but a dispatch can be 65535
  // threadgroups for a dimension. Use that upper bound to fix the min size of all fields.
  ui->groupX->setMaximum(65535);
  int sizeHint = ui->groupX->minimumSizeHint().width();
  ui->groupX->setMinimumWidth(sizeHint);
  ui->groupY->setMinimumWidth(sizeHint);
  ui->groupZ->setMinimumWidth(sizeHint);
  ui->threadX->setMinimumWidth(sizeHint);
  ui->threadY->setMinimumWidth(sizeHint);
  ui->threadZ->setMinimumWidth(sizeHint);
  ui->dispatchX->setMinimumWidth(sizeHint);
  ui->dispatchY->setMinimumWidth(sizeHint);
  ui->dispatchZ->setMinimumWidth(sizeHint);
}

ComputeDebugSelector::~ComputeDebugSelector()
{
  delete ui;
}

void ComputeDebugSelector::SetThreadBounds(const rdcfixedarray<uint32_t, 3> &group,
                                           const rdcfixedarray<uint32_t, 3> &thread)
{
  // Set maximums for CS debugging
  ui->groupX->setMaximum(group[0] - 1);
  ui->groupY->setMaximum(group[1] - 1);
  ui->groupZ->setMaximum(group[2] - 1);

  ui->threadX->setMaximum(thread[0] - 1);
  ui->threadY->setMaximum(thread[1] - 1);
  ui->threadZ->setMaximum(thread[2] - 1);

  ui->dispatchX->setMaximum(group[0] * thread[0] - 1);
  ui->dispatchY->setMaximum(group[1] * thread[1] - 1);
  ui->dispatchZ->setMaximum(group[2] * thread[2] - 1);

  m_threadGroupSize = thread;
}

void ComputeDebugSelector::SyncGroupThreadValue()
{
  QSignalBlocker blockers[3] = {QSignalBlocker(ui->dispatchX), QSignalBlocker(ui->dispatchY),
                                QSignalBlocker(ui->dispatchZ)};

  ui->dispatchX->setValue(ui->groupX->value() * m_threadGroupSize[0] + ui->threadX->value());
  ui->dispatchY->setValue(ui->groupY->value() * m_threadGroupSize[1] + ui->threadY->value());
  ui->dispatchZ->setValue(ui->groupZ->value() * m_threadGroupSize[2] + ui->threadZ->value());
}

void ComputeDebugSelector::SyncDispatchThreadValue()
{
  uint32_t group[3] = {ui->dispatchX->value() / m_threadGroupSize[0],
                       ui->dispatchY->value() / m_threadGroupSize[1],
                       ui->dispatchZ->value() / m_threadGroupSize[2]};
  uint32_t thread[3] = {ui->dispatchX->value() % m_threadGroupSize[0],
                        ui->dispatchY->value() % m_threadGroupSize[1],
                        ui->dispatchZ->value() % m_threadGroupSize[2]};

  QSignalBlocker blockers[6] = {QSignalBlocker(ui->groupX),  QSignalBlocker(ui->groupY),
                                QSignalBlocker(ui->groupZ),  QSignalBlocker(ui->threadX),
                                QSignalBlocker(ui->threadY), QSignalBlocker(ui->threadZ)};

  ui->groupX->setValue(group[0]);
  ui->groupY->setValue(group[1]);
  ui->groupZ->setValue(group[2]);
  ui->threadX->setValue(thread[0]);
  ui->threadY->setValue(thread[1]);
  ui->threadZ->setValue(thread[2]);
}

void ComputeDebugSelector::on_beginDebug_clicked()
{
  // The dispatch thread IDs and the group/thread IDs are synced on editing either set, so we can
  // choose either one to begin debugging.
  uint32_t group[3] = {(uint32_t)ui->groupX->value(), (uint32_t)ui->groupY->value(),
                       (uint32_t)ui->groupZ->value()};
  uint32_t thread[3] = {(uint32_t)ui->threadX->value(), (uint32_t)ui->threadY->value(),
                        (uint32_t)ui->threadZ->value()};
  emit beginDebug(group, thread);
  close();
}

void ComputeDebugSelector::on_cancelDebug_clicked()
{
  close();
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkContextInteractorStyle.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkContextInteractorStyle.h"

#include "vtkContextMouseEvent.h"
#include "vtkContextKeyEvent.h"
#include "vtkContextScene.h"
#include "vtkCallbackCommand.h"
#include "vtkCommand.h"
#include "vtkObjectFactory.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"

#include <cassert>

vtkStandardNewMacro(vtkContextInteractorStyle);

//--------------------------------------------------------------------------
vtkContextInteractorStyle::vtkContextInteractorStyle()
{
  this->Scene = NULL;
  this->ProcessingEvents = 0;
  this->SceneCallbackCommand->SetClientData(this);
  this->SceneCallbackCommand->SetCallback(
    vtkContextInteractorStyle::ProcessSceneEvents);
  this->InteractorCallbackCommand->SetClientData(this);
  this->InteractorCallbackCommand->SetCallback(
    vtkContextInteractorStyle::ProcessInteractorEvents);
  this->LastSceneRepaintMTime = 0;
  this->TimerId = 0;
  this->TimerCallbackInitialized = false;
}

//--------------------------------------------------------------------------
vtkContextInteractorStyle::~vtkContextInteractorStyle()
{
  // to remove observers.
  this->SetScene(0);
  if (this->TimerCallbackInitialized && this->Interactor)
    {
    this->Interactor->RemoveObserver(this->InteractorCallbackCommand.Get());
    this->TimerCallbackInitialized = false;
    }
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Scene: " << this->Scene << endl;
  if (this->Scene)
    {
    this->Scene->PrintSelf(os, indent.GetNextIndent());
    }
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::SetScene(vtkContextScene* scene)
{
  if (this->Scene == scene)
    {
    return;
    }
  if (this->Scene)
    {
    this->Scene->RemoveObserver(this->SceneCallbackCommand.GetPointer());
    }

  this->Scene = scene;

  if (this->Scene)
    {
    this->Scene->AddObserver(vtkCommand::ModifiedEvent,
                             this->SceneCallbackCommand.GetPointer(),
                             this->Priority);
    }
  this->Modified();
}

//----------------------------------------------------------------------------
vtkContextScene* vtkContextInteractorStyle::GetScene()
{
  return this->Scene;
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::ProcessSceneEvents(vtkObject*,
                                                   unsigned long event,
                                                   void* clientdata,
                                                   void* vtkNotUsed(calldata))
{
  vtkContextInteractorStyle* self =
    reinterpret_cast<vtkContextInteractorStyle *>( clientdata );
  switch (event)
    {
    case vtkCommand::ModifiedEvent:
      self->OnSceneModified();
      break;
    default:
      break;
    }
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::ProcessInteractorEvents(vtkObject*,
                                                        unsigned long,
                                                        void* clientdata,
                                                        void* vtkNotUsed(calldata))
{
  vtkContextInteractorStyle* self =
    reinterpret_cast<vtkContextInteractorStyle *>(clientdata);
  self->RenderNow();
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::RenderNow()
{
  this->TimerId = 0;
  if (this->Scene && !this->ProcessingEvents &&
      this->Interactor->GetInitialized())
    {
    this->Interactor->GetRenderWindow()->Render();
    }
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::OnSceneModified()
{
  if (!this->Scene
      || !this->Scene->GetDirty()
      || this->ProcessingEvents
      || this->Scene->GetMTime() == this->LastSceneRepaintMTime
      || !this->Interactor->GetInitialized())
    {
    return;
    }
  this->BeginProcessingEvent();
  if (!this->TimerCallbackInitialized && this->Interactor)
    {
    this->Interactor->AddObserver(vtkCommand::TimerEvent,
                                  this->InteractorCallbackCommand.GetPointer(),
                                  0.0);
    this->TimerCallbackInitialized = true;
    }
  this->LastSceneRepaintMTime = this->Scene->GetMTime();
  // If there is no timer, create a one shot timer to render an updated scene
  if (this->TimerId == 0)
    {
    this->Interactor->CreateOneShotTimer(40);
    }
  this->EndProcessingEvent();
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::BeginProcessingEvent()
{
  ++this->ProcessingEvents;
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::EndProcessingEvent()
{
  --this->ProcessingEvents;
  assert(this->ProcessingEvents >= 0);
  if (this->ProcessingEvents == 0)
    {
    this->OnSceneModified();
    }
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::OnMouseMove()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::NO_BUTTON);
    eatEvent = this->Scene->MouseMoveEvent(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnMouseMove();
    }

  this->EndProcessingEvent();
}

inline bool vtkContextInteractorStyle::ProcessMousePress(
    const vtkContextMouseEvent &event)
{
  bool eatEvent(false);
  if (this->Interactor->GetRepeatCount())
    {
    eatEvent = this->Scene->DoubleClickEvent(event);
    //
    // The second ButtonRelease event seems not to be processed automatically,
    // need manually processing here so that the following MouseMove event will
    // not think the mouse button is still pressed down, and we don't really
    // care about the return result from the second ButtonRelease.
    //
    if (eatEvent)
      {
      this->Scene->ButtonReleaseEvent(event);
      }
    }
  else
    {
    eatEvent = this->Scene->ButtonPressEvent(event);
    }
  return eatEvent;
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::OnLeftButtonDown()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::LEFT_BUTTON);
    eatEvent = this->ProcessMousePress(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnLeftButtonDown();
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnLeftButtonUp()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::LEFT_BUTTON);
    eatEvent = this->Scene->ButtonReleaseEvent(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnLeftButtonUp();
    }
  this->EndProcessingEvent();
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::OnMiddleButtonDown()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON);
    eatEvent = this->ProcessMousePress(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnMiddleButtonDown();
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnMiddleButtonUp()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON);
    eatEvent = this->Scene->ButtonReleaseEvent(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnMiddleButtonUp();
    }
  this->EndProcessingEvent();
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::OnRightButtonDown()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::RIGHT_BUTTON);
    eatEvent = this->ProcessMousePress(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnRightButtonDown();
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnRightButtonUp()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::RIGHT_BUTTON);
    eatEvent = this->Scene->ButtonReleaseEvent(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnRightButtonUp();
    }
  this->EndProcessingEvent();
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::OnMouseWheelForward()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON);
    eatEvent = this->Scene->MouseWheelEvent(
          static_cast<int>(this->MouseWheelMotionFactor), event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnMouseWheelForward();
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnMouseWheelBackward()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON);
    eatEvent = this->Scene->MouseWheelEvent(
          -static_cast<int>(this->MouseWheelMotionFactor), event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnMouseWheelBackward();
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnSelection(unsigned int rect[5])
{
  this->BeginProcessingEvent();
  if (this->Scene)
    {
    this->Scene->ProcessSelectionEvent(rect);
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnChar()
{
  this->Superclass::OnChar();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnKeyPress()
{
  this->BeginProcessingEvent();
  vtkContextKeyEvent event;
  vtkVector2i position(this->Interactor->GetEventPosition()[0],
                       this->Interactor->GetEventPosition()[0]);
  event.SetInteractor(this->Interactor);
  event.SetPosition(position);
  bool keepEvent = false;
  if (this->Scene)
    {
    keepEvent = this->Scene->KeyPressEvent(event);
    }
  if (!keepEvent)
    {
    this->Superclass::OnKeyPress();
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnKeyRelease()
{
  this->BeginProcessingEvent();
  vtkContextKeyEvent event;
  vtkVector2i position(this->Interactor->GetEventPosition()[0],
                       this->Interactor->GetEventPosition()[0]);
  event.SetInteractor(this->Interactor);
  event.SetPosition(position);
  bool keepEvent = false;
  if (this->Scene)
    {
    keepEvent = this->Scene->KeyReleaseEvent(event);
    }
  if (!keepEvent)
    {
    this->Superclass::OnKeyRelease();
    }
  this->EndProcessingEvent();
}

//-------------------------------------------------------------------------
inline void vtkContextInteractorStyle::ConstructMouseEvent(
    vtkContextMouseEvent &event, int button)
{
  event.SetInteractor(this->Interactor);
  event.SetPos(vtkVector2f(this->Interactor->GetEventPosition()[0],
                           this->Interactor->GetEventPosition()[1]));
  event.SetButton(button);
}
<commit_msg>BUG: Fixed error in passing position of key press<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkContextInteractorStyle.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

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

=========================================================================*/
#include "vtkContextInteractorStyle.h"

#include "vtkContextMouseEvent.h"
#include "vtkContextKeyEvent.h"
#include "vtkContextScene.h"
#include "vtkCallbackCommand.h"
#include "vtkCommand.h"
#include "vtkObjectFactory.h"
#include "vtkRenderWindow.h"
#include "vtkRenderWindowInteractor.h"

#include <cassert>

vtkStandardNewMacro(vtkContextInteractorStyle);

//--------------------------------------------------------------------------
vtkContextInteractorStyle::vtkContextInteractorStyle()
{
  this->Scene = NULL;
  this->ProcessingEvents = 0;
  this->SceneCallbackCommand->SetClientData(this);
  this->SceneCallbackCommand->SetCallback(
    vtkContextInteractorStyle::ProcessSceneEvents);
  this->InteractorCallbackCommand->SetClientData(this);
  this->InteractorCallbackCommand->SetCallback(
    vtkContextInteractorStyle::ProcessInteractorEvents);
  this->LastSceneRepaintMTime = 0;
  this->TimerId = 0;
  this->TimerCallbackInitialized = false;
}

//--------------------------------------------------------------------------
vtkContextInteractorStyle::~vtkContextInteractorStyle()
{
  // to remove observers.
  this->SetScene(0);
  if (this->TimerCallbackInitialized && this->Interactor)
    {
    this->Interactor->RemoveObserver(this->InteractorCallbackCommand.Get());
    this->TimerCallbackInitialized = false;
    }
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::PrintSelf(ostream& os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << indent << "Scene: " << this->Scene << endl;
  if (this->Scene)
    {
    this->Scene->PrintSelf(os, indent.GetNextIndent());
    }
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::SetScene(vtkContextScene* scene)
{
  if (this->Scene == scene)
    {
    return;
    }
  if (this->Scene)
    {
    this->Scene->RemoveObserver(this->SceneCallbackCommand.GetPointer());
    }

  this->Scene = scene;

  if (this->Scene)
    {
    this->Scene->AddObserver(vtkCommand::ModifiedEvent,
                             this->SceneCallbackCommand.GetPointer(),
                             this->Priority);
    }
  this->Modified();
}

//----------------------------------------------------------------------------
vtkContextScene* vtkContextInteractorStyle::GetScene()
{
  return this->Scene;
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::ProcessSceneEvents(vtkObject*,
                                                   unsigned long event,
                                                   void* clientdata,
                                                   void* vtkNotUsed(calldata))
{
  vtkContextInteractorStyle* self =
    reinterpret_cast<vtkContextInteractorStyle *>( clientdata );
  switch (event)
    {
    case vtkCommand::ModifiedEvent:
      self->OnSceneModified();
      break;
    default:
      break;
    }
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::ProcessInteractorEvents(vtkObject*,
                                                        unsigned long,
                                                        void* clientdata,
                                                        void* vtkNotUsed(calldata))
{
  vtkContextInteractorStyle* self =
    reinterpret_cast<vtkContextInteractorStyle *>(clientdata);
  self->RenderNow();
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::RenderNow()
{
  this->TimerId = 0;
  if (this->Scene && !this->ProcessingEvents &&
      this->Interactor->GetInitialized())
    {
    this->Interactor->GetRenderWindow()->Render();
    }
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::OnSceneModified()
{
  if (!this->Scene
      || !this->Scene->GetDirty()
      || this->ProcessingEvents
      || this->Scene->GetMTime() == this->LastSceneRepaintMTime
      || !this->Interactor->GetInitialized())
    {
    return;
    }
  this->BeginProcessingEvent();
  if (!this->TimerCallbackInitialized && this->Interactor)
    {
    this->Interactor->AddObserver(vtkCommand::TimerEvent,
                                  this->InteractorCallbackCommand.GetPointer(),
                                  0.0);
    this->TimerCallbackInitialized = true;
    }
  this->LastSceneRepaintMTime = this->Scene->GetMTime();
  // If there is no timer, create a one shot timer to render an updated scene
  if (this->TimerId == 0)
    {
    this->Interactor->CreateOneShotTimer(40);
    }
  this->EndProcessingEvent();
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::BeginProcessingEvent()
{
  ++this->ProcessingEvents;
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::EndProcessingEvent()
{
  --this->ProcessingEvents;
  assert(this->ProcessingEvents >= 0);
  if (this->ProcessingEvents == 0)
    {
    this->OnSceneModified();
    }
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::OnMouseMove()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::NO_BUTTON);
    eatEvent = this->Scene->MouseMoveEvent(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnMouseMove();
    }

  this->EndProcessingEvent();
}

inline bool vtkContextInteractorStyle::ProcessMousePress(
    const vtkContextMouseEvent &event)
{
  bool eatEvent(false);
  if (this->Interactor->GetRepeatCount())
    {
    eatEvent = this->Scene->DoubleClickEvent(event);
    //
    // The second ButtonRelease event seems not to be processed automatically,
    // need manually processing here so that the following MouseMove event will
    // not think the mouse button is still pressed down, and we don't really
    // care about the return result from the second ButtonRelease.
    //
    if (eatEvent)
      {
      this->Scene->ButtonReleaseEvent(event);
      }
    }
  else
    {
    eatEvent = this->Scene->ButtonPressEvent(event);
    }
  return eatEvent;
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::OnLeftButtonDown()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::LEFT_BUTTON);
    eatEvent = this->ProcessMousePress(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnLeftButtonDown();
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnLeftButtonUp()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::LEFT_BUTTON);
    eatEvent = this->Scene->ButtonReleaseEvent(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnLeftButtonUp();
    }
  this->EndProcessingEvent();
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::OnMiddleButtonDown()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON);
    eatEvent = this->ProcessMousePress(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnMiddleButtonDown();
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnMiddleButtonUp()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON);
    eatEvent = this->Scene->ButtonReleaseEvent(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnMiddleButtonUp();
    }
  this->EndProcessingEvent();
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::OnRightButtonDown()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::RIGHT_BUTTON);
    eatEvent = this->ProcessMousePress(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnRightButtonDown();
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnRightButtonUp()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::RIGHT_BUTTON);
    eatEvent = this->Scene->ButtonReleaseEvent(event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnRightButtonUp();
    }
  this->EndProcessingEvent();
}

//----------------------------------------------------------------------------
void vtkContextInteractorStyle::OnMouseWheelForward()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON);
    eatEvent = this->Scene->MouseWheelEvent(
          static_cast<int>(this->MouseWheelMotionFactor), event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnMouseWheelForward();
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnMouseWheelBackward()
{
  this->BeginProcessingEvent();

  bool eatEvent = false;
  if (this->Scene)
    {
    vtkContextMouseEvent event;
    this->ConstructMouseEvent(event, vtkContextMouseEvent::MIDDLE_BUTTON);
    eatEvent = this->Scene->MouseWheelEvent(
          -static_cast<int>(this->MouseWheelMotionFactor), event);
    }
  if (!eatEvent)
    {
    this->Superclass::OnMouseWheelBackward();
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnSelection(unsigned int rect[5])
{
  this->BeginProcessingEvent();
  if (this->Scene)
    {
    this->Scene->ProcessSelectionEvent(rect);
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnChar()
{
  this->Superclass::OnChar();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnKeyPress()
{
  this->BeginProcessingEvent();
  vtkContextKeyEvent event;
  vtkVector2i position(this->Interactor->GetEventPosition()[0],
                       this->Interactor->GetEventPosition()[1]);
  event.SetInteractor(this->Interactor);
  event.SetPosition(position);
  bool keepEvent = false;
  if (this->Scene)
    {
    keepEvent = this->Scene->KeyPressEvent(event);
    }
  if (!keepEvent)
    {
    this->Superclass::OnKeyPress();
    }
  this->EndProcessingEvent();
}

//--------------------------------------------------------------------------
void vtkContextInteractorStyle::OnKeyRelease()
{
  this->BeginProcessingEvent();
  vtkContextKeyEvent event;
  vtkVector2i position(this->Interactor->GetEventPosition()[0],
                       this->Interactor->GetEventPosition()[1]);
  event.SetInteractor(this->Interactor);
  event.SetPosition(position);
  bool keepEvent = false;
  if (this->Scene)
    {
    keepEvent = this->Scene->KeyReleaseEvent(event);
    }
  if (!keepEvent)
    {
    this->Superclass::OnKeyRelease();
    }
  this->EndProcessingEvent();
}

//-------------------------------------------------------------------------
inline void vtkContextInteractorStyle::ConstructMouseEvent(
    vtkContextMouseEvent &event, int button)
{
  event.SetInteractor(this->Interactor);
  event.SetPos(vtkVector2f(this->Interactor->GetEventPosition()[0],
                           this->Interactor->GetEventPosition()[1]));
  event.SetButton(button);
}
<|endoftext|>


<commit_before>#include "Direct3DHandler.h"

Direct3DHandler::Direct3DHandler()
{
	this->m_activeWindow = nullptr;
	this->m_backBufferRTV = nullptr;
	this->m_depthStencilBuffer = nullptr;
	this->m_gDevice = nullptr;
	this->m_gDeviceContext = nullptr;
	this->m_rasterizerState = nullptr;
	this->m_rasterizerStateWireFrame = nullptr;
	this->m_swapChain = nullptr;
	this->m_viewport = nullptr;
	this->m_SwapCount = 1;
}

Direct3DHandler::~Direct3DHandler()
{
}

int Direct3DHandler::Initialize(HWND* windowHandle, const DirectX::XMINT2& resolution, bool editorMode)
{
	HRESULT hResult;

	// Create the Device \\

	D3D_FEATURE_LEVEL featureLevel;
	this->m_SwapCount = 1;
	if (editorMode)
	{
		featureLevel = D3D_FEATURE_LEVEL_11_0;
		this->m_SwapCount = 0;
	}
	else
	{
		featureLevel = D3D_FEATURE_LEVEL_11_1;
		this->m_SwapCount = 1;
	}

#ifdef _DEBUG
	hResult = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE,
		NULL, D3D11_CREATE_DEVICE_DEBUG, &featureLevel, 1, D3D11_SDK_VERSION, &this->m_gDevice,
		NULL, &this->m_gDeviceContext);
	if (FAILED(hResult))
	{
		return 1;
	}
#else
	hResult = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE,
		NULL, D3D11_CREATE_DEVICE_SINGLETHREADED, &featureLevel, 1, D3D11_SDK_VERSION, &this->m_gDevice,
		NULL, &this->m_gDeviceContext);
	if (FAILED(hResult))
	{
		return 1;
	}
#endif

	// Create the rasterizer state \\

	D3D11_RASTERIZER_DESC rasterizerDesc;
	ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc));

	rasterizerDesc.AntialiasedLineEnable = false;
	rasterizerDesc.CullMode = D3D11_CULL_BACK; //Enable backface culling
	rasterizerDesc.DepthBias = 0;
	rasterizerDesc.DepthBiasClamp = 0.0f;
	rasterizerDesc.DepthClipEnable = true;
	rasterizerDesc.FillMode = D3D11_FILL_SOLID;
	rasterizerDesc.FrontCounterClockwise = false;
	rasterizerDesc.MultisampleEnable = false;
	rasterizerDesc.ScissorEnable = false;
	rasterizerDesc.SlopeScaledDepthBias = 0.0f;

	hResult = this->m_gDevice->CreateRasterizerState(&rasterizerDesc, &this->m_rasterizerState);
	if (FAILED(hResult))
	{
		return 1;
	}

	this->m_gDeviceContext->RSSetState(this->m_rasterizerState); //Set the rasterstate

	// Create the swapchain \\

	DXGI_SWAP_CHAIN_DESC1 swapChainDesc = { 0 };
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	swapChainDesc.Height = resolution.y;
	swapChainDesc.Width = resolution.x;
	swapChainDesc.Stereo = false;
	swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
	swapChainDesc.Scaling = DXGI_SCALING_NONE;

	swapChainDesc.SampleDesc.Count = 1; //No MSAA
	swapChainDesc.SampleDesc.Quality = 0;

	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT;
	if (editorMode)
	{
		swapChainDesc.BufferCount = 1;
		swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
		swapChainDesc.Flags = 0;
	}
	else
	{
		swapChainDesc.BufferCount = 2;
		swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
		swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH /*DXGI_PRESENT_RESTART*/;
	}

	DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullScreenDesc;
	fullScreenDesc.RefreshRate.Numerator = 60;
	fullScreenDesc.RefreshRate.Denominator = 1;
	fullScreenDesc.Windowed = true;
	fullScreenDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	fullScreenDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;

	IDXGIDevice1* dxgiDevice = nullptr;
	hResult = this->m_gDevice->QueryInterface(__uuidof(IDXGIDevice1), (void**)&dxgiDevice);
	if (FAILED(hResult))
	{
		return 1;
	}

	IDXGIAdapter2* dxgiAdapter = nullptr;
	hResult = dxgiDevice->GetParent(__uuidof(IDXGIAdapter2), (void**)&dxgiAdapter);
	if (FAILED(hResult))
	{
		return 1;
	}

	IDXGIFactory2* dxgiFactory2 = nullptr;
	hResult = dxgiAdapter->GetParent(__uuidof(IDXGIFactory2), (void**)&dxgiFactory2);
	if (FAILED(hResult))
	{
		return 1;
	}

	hResult = dxgiFactory2->CreateSwapChainForHwnd(this->m_gDevice, HWND(*windowHandle), &swapChainDesc, &fullScreenDesc, nullptr, &m_swapChain);
	if (FAILED(hResult))
	{
		return 1;
	}

	// Create the backbuffer render target view \\

	ID3D11Texture2D* backBufferPrt = nullptr;
	this->m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)(&backBufferPrt));

	hResult = this->m_gDevice->CreateRenderTargetView(backBufferPrt, NULL, &this->m_backBufferRTV);
	if (FAILED(hResult))
	{
		return 1;
	}

	hResult = this->m_gDevice->CreateShaderResourceView(backBufferPrt, nullptr, &this->m_backBufferSRV);

	if (FAILED(hResult))
	{
		return 1;
	}

	backBufferPrt->Release();

	this->m_viewport = new D3D11_VIEWPORT;
	this->m_viewport->TopLeftX = 0.0f;
	this->m_viewport->TopLeftY = 0.0f;
	this->m_viewport->Width = float(resolution.x);
	this->m_viewport->Height = float(resolution.y);
	this->m_viewport->MinDepth = 0.0f;
	this->m_viewport->MaxDepth = 1.0f;

	this->m_gDeviceContext->RSSetViewports(1, this->m_viewport);

	Resources::ResourceHandler::GetInstance()->SetDeviceAndContext(this->m_gDevice, this->m_gDeviceContext);

	D3D11_BLEND_DESC BlendState;
	ZeroMemory(&BlendState, sizeof(D3D11_BLEND_DESC));
	BlendState.RenderTarget[0].BlendEnable = FALSE;
	BlendState.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
	this->m_gDevice->CreateBlendState(&BlendState, &g_pBlendStateNoBlend);

	return 0;
}

int Direct3DHandler::InitializeGridRasterizer()
{
	HRESULT hResult;

	D3D11_RASTERIZER_DESC rasterizerDesc;
	ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc));

	rasterizerDesc.AntialiasedLineEnable = false;
	rasterizerDesc.CullMode = D3D11_CULL_NONE; //Enable backface culling
	rasterizerDesc.DepthBias = 0;
	rasterizerDesc.DepthBiasClamp = 0.0f;
	rasterizerDesc.DepthClipEnable = true;
	rasterizerDesc.FillMode = D3D11_FILL_WIREFRAME;
	rasterizerDesc.FrontCounterClockwise = false;
	rasterizerDesc.MultisampleEnable = false;
	rasterizerDesc.ScissorEnable = false;
	rasterizerDesc.SlopeScaledDepthBias = 0.0f;

	hResult = this->m_gDevice->CreateRasterizerState(&rasterizerDesc, &this->m_rasterizerStateWireFrame);
	if (FAILED(hResult))
	{
		return 1;
	}

	return 0;
}

int Direct3DHandler::PresentScene()
{
	//RECT dirtyRectPrev, dirtyRectCurrent, dirtyRectCopy;
	//IntersectRect(&dirtyRectCopy, &dirtyRectPrev, &dirtyRectCurrent);

	this->m_swapChain->Present(this->m_SwapCount, 0);

	return 0;
}

void Direct3DHandler::Shutdown()
{
	if (this->m_depthStencilBuffer)
	{
		this->m_depthStencilBuffer->Release();
		this->m_depthStencilBuffer = nullptr;
	}

	if (this->m_rasterizerState)
	{
		this->m_rasterizerState->Release();
		this->m_rasterizerState = nullptr;
	}

	if (this->m_rasterizerState)
	{
		this->m_rasterizerState->Release();
		this->m_rasterizerState = nullptr;
	}

	if (this->m_backBufferRTV)
	{
		this->m_backBufferRTV->Release();
		this->m_backBufferRTV = nullptr;
	}

	if (this->m_backBufferSRV)
	{
		this->m_backBufferSRV->Release();
		this->m_backBufferSRV = nullptr;
	}

	if (this->m_swapChain)
	{
		this->m_swapChain->Release();
		this->m_swapChain = nullptr;
	}

	if (this->m_gDeviceContext)
	{
		this->m_gDeviceContext->Release();
		this->m_gDeviceContext = nullptr;
	}

	if (this->m_gDevice)
	{
		this->m_gDevice->Release();
		this->m_gDevice = nullptr;
	}

	if (this->m_viewport)
	{
		delete this->m_viewport;
		this->m_viewport = nullptr;
	}

	if (this->m_rasterizerStateWireFrame)
	{
		m_rasterizerStateWireFrame->Release();
		this->m_rasterizerStateWireFrame = nullptr;
	}
}

ID3D11Device * Direct3DHandler::GetDevice()
{
	return this->m_gDevice;
}

ID3D11DeviceContext * Direct3DHandler::GetDeviceContext()
{
	return this->m_gDeviceContext;
}

ID3D11RenderTargetView * Direct3DHandler::GetBackbufferRTV()
{
	return this->m_backBufferRTV;
}

ID3D11ShaderResourceView * Direct3DHandler::GetBackbufferSRV()
{
	return this->m_backBufferSRV;
}

D3D11_VIEWPORT * Direct3DHandler::GetViewPort()
{
	return m_viewport;
}

int Direct3DHandler::SetRasterizerState(D3D11_FILL_MODE mode)
{
	switch (mode)
	{
	case D3D11_FILL_WIREFRAME:
	{
		this->m_gDeviceContext->RSSetState(this->m_rasterizerStateWireFrame);
		break;
	}
	case D3D11_FILL_SOLID:
	{
		this->m_gDeviceContext->RSSetState(this->m_rasterizerState);
		break;
	}
	default:
		break;
	}

	return 0;
}

int Direct3DHandler::ClearBlendState()
{
	this->m_gDeviceContext->OMSetBlendState(this->g_pBlendStateNoBlend, this->blendFactor, this->sampleMask);
	return 0;
}

<commit_msg>FIX merge override that removed exact ideal screen update<commit_after>#include "Direct3DHandler.h"

Direct3DHandler::Direct3DHandler()
{
	this->m_activeWindow = nullptr;
	this->m_backBufferRTV = nullptr;
	this->m_depthStencilBuffer = nullptr;
	this->m_gDevice = nullptr;
	this->m_gDeviceContext = nullptr;
	this->m_rasterizerState = nullptr;
	this->m_rasterizerStateWireFrame = nullptr;
	this->m_swapChain = nullptr;
	this->m_viewport = nullptr;
	this->m_SwapCount = 1;
}

Direct3DHandler::~Direct3DHandler()
{
}

int Direct3DHandler::Initialize(HWND* windowHandle, const DirectX::XMINT2& resolution, bool editorMode)
{
	HRESULT hResult;

	// Create the Device \\

	D3D_FEATURE_LEVEL featureLevel;
	this->m_SwapCount = 1;
	if (editorMode)
	{
		featureLevel = D3D_FEATURE_LEVEL_11_0;
		this->m_SwapCount = 0;
	}
	else
	{
		featureLevel = D3D_FEATURE_LEVEL_11_1;
		this->m_SwapCount = 1;
	}

#ifdef _DEBUG
	hResult = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE,
		NULL, D3D11_CREATE_DEVICE_DEBUG, &featureLevel, 1, D3D11_SDK_VERSION, &this->m_gDevice,
		NULL, &this->m_gDeviceContext);
	if (FAILED(hResult))
	{
		return 1;
	}
#else
	hResult = D3D11CreateDevice(NULL, D3D_DRIVER_TYPE_HARDWARE,
		NULL, D3D11_CREATE_DEVICE_SINGLETHREADED, &featureLevel, 1, D3D11_SDK_VERSION, &this->m_gDevice,
		NULL, &this->m_gDeviceContext);
	if (FAILED(hResult))
	{
		return 1;
	}
#endif

	// Create the rasterizer state \\

	D3D11_RASTERIZER_DESC rasterizerDesc;
	ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc));

	rasterizerDesc.AntialiasedLineEnable = false;
	rasterizerDesc.CullMode = D3D11_CULL_BACK; //Enable backface culling
	rasterizerDesc.DepthBias = 0;
	rasterizerDesc.DepthBiasClamp = 0.0f;
	rasterizerDesc.DepthClipEnable = true;
	rasterizerDesc.FillMode = D3D11_FILL_SOLID;
	rasterizerDesc.FrontCounterClockwise = false;
	rasterizerDesc.MultisampleEnable = false;
	rasterizerDesc.ScissorEnable = false;
	rasterizerDesc.SlopeScaledDepthBias = 0.0f;

	hResult = this->m_gDevice->CreateRasterizerState(&rasterizerDesc, &this->m_rasterizerState);
	if (FAILED(hResult))
	{
		return 1;
	}

	this->m_gDeviceContext->RSSetState(this->m_rasterizerState); //Set the rasterstate

	// Create the swapchain \\

	DXGI_SWAP_CHAIN_DESC1 swapChainDesc = { 0 };
	ZeroMemory(&swapChainDesc, sizeof(swapChainDesc));

	swapChainDesc.Format = DXGI_FORMAT_R8G8B8A8_UNORM;
	swapChainDesc.Height = resolution.y;
	swapChainDesc.Width = resolution.x;
	swapChainDesc.Stereo = false;
	swapChainDesc.AlphaMode = DXGI_ALPHA_MODE_UNSPECIFIED;
	swapChainDesc.Scaling = DXGI_SCALING_NONE;

	swapChainDesc.SampleDesc.Count = 1; //No MSAA
	swapChainDesc.SampleDesc.Quality = 0;

	swapChainDesc.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT | DXGI_USAGE_SHADER_INPUT;
	if (editorMode)
	{
		swapChainDesc.BufferCount = 1;
		swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_DISCARD;
		swapChainDesc.Flags = 0;
	}
	else
	{
		swapChainDesc.BufferCount = 2;
		swapChainDesc.SwapEffect = DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL;
		swapChainDesc.Flags = DXGI_SWAP_CHAIN_FLAG_ALLOW_MODE_SWITCH /*DXGI_PRESENT_RESTART*/;
	}

	DXGI_SWAP_CHAIN_FULLSCREEN_DESC fullScreenDesc;
	fullScreenDesc.RefreshRate.Numerator = 59994;
	fullScreenDesc.RefreshRate.Denominator = 1002;
	fullScreenDesc.Windowed = true;
	fullScreenDesc.Scaling = DXGI_MODE_SCALING_UNSPECIFIED;
	fullScreenDesc.ScanlineOrdering = DXGI_MODE_SCANLINE_ORDER_UNSPECIFIED;

	IDXGIDevice1* dxgiDevice = nullptr;
	hResult = this->m_gDevice->QueryInterface(__uuidof(IDXGIDevice1), (void**)&dxgiDevice);
	if (FAILED(hResult))
	{
		return 1;
	}

	IDXGIAdapter2* dxgiAdapter = nullptr;
	hResult = dxgiDevice->GetParent(__uuidof(IDXGIAdapter2), (void**)&dxgiAdapter);
	if (FAILED(hResult))
	{
		return 1;
	}

	IDXGIFactory2* dxgiFactory2 = nullptr;
	hResult = dxgiAdapter->GetParent(__uuidof(IDXGIFactory2), (void**)&dxgiFactory2);
	if (FAILED(hResult))
	{
		return 1;
	}

	hResult = dxgiFactory2->CreateSwapChainForHwnd(this->m_gDevice, HWND(*windowHandle), &swapChainDesc, &fullScreenDesc, nullptr, &m_swapChain);
	if (FAILED(hResult))
	{
		return 1;
	}

	// Create the backbuffer render target view \\

	ID3D11Texture2D* backBufferPrt = nullptr;
	this->m_swapChain->GetBuffer(0, __uuidof(ID3D11Texture2D), (LPVOID*)(&backBufferPrt));

	hResult = this->m_gDevice->CreateRenderTargetView(backBufferPrt, NULL, &this->m_backBufferRTV);
	if (FAILED(hResult))
	{
		return 1;
	}

	hResult = this->m_gDevice->CreateShaderResourceView(backBufferPrt, nullptr, &this->m_backBufferSRV);

	if (FAILED(hResult))
	{
		return 1;
	}

	backBufferPrt->Release();

	this->m_viewport = new D3D11_VIEWPORT;
	this->m_viewport->TopLeftX = 0.0f;
	this->m_viewport->TopLeftY = 0.0f;
	this->m_viewport->Width = float(resolution.x);
	this->m_viewport->Height = float(resolution.y);
	this->m_viewport->MinDepth = 0.0f;
	this->m_viewport->MaxDepth = 1.0f;

	this->m_gDeviceContext->RSSetViewports(1, this->m_viewport);

	Resources::ResourceHandler::GetInstance()->SetDeviceAndContext(this->m_gDevice, this->m_gDeviceContext);

	D3D11_BLEND_DESC BlendState;
	ZeroMemory(&BlendState, sizeof(D3D11_BLEND_DESC));
	BlendState.RenderTarget[0].BlendEnable = FALSE;
	BlendState.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL;
	this->m_gDevice->CreateBlendState(&BlendState, &g_pBlendStateNoBlend);

	return 0;
}

int Direct3DHandler::InitializeGridRasterizer()
{
	HRESULT hResult;

	D3D11_RASTERIZER_DESC rasterizerDesc;
	ZeroMemory(&rasterizerDesc, sizeof(rasterizerDesc));

	rasterizerDesc.AntialiasedLineEnable = false;
	rasterizerDesc.CullMode = D3D11_CULL_NONE; //Enable backface culling
	rasterizerDesc.DepthBias = 0;
	rasterizerDesc.DepthBiasClamp = 0.0f;
	rasterizerDesc.DepthClipEnable = true;
	rasterizerDesc.FillMode = D3D11_FILL_WIREFRAME;
	rasterizerDesc.FrontCounterClockwise = false;
	rasterizerDesc.MultisampleEnable = false;
	rasterizerDesc.ScissorEnable = false;
	rasterizerDesc.SlopeScaledDepthBias = 0.0f;

	hResult = this->m_gDevice->CreateRasterizerState(&rasterizerDesc, &this->m_rasterizerStateWireFrame);
	if (FAILED(hResult))
	{
		return 1;
	}

	return 0;
}

int Direct3DHandler::PresentScene()
{
	//RECT dirtyRectPrev, dirtyRectCurrent, dirtyRectCopy;
	//IntersectRect(&dirtyRectCopy, &dirtyRectPrev, &dirtyRectCurrent);

	this->m_swapChain->Present(this->m_SwapCount, 0);

	return 0;
}

void Direct3DHandler::Shutdown()
{
	if (this->m_depthStencilBuffer)
	{
		this->m_depthStencilBuffer->Release();
		this->m_depthStencilBuffer = nullptr;
	}

	if (this->m_rasterizerState)
	{
		this->m_rasterizerState->Release();
		this->m_rasterizerState = nullptr;
	}

	if (this->m_rasterizerState)
	{
		this->m_rasterizerState->Release();
		this->m_rasterizerState = nullptr;
	}

	if (this->m_backBufferRTV)
	{
		this->m_backBufferRTV->Release();
		this->m_backBufferRTV = nullptr;
	}

	if (this->m_backBufferSRV)
	{
		this->m_backBufferSRV->Release();
		this->m_backBufferSRV = nullptr;
	}

	if (this->m_swapChain)
	{
		this->m_swapChain->Release();
		this->m_swapChain = nullptr;
	}

	if (this->m_gDeviceContext)
	{
		this->m_gDeviceContext->Release();
		this->m_gDeviceContext = nullptr;
	}

	if (this->m_gDevice)
	{
		this->m_gDevice->Release();
		this->m_gDevice = nullptr;
	}

	if (this->m_viewport)
	{
		delete this->m_viewport;
		this->m_viewport = nullptr;
	}

	if (this->m_rasterizerStateWireFrame)
	{
		m_rasterizerStateWireFrame->Release();
		this->m_rasterizerStateWireFrame = nullptr;
	}
}

ID3D11Device * Direct3DHandler::GetDevice()
{
	return this->m_gDevice;
}

ID3D11DeviceContext * Direct3DHandler::GetDeviceContext()
{
	return this->m_gDeviceContext;
}

ID3D11RenderTargetView * Direct3DHandler::GetBackbufferRTV()
{
	return this->m_backBufferRTV;
}

ID3D11ShaderResourceView * Direct3DHandler::GetBackbufferSRV()
{
	return this->m_backBufferSRV;
}

D3D11_VIEWPORT * Direct3DHandler::GetViewPort()
{
	return m_viewport;
}

int Direct3DHandler::SetRasterizerState(D3D11_FILL_MODE mode)
{
	switch (mode)
	{
	case D3D11_FILL_WIREFRAME:
	{
		this->m_gDeviceContext->RSSetState(this->m_rasterizerStateWireFrame);
		break;
	}
	case D3D11_FILL_SOLID:
	{
		this->m_gDeviceContext->RSSetState(this->m_rasterizerState);
		break;
	}
	default:
		break;
	}

	return 0;
}

int Direct3DHandler::ClearBlendState()
{
	this->m_gDeviceContext->OMSetBlendState(this->g_pBlendStateNoBlend, this->blendFactor, this->sampleMask);
	return 0;
}

<|endoftext|>