<commit_before>/*
 * Copyright © 2010 Intel Corporation
 *
 * 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 (including the next
 * paragraph) 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.
 */

/**
 * \file opt_structure_splitting.cpp
 *
 * If a structure is only ever referenced by its components, then
 * split those components out to individual variables so they can be
 * handled normally by other optimization passes.
 *
 * This skips structures like uniforms, which need to be accessible as
 * structures for their access by the GL.
 */

#include "ir.h"
#include "ir_visitor.h"
#include "ir_print_visitor.h"
#include "ir_rvalue_visitor.h"
#include "glsl_types.h"

namespace {

static bool debug = false;

// XXX using variable_entry2 here to avoid collision (MSVC multiply-defined
// function) with the variable_entry class seen in ir_variable_refcount.h
// Perhaps we can use the one in ir_variable_refcount.h and make this class
// here go away?
class variable_entry2 : public exec_node
{
public:
   variable_entry2(ir_variable *var)
   {
      this->var = var;
      this->whole_structure_access = 0;
      this->declaration = false;
      this->components = NULL;
      this->mem_ctx = NULL;
   }

   ir_variable *var; /* The key: the variable's pointer. */

   /** Number of times the variable is referenced, including assignments. */
   unsigned whole_structure_access;

   /* If the variable had a decl we can work with in the instruction
    * stream.  We can't do splitting on function arguments, which
    * don't get this variable set.
    */
   bool declaration;

   ir_variable **components;

   /** ralloc_parent(this->var) -- the shader's ralloc context. */
   void *mem_ctx;
};

class ir_structure_reference_visitor : public ir_hierarchical_visitor {
public:
   ir_structure_reference_visitor(void)
   {
      this->mem_ctx = ralloc_context(NULL);
      this->variable_list.make_empty();
   }

   ~ir_structure_reference_visitor(void)
   {
      ralloc_free(mem_ctx);
   }

   virtual ir_visitor_status visit(ir_variable *);
   virtual ir_visitor_status visit(ir_dereference_variable *);
   virtual ir_visitor_status visit_enter(ir_dereference_record *);
   virtual ir_visitor_status visit_enter(ir_assignment *);
   virtual ir_visitor_status visit_enter(ir_function_signature *);

   variable_entry2 *get_variable_entry2(ir_variable *var);

   /* List of variable_entry */
   exec_list variable_list;

   void *mem_ctx;
};

variable_entry2 *
ir_structure_reference_visitor::get_variable_entry2(ir_variable *var)
{
   assert(var);

   if (!var->type->is_record() || var->mode == ir_var_uniform)
      return NULL;

   foreach_iter(exec_list_iterator, iter, this->variable_list) {
      variable_entry2 *entry = (variable_entry2 *)iter.get();
      if (entry->var == var)
	 return entry;
   }

   variable_entry2 *entry = new(mem_ctx) variable_entry2(var);
   this->variable_list.push_tail(entry);
   return entry;
}

ir_visitor_status
ir_structure_reference_visitor::visit(ir_variable *ir)
{
   variable_entry2 *entry = this->get_variable_entry2(ir);

   if (entry)
      entry->declaration = true;

   return visit_continue;
}

ir_visitor_status
ir_structure_reference_visitor::visit(ir_dereference_variable *ir)
{
   ir_variable *const var = ir->variable_referenced();
   variable_entry2 *entry = this->get_variable_entry2(var);

   if (entry)
      entry->whole_structure_access++;

   return visit_continue;
}

ir_visitor_status
ir_structure_reference_visitor::visit_enter(ir_dereference_record *ir)
{
   (void) ir;
   /* Don't descend into the ir_dereference_variable below. */
   return visit_continue_with_parent;
}

ir_visitor_status
ir_structure_reference_visitor::visit_enter(ir_assignment *ir)
{
   /* If there are no structure references yet, no need to bother with
    * processing the expression tree.
    */
   if (this->variable_list.is_empty())
      return visit_continue_with_parent;

   if (ir->lhs->as_dereference_variable() &&
       ir->rhs->as_dereference_variable() &&
       !ir->condition) {
      /* We'll split copies of a structure to copies of components, so don't
       * descend to the ir_dereference_variables.
       */
      return visit_continue_with_parent;
   }
   return visit_continue;
}

ir_visitor_status
ir_structure_reference_visitor::visit_enter(ir_function_signature *ir)
{
   /* We don't have logic for structure-splitting function arguments,
    * so just look at the body instructions and not the parameter
    * declarations.
    */
   visit_list_elements(this, &ir->body);
   return visit_continue_with_parent;
}

class ir_structure_splitting_visitor : public ir_rvalue_visitor {
public:
   ir_structure_splitting_visitor(exec_list *vars)
   {
      this->variable_list = vars;
   }

   virtual ~ir_structure_splitting_visitor()
   {
   }

   virtual ir_visitor_status visit_leave(ir_assignment *);

   void split_deref(ir_dereference **deref);
   void handle_rvalue(ir_rvalue **rvalue);
   variable_entry2 *get_splitting_entry(ir_variable *var);

   exec_list *variable_list;
};

variable_entry2 *
ir_structure_splitting_visitor::get_splitting_entry(ir_variable *var)
{
   assert(var);

   if (!var->type->is_record())
      return NULL;

   foreach_iter(exec_list_iterator, iter, *this->variable_list) {
      variable_entry2 *entry = (variable_entry2 *)iter.get();
      if (entry->var == var) {
	 return entry;
      }
   }

   return NULL;
}

void
ir_structure_splitting_visitor::split_deref(ir_dereference **deref)
{
   if ((*deref)->ir_type != ir_type_dereference_record)
      return;

   ir_dereference_record *deref_record = (ir_dereference_record *)*deref;
   ir_dereference_variable *deref_var = deref_record->record->as_dereference_variable();
   if (!deref_var)
      return;

   variable_entry2 *entry = get_splitting_entry(deref_var->var);
   if (!entry)
      return;

   unsigned int i;
   for (i = 0; i < entry->var->type->length; i++) {
      if (strcmp(deref_record->field,
		 entry->var->type->fields.structure[i].name) == 0)
	 break;
   }
   assert(i != entry->var->type->length);

   *deref = new(entry->mem_ctx) ir_dereference_variable(entry->components[i]);
}

void
ir_structure_splitting_visitor::handle_rvalue(ir_rvalue **rvalue)
{
   if (!*rvalue)
      return;

   ir_dereference *deref = (*rvalue)->as_dereference();

   if (!deref)
      return;

   split_deref(&deref);
   *rvalue = deref;
}

ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_assignment *ir)
{
   ir_dereference_variable *lhs_deref = ir->lhs->as_dereference_variable();
   ir_dereference_variable *rhs_deref = ir->rhs->as_dereference_variable();
   variable_entry2 *lhs_entry = lhs_deref ? get_splitting_entry(lhs_deref->var) : NULL;
   variable_entry2 *rhs_entry = rhs_deref ? get_splitting_entry(rhs_deref->var) : NULL;
   const glsl_type *type = ir->rhs->type;

   if ((lhs_entry || rhs_entry) && !ir->condition) {
      for (unsigned int i = 0; i < type->length; i++) {
	 ir_dereference *new_lhs, *new_rhs;
	 void *mem_ctx = lhs_entry ? lhs_entry->mem_ctx : rhs_entry->mem_ctx;

	 if (lhs_entry) {
	    new_lhs = new(mem_ctx) ir_dereference_variable(lhs_entry->components[i]);
	 } else {
	    new_lhs = new(mem_ctx)
	       ir_dereference_record(ir->lhs->clone(mem_ctx, NULL),
				     type->fields.structure[i].name);
	 }

	 if (rhs_entry) {
	    new_rhs = new(mem_ctx) ir_dereference_variable(rhs_entry->components[i]);
	 } else {
	    new_rhs = new(mem_ctx)
	       ir_dereference_record(ir->rhs->clone(mem_ctx, NULL),
				     type->fields.structure[i].name);
	 }

	 ir->insert_before(new(mem_ctx) ir_assignment(new_lhs,
						      new_rhs,
						      NULL));
      }
      ir->remove();
   } else {
      handle_rvalue(&ir->rhs);
      split_deref(&ir->lhs);
   }

   handle_rvalue(&ir->condition);

   return visit_continue;
}

} /* unnamed namespace */

bool
do_structure_splitting(exec_list *instructions)
{
   ir_structure_reference_visitor refs;

   visit_list_elements(&refs, instructions);

   /* Trim out variables we can't split. */
   foreach_iter(exec_list_iterator, iter, refs.variable_list) {
      variable_entry2 *entry = (variable_entry2 *)iter.get();

      if (debug) {
	 printf("structure %s@%p: decl %d, whole_access %d\n",
		entry->var->name, (void *) entry->var, entry->declaration,
		entry->whole_structure_access);
      }

      if (!entry->declaration || entry->whole_structure_access) {
	 entry->remove();
      }
   }

   if (refs.variable_list.is_empty())
      return false;

   void *mem_ctx = ralloc_context(NULL);

   /* Replace the decls of the structures to be split with their split
    * components.
    */
   foreach_iter(exec_list_iterator, iter, refs.variable_list) {
      variable_entry2 *entry = (variable_entry2 *)iter.get();
      const struct glsl_type *type = entry->var->type;

      entry->mem_ctx = ralloc_parent(entry->var);

      entry->components = ralloc_array(mem_ctx,
				       ir_variable *,
				       type->length);

      for (unsigned int i = 0; i < entry->var->type->length; i++) {
	 const char *name = ralloc_asprintf(mem_ctx, "%s_%s",
					    entry->var->name,
					    type->fields.structure[i].name);

	 entry->components[i] =
	    new(entry->mem_ctx) ir_variable(type->fields.structure[i].type,
					    name,
					    ir_var_temporary);
	 entry->var->insert_before(entry->components[i]);
      }

      entry->var->remove();
   }

   ir_structure_splitting_visitor split(&refs.variable_list);
   visit_list_elements(&split, instructions);

   ralloc_free(mem_ctx);

   return true;
}
<commit_msg>glsl: Rename variable_entry2 back to variable_entry in struct splitting.<commit_after>/*
 * Copyright © 2010 Intel Corporation
 *
 * 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 (including the next
 * paragraph) 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.
 */

/**
 * \file opt_structure_splitting.cpp
 *
 * If a structure is only ever referenced by its components, then
 * split those components out to individual variables so they can be
 * handled normally by other optimization passes.
 *
 * This skips structures like uniforms, which need to be accessible as
 * structures for their access by the GL.
 */

#include "ir.h"
#include "ir_visitor.h"
#include "ir_print_visitor.h"
#include "ir_rvalue_visitor.h"
#include "glsl_types.h"

namespace {

static bool debug = false;

class variable_entry : public exec_node
{
public:
   variable_entry(ir_variable *var)
   {
      this->var = var;
      this->whole_structure_access = 0;
      this->declaration = false;
      this->components = NULL;
      this->mem_ctx = NULL;
   }

   ir_variable *var; /* The key: the variable's pointer. */

   /** Number of times the variable is referenced, including assignments. */
   unsigned whole_structure_access;

   /* If the variable had a decl we can work with in the instruction
    * stream.  We can't do splitting on function arguments, which
    * don't get this variable set.
    */
   bool declaration;

   ir_variable **components;

   /** ralloc_parent(this->var) -- the shader's ralloc context. */
   void *mem_ctx;
};

class ir_structure_reference_visitor : public ir_hierarchical_visitor {
public:
   ir_structure_reference_visitor(void)
   {
      this->mem_ctx = ralloc_context(NULL);
      this->variable_list.make_empty();
   }

   ~ir_structure_reference_visitor(void)
   {
      ralloc_free(mem_ctx);
   }

   virtual ir_visitor_status visit(ir_variable *);
   virtual ir_visitor_status visit(ir_dereference_variable *);
   virtual ir_visitor_status visit_enter(ir_dereference_record *);
   virtual ir_visitor_status visit_enter(ir_assignment *);
   virtual ir_visitor_status visit_enter(ir_function_signature *);

   variable_entry *get_variable_entry(ir_variable *var);

   /* List of variable_entry */
   exec_list variable_list;

   void *mem_ctx;
};

variable_entry *
ir_structure_reference_visitor::get_variable_entry(ir_variable *var)
{
   assert(var);

   if (!var->type->is_record() || var->mode == ir_var_uniform)
      return NULL;

   foreach_iter(exec_list_iterator, iter, this->variable_list) {
      variable_entry *entry = (variable_entry *)iter.get();
      if (entry->var == var)
	 return entry;
   }

   variable_entry *entry = new(mem_ctx) variable_entry(var);
   this->variable_list.push_tail(entry);
   return entry;
}

ir_visitor_status
ir_structure_reference_visitor::visit(ir_variable *ir)
{
   variable_entry *entry = this->get_variable_entry(ir);

   if (entry)
      entry->declaration = true;

   return visit_continue;
}

ir_visitor_status
ir_structure_reference_visitor::visit(ir_dereference_variable *ir)
{
   ir_variable *const var = ir->variable_referenced();
   variable_entry *entry = this->get_variable_entry(var);

   if (entry)
      entry->whole_structure_access++;

   return visit_continue;
}

ir_visitor_status
ir_structure_reference_visitor::visit_enter(ir_dereference_record *ir)
{
   (void) ir;
   /* Don't descend into the ir_dereference_variable below. */
   return visit_continue_with_parent;
}

ir_visitor_status
ir_structure_reference_visitor::visit_enter(ir_assignment *ir)
{
   /* If there are no structure references yet, no need to bother with
    * processing the expression tree.
    */
   if (this->variable_list.is_empty())
      return visit_continue_with_parent;

   if (ir->lhs->as_dereference_variable() &&
       ir->rhs->as_dereference_variable() &&
       !ir->condition) {
      /* We'll split copies of a structure to copies of components, so don't
       * descend to the ir_dereference_variables.
       */
      return visit_continue_with_parent;
   }
   return visit_continue;
}

ir_visitor_status
ir_structure_reference_visitor::visit_enter(ir_function_signature *ir)
{
   /* We don't have logic for structure-splitting function arguments,
    * so just look at the body instructions and not the parameter
    * declarations.
    */
   visit_list_elements(this, &ir->body);
   return visit_continue_with_parent;
}

class ir_structure_splitting_visitor : public ir_rvalue_visitor {
public:
   ir_structure_splitting_visitor(exec_list *vars)
   {
      this->variable_list = vars;
   }

   virtual ~ir_structure_splitting_visitor()
   {
   }

   virtual ir_visitor_status visit_leave(ir_assignment *);

   void split_deref(ir_dereference **deref);
   void handle_rvalue(ir_rvalue **rvalue);
   variable_entry *get_splitting_entry(ir_variable *var);

   exec_list *variable_list;
};

variable_entry *
ir_structure_splitting_visitor::get_splitting_entry(ir_variable *var)
{
   assert(var);

   if (!var->type->is_record())
      return NULL;

   foreach_iter(exec_list_iterator, iter, *this->variable_list) {
      variable_entry *entry = (variable_entry *)iter.get();
      if (entry->var == var) {
	 return entry;
      }
   }

   return NULL;
}

void
ir_structure_splitting_visitor::split_deref(ir_dereference **deref)
{
   if ((*deref)->ir_type != ir_type_dereference_record)
      return;

   ir_dereference_record *deref_record = (ir_dereference_record *)*deref;
   ir_dereference_variable *deref_var = deref_record->record->as_dereference_variable();
   if (!deref_var)
      return;

   variable_entry *entry = get_splitting_entry(deref_var->var);
   if (!entry)
      return;

   unsigned int i;
   for (i = 0; i < entry->var->type->length; i++) {
      if (strcmp(deref_record->field,
		 entry->var->type->fields.structure[i].name) == 0)
	 break;
   }
   assert(i != entry->var->type->length);

   *deref = new(entry->mem_ctx) ir_dereference_variable(entry->components[i]);
}

void
ir_structure_splitting_visitor::handle_rvalue(ir_rvalue **rvalue)
{
   if (!*rvalue)
      return;

   ir_dereference *deref = (*rvalue)->as_dereference();

   if (!deref)
      return;

   split_deref(&deref);
   *rvalue = deref;
}

ir_visitor_status
ir_structure_splitting_visitor::visit_leave(ir_assignment *ir)
{
   ir_dereference_variable *lhs_deref = ir->lhs->as_dereference_variable();
   ir_dereference_variable *rhs_deref = ir->rhs->as_dereference_variable();
   variable_entry *lhs_entry = lhs_deref ? get_splitting_entry(lhs_deref->var) : NULL;
   variable_entry *rhs_entry = rhs_deref ? get_splitting_entry(rhs_deref->var) : NULL;
   const glsl_type *type = ir->rhs->type;

   if ((lhs_entry || rhs_entry) && !ir->condition) {
      for (unsigned int i = 0; i < type->length; i++) {
	 ir_dereference *new_lhs, *new_rhs;
	 void *mem_ctx = lhs_entry ? lhs_entry->mem_ctx : rhs_entry->mem_ctx;

	 if (lhs_entry) {
	    new_lhs = new(mem_ctx) ir_dereference_variable(lhs_entry->components[i]);
	 } else {
	    new_lhs = new(mem_ctx)
	       ir_dereference_record(ir->lhs->clone(mem_ctx, NULL),
				     type->fields.structure[i].name);
	 }

	 if (rhs_entry) {
	    new_rhs = new(mem_ctx) ir_dereference_variable(rhs_entry->components[i]);
	 } else {
	    new_rhs = new(mem_ctx)
	       ir_dereference_record(ir->rhs->clone(mem_ctx, NULL),
				     type->fields.structure[i].name);
	 }

	 ir->insert_before(new(mem_ctx) ir_assignment(new_lhs,
						      new_rhs,
						      NULL));
      }
      ir->remove();
   } else {
      handle_rvalue(&ir->rhs);
      split_deref(&ir->lhs);
   }

   handle_rvalue(&ir->condition);

   return visit_continue;
}

} /* unnamed namespace */

bool
do_structure_splitting(exec_list *instructions)
{
   ir_structure_reference_visitor refs;

   visit_list_elements(&refs, instructions);

   /* Trim out variables we can't split. */
   foreach_iter(exec_list_iterator, iter, refs.variable_list) {
      variable_entry *entry = (variable_entry *)iter.get();

      if (debug) {
	 printf("structure %s@%p: decl %d, whole_access %d\n",
		entry->var->name, (void *) entry->var, entry->declaration,
		entry->whole_structure_access);
      }

      if (!entry->declaration || entry->whole_structure_access) {
	 entry->remove();
      }
   }

   if (refs.variable_list.is_empty())
      return false;

   void *mem_ctx = ralloc_context(NULL);

   /* Replace the decls of the structures to be split with their split
    * components.
    */
   foreach_iter(exec_list_iterator, iter, refs.variable_list) {
      variable_entry *entry = (variable_entry *)iter.get();
      const struct glsl_type *type = entry->var->type;

      entry->mem_ctx = ralloc_parent(entry->var);

      entry->components = ralloc_array(mem_ctx,
				       ir_variable *,
				       type->length);

      for (unsigned int i = 0; i < entry->var->type->length; i++) {
	 const char *name = ralloc_asprintf(mem_ctx, "%s_%s",
					    entry->var->name,
					    type->fields.structure[i].name);

	 entry->components[i] =
	    new(entry->mem_ctx) ir_variable(type->fields.structure[i].type,
					    name,
					    ir_var_temporary);
	 entry->var->insert_before(entry->components[i]);
      }

      entry->var->remove();
   }

   ir_structure_splitting_visitor split(&refs.variable_list);
   visit_list_elements(&split, instructions);

   ralloc_free(mem_ctx);

   return true;
}
<|endoftext|>


<commit_before>//////////////////////////////////////////////////////////////////////
// macros.cpp -- Process Macro Values
// Date: Fri Nov 29 21:40:13 2013
///////////////////////////////////////////////////////////////////////

#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <assert.h>

#include <algorithm>
#include <iostream>
#include <sstream>

#include "glue.hpp"
#include "utils.hpp"
#include "comp.hpp"
#include "config.hpp"

static void
comp_macro_set(s_config::s_macro_set& mset) {
	char sgenset[32];
	std::fstream fs;

	sprintf(sgenset,"%04d",mset.genset);

	std::cout << "Genset " << sgenset << " macro set\n";

	if ( !gcc_open(fs,mset.genset) )
		exit(3);

	fs 	<< "#include <stdio.h>\n\n";

	for ( auto it=mset.includes.begin(); it != mset.includes.end(); ++it ) {
		const std::string& incl_file = *it;

		fs << "#include <" << incl_file << ">\n";
	}

	fs	<< "\nstatic struct {\n"
		<< "\tconst char\t*name;\n"
		<< "\tlong\t\tvalue;\n"
		<< "} macros[] = {\n";

	for ( auto it=mset.macros.begin(); it != mset.macros.end(); ++it ) {
		const std::string& name = *it;

		fs	<< "#ifdef " << name << "\n"
			<< "\t{ \"" << name << "\", " << name << " },\n";

		auto ait = mset.alternates.find(name);
		if ( ait != mset.alternates.end() ) {
			const std::string& alt = mset.alternates[name];

			fs	<< "#else\n"
				<< "#ifdef " << alt << "\n"
				<< "\t{ \"" << name << "\", " << alt << " },\n"
				<< "#endif\n";
		}
		fs	<< "#endif\n";
	}

	fs	<< "\t{ 0, 0 }\n"
		<< "};\n"
		<< "\nint main() {\n"
		<< "\tint x;\n\n"
		<< "\tfor ( x=0; macros[x].name != 0; ++x )\n"
		<< "\t\tprintf(\"%s|%ld\\n\",macros[x].name,macros[x].value);\n"
		<< "\treturn 0;\n"
		<< "}\n";
	fs.close();

	if ( !gcc_compile(fs,mset.genset) )
		exit(2);

	std::string line;

	while ( fs.good() ) {
		std::getline(fs,line);
		if ( fs.eof() )
			break;

		size_t pos = line.find_first_of('|');
		assert(pos != std::string::npos);

		std::string name = line.substr(0,pos);
		std::string value = line.substr(pos+1);
		long mvalue = stol(value);

		mset.values[name] = mvalue;
	}

	fs.close();
}

void
comp_macros() {

	for ( auto it=config.macro_sets.begin(); it != config.macro_sets.end(); ++it ) {
		s_config::s_macro_set& mset = *it;
		comp_macro_set(mset);
	}
}

struct s_msort {
	std::string	name;
	long		value;
};

bool
sort_msort(const s_msort& left,const s_msort& right) {
	return left.value < right.value;
}

void
emit_macros() {

	for ( auto it=config.macro_sets.begin(); it != config.macro_sets.end(); ++it ) {
		const s_config::s_macro_set& mset = *it;
		char sgenset[32];
		std::fstream ads;

		sprintf(sgenset,"%04d",mset.genset);

		std::cout << "Genset " << sgenset << " emit macros\n";

		if ( !gcc_open(ads,mset.genset,".ads") )
			exit(3);

		std::vector<s_msort> svec;

		for ( auto mit=mset.values.begin(); mit != mset.values.end(); ++mit ) {
			const std::string& name = mit->first;
			const long value = mit->second;

			svec.push_back({ name, value });
		}

		std::sort(svec.begin(),svec.end(),sort_msort);

		for ( auto sit=svec.begin(); sit != svec.end(); ++sit ) {
			const s_msort& ent = *sit;
			std::stringstream s;

			s << ent.name << " :";

			ads << "   ";
			ads.width(20);
			ads << std::left << s.str() << " const ";

			if ( mset.type != "" )
				ads << mset.type << " ";
			ads << ":= ";

			char vbuf[128];
			sprintf(vbuf,mset.format.c_str(),ent.value);

			ads << vbuf << ";\n";
		}

		if ( mset.alternates.size() > 0 ) {
			ads << "\n";

			for ( auto ait=mset.alternates.begin(); ait != mset.alternates.end(); ++ait ) {
				const std::string& name = ait->first;
				const std::string& value = ait->second;
				std::stringstream s;

				if ( value[0] == '_' )
					continue;		// Not a legal Ada name

				s << value << " :";

				ads << "   ";
				ads.width(20);
				ads << std::left << s.str() << " const ";
				if ( mset.type != "" )
					ads << mset.type;
				ads << ":= " << name << ";\n";
			}
		}

		ads.close();
	}
}

// End macros.cpp
<commit_msg>Fixed const as constant as required by Ada<commit_after>//////////////////////////////////////////////////////////////////////
// macros.cpp -- Process Macro Values
// Date: Fri Nov 29 21:40:13 2013
///////////////////////////////////////////////////////////////////////

#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <assert.h>

#include <algorithm>
#include <iostream>
#include <sstream>

#include "glue.hpp"
#include "utils.hpp"
#include "comp.hpp"
#include "config.hpp"

static void
comp_macro_set(s_config::s_macro_set& mset) {
	char sgenset[32];
	std::fstream fs;

	sprintf(sgenset,"%04d",mset.genset);

	std::cout << "Genset " << sgenset << " macro set\n";

	if ( !gcc_open(fs,mset.genset) )
		exit(3);

	fs 	<< "#include <stdio.h>\n\n";

	for ( auto it=mset.includes.begin(); it != mset.includes.end(); ++it ) {
		const std::string& incl_file = *it;

		fs << "#include <" << incl_file << ">\n";
	}

	fs	<< "\nstatic struct {\n"
		<< "\tconst char\t*name;\n"
		<< "\tlong\t\tvalue;\n"
		<< "} macros[] = {\n";

	for ( auto it=mset.macros.begin(); it != mset.macros.end(); ++it ) {
		const std::string& name = *it;

		fs	<< "#ifdef " << name << "\n"
			<< "\t{ \"" << name << "\", " << name << " },\n";

		auto ait = mset.alternates.find(name);
		if ( ait != mset.alternates.end() ) {
			const std::string& alt = mset.alternates[name];

			fs	<< "#else\n"
				<< "#ifdef " << alt << "\n"
				<< "\t{ \"" << name << "\", " << alt << " },\n"
				<< "#endif\n";
		}
		fs	<< "#endif\n";
	}

	fs	<< "\t{ 0, 0 }\n"
		<< "};\n"
		<< "\nint main() {\n"
		<< "\tint x;\n\n"
		<< "\tfor ( x=0; macros[x].name != 0; ++x )\n"
		<< "\t\tprintf(\"%s|%ld\\n\",macros[x].name,macros[x].value);\n"
		<< "\treturn 0;\n"
		<< "}\n";
	fs.close();

	if ( !gcc_compile(fs,mset.genset) )
		exit(2);

	std::string line;

	while ( fs.good() ) {
		std::getline(fs,line);
		if ( fs.eof() )
			break;

		size_t pos = line.find_first_of('|');
		assert(pos != std::string::npos);

		std::string name = line.substr(0,pos);
		std::string value = line.substr(pos+1);
		long mvalue = stol(value);

		mset.values[name] = mvalue;
	}

	fs.close();
}

void
comp_macros() {

	for ( auto it=config.macro_sets.begin(); it != config.macro_sets.end(); ++it ) {
		s_config::s_macro_set& mset = *it;
		comp_macro_set(mset);
	}
}

struct s_msort {
	std::string	name;
	long		value;
};

bool
sort_msort(const s_msort& left,const s_msort& right) {
	return left.value < right.value;
}

void
emit_macros() {

	for ( auto it=config.macro_sets.begin(); it != config.macro_sets.end(); ++it ) {
		const s_config::s_macro_set& mset = *it;
		char sgenset[32];
		std::fstream ads;

		sprintf(sgenset,"%04d",mset.genset);

		std::cout << "Genset " << sgenset << " emit macros\n";

		if ( !gcc_open(ads,mset.genset,".ads") )
			exit(3);

		std::vector<s_msort> svec;

		for ( auto mit=mset.values.begin(); mit != mset.values.end(); ++mit ) {
			const std::string& name = mit->first;
			const long value = mit->second;

			svec.push_back({ name, value });
		}

		std::sort(svec.begin(),svec.end(),sort_msort);

		for ( auto sit=svec.begin(); sit != svec.end(); ++sit ) {
			const s_msort& ent = *sit;
			std::stringstream s;

			s << ent.name << " :";

			ads << "   ";
			ads.width(20);
			ads << std::left << s.str() << " constant ";

			if ( mset.type != "" )
				ads << mset.type << " ";
			ads << ":= ";

			char vbuf[128];
			sprintf(vbuf,mset.format.c_str(),ent.value);

			ads << vbuf << ";\n";
		}

		if ( mset.alternates.size() > 0 ) {
			ads << "\n";

			for ( auto ait=mset.alternates.begin(); ait != mset.alternates.end(); ++ait ) {
				const std::string& name = ait->first;
				const std::string& value = ait->second;
				std::stringstream s;

				if ( value[0] == '_' )
					continue;		// Not a legal Ada name

				s << value << " :";

				ads << "   ";
				ads.width(20);
				ads << std::left << s.str() << " constant ";
				if ( mset.type != "" )
					ads << mset.type;
				ads << ":= " << name << ";\n";
			}
		}

		ads.close();
	}
}

// End macros.cpp
<|endoftext|>


<commit_before>/*

  Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4

  Copyright (C) 2018 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>

*/

/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#include "QSvgRendererSlots.h"

static QSvgRendererSlots * s = NULL;

QSvgRendererSlots::QSvgRendererSlots(QObject *parent) : QObject(parent)
{
}

QSvgRendererSlots::~QSvgRendererSlots()
{
}
void QSvgRendererSlots::repaintNeeded()
{
  QObject *object = qobject_cast<QObject *>(sender());
  PHB_ITEM cb = Signals_return_codeblock( object, "repaintNeeded()" );
  if( cb )
  {
    PHB_ITEM psender = Signals_return_qobject ( object, "QSVGRENDERER" );
    hb_vmEvalBlockV( (PHB_ITEM) cb, 1, psender );
    hb_itemRelease( psender );
  }
}

void QSvgRendererSlots_connect_signal ( const QString & signal, const QString & slot )
{
  if( s == NULL )
  {
    s = new QSvgRendererSlots( QCoreApplication::instance() );
  }

  hb_retl( Signals_connection_disconnection( s, signal, slot ) );
}
<commit_msg>QtSvg: module updated<commit_after>/*

  Qt4xHb - Bindings libraries for Harbour/xHarbour and Qt Framework 4

  Copyright (C) 2018 Marcos Antonio Gambeta <marcosgambeta AT outlook DOT com>

*/

/*
  DO NOT EDIT THIS FILE - the content was created using a source code generator
*/

#include "QSvgRendererSlots.h"

static QSvgRendererSlots * s = NULL;

QSvgRendererSlots::QSvgRendererSlots(QObject *parent) : QObject(parent)
{
}

QSvgRendererSlots::~QSvgRendererSlots()
{
}
void QSvgRendererSlots::repaintNeeded()
{
  QObject *object = qobject_cast<QObject *>(sender());
  PHB_ITEM cb = Signals_return_codeblock( object, "repaintNeeded()" );
  if( cb )
  {
    PHB_ITEM psender = Signals_return_qobject ( (QObject *) object, "QSVGRENDERER" );
    hb_vmEvalBlockV( (PHB_ITEM) cb, 1, psender );
    hb_itemRelease( psender );
  }
}

void QSvgRendererSlots_connect_signal ( const QString & signal, const QString & slot )
{
  if( s == NULL )
  {
    s = new QSvgRendererSlots( QCoreApplication::instance() );
  }

  hb_retl( Signals_connection_disconnection( s, signal, slot ) );
}
<|endoftext|>


<commit_before>// $Id: EnergyProcessor_test.C,v 1.2 2001/07/15 17:32:39 amoll Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////

// insert includes here
#include <BALL/ENERGY/energyProcessor.h>

///////////////////////////

START_TEST(EnergyProcessor", "$Id: EnergyProcessor_test.C,v 1.2 2001/07/15 17:32:39 amoll Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

///  insert tests for each member function here
///

CHECK(EnergyProcessor::EnergyProcessor())
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::EnergyProcessor(const EnergyProcessor& proc))
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::~EnergyProcessor())
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::destroy())
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::clear())
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::set(const EnergyProcessor& proc))
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::EnergyProcessor& operator = (const EnergyProcessor& proc))
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::start())
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::Processor::Result operator () (BaseFragment& fragment))
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::getEnergy() const )
  //BAUSTELLE
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<commit_msg>fixed: removed typo<commit_after>// $Id: EnergyProcessor_test.C,v 1.3 2001/07/15 21:06:32 oliver Exp $
#include <BALL/CONCEPT/classTest.h>

///////////////////////////

// insert includes here
#include <BALL/ENERGY/energyProcessor.h>

///////////////////////////

START_TEST(EnergyProcessor, "$Id: EnergyProcessor_test.C,v 1.3 2001/07/15 21:06:32 oliver Exp $")

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////

using namespace BALL;

///  insert tests for each member function here
///

CHECK(EnergyProcessor::EnergyProcessor())
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::EnergyProcessor(const EnergyProcessor& proc))
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::~EnergyProcessor())
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::destroy())
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::clear())
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::set(const EnergyProcessor& proc))
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::EnergyProcessor& operator = (const EnergyProcessor& proc))
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::start())
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::Processor::Result operator () (BaseFragment& fragment))
  //BAUSTELLE
RESULT

CHECK(EnergyProcessor::getEnergy() const )
  //BAUSTELLE
RESULT

/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
END_TEST
<|endoftext|>


<commit_before>/*
 * Desktop.cpp
 *
 * This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns)
 * See "LICENSE.txt" for license information.
 */

#include <LLGL/Desktop.h>

namespace LLGL
{

namespace Desktop
{

LLGL_EXPORT Extent2D GetResolution()
{
    return { 1920, 1080 };//!!!
}

LLGL_EXPORT int GetColorDepth()
{
    return 24;//!!!
}

LLGL_EXPORT bool SetVideoMode(const VideoModeDescriptor& videoMode)
{
    return false;
}

LLGL_EXPORT bool ResetVideoMode()
{
    return false;
}

} // /namespace Desktop

} // /namespace LLGL

// ================================================================================
<commit_msg>Implemented 'Desktop::GetResolution' function on Linux port.<commit_after>/*
 * Desktop.cpp
 *
 * This file is part of the "LLGL" project (Copyright (c) 2015 by Lukas Hermanns)
 * See "LICENSE.txt" for license information.
 */

#include <LLGL/Desktop.h>
#include <X11/Xlib.h>

namespace LLGL
{

namespace Desktop
{

LLGL_EXPORT Extent2D GetResolution()
{
    if (auto dpy = XOpenDisplay(nullptr))
    {
        if (auto scr = DefaultScreenOfDisplay(dpy))
        {
            return
            {
                static_cast<std::uint32_t>(scr->width),
                static_cast<std::uint32_t>(scr->height)
            };
        }
        XCloseDisplay(dpy);
    }
    return { 0u, 0u };
}

LLGL_EXPORT int GetColorDepth()
{
    return 24;
}

LLGL_EXPORT bool SetVideoMode(const VideoModeDescriptor& videoMode)
{
    return false;
}

LLGL_EXPORT bool ResetVideoMode()
{
    return false;
}

} // /namespace Desktop

} // /namespace LLGL

// ================================================================================
<|endoftext|>


<commit_before>// Copyright 2014 Toggl Desktop developers.

#include "./timerwidget.h"
#include "./ui_timerwidget.h"

#include <QApplication>  // NOLINT

#include "./autocompleteview.h"
#include "./timeentryview.h"
#include "./toggl.h"

TimerWidget::TimerWidget(QWidget *parent) : QWidget(parent),
ui(new Ui::TimerWidget),
timer(new QTimer(this)),
duration(0),
timeEntryAutocompleteNeedsUpdate(false) {
    ui->setupUi(this);

    connect(TogglApi::instance, SIGNAL(displayStoppedTimerState()),
            this, SLOT(displayStoppedTimerState()));

    connect(TogglApi::instance, SIGNAL(displayRunningTimerState(TimeEntryView*)),  // NOLINT
            this, SLOT(displayRunningTimerState(TimeEntryView*)));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayMinitimerAutocomplete(QVector<AutocompleteView*>)),  // NOLINT
            this, SLOT(displayMinitimerAutocomplete(QVector<AutocompleteView*>)));  // NOLINT

    connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)),
            this, SLOT(focusChanged(QWidget*, QWidget*)));

    connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));

    connect(ui->description->lineEdit(), SIGNAL(returnPressed()),
            this, SLOT(descriptionReturnPressed()));

    descriptionPlaceholder = "What are you doing?";
}

TimerWidget::~TimerWidget() {
    timer->stop();

    delete ui;
}

void TimerWidget::descriptionReturnPressed() {
    start();
}

void TimerWidget::focusChanged(QWidget *old, QWidget *now) {
    if (old == ui->description) {
        if (ui->description->currentText().length() == 0) {
            ui->description->setEditText(descriptionPlaceholder);
        }
        if (timeEntryAutocompleteNeedsUpdate) {
            displayMinitimerAutocomplete(timeEntryAutocompleteUpdate);
        }
    }
    if (now == ui->description &&
            ui->description->currentText() == descriptionPlaceholder) {
        ui->description->setEditText("");
    }
}

void TimerWidget::displayRunningTimerState(
    TimeEntryView *te) {
    ui->start->setText("Stop");
    ui->start->setStyleSheet(
        "background-color: #e20000; color:'white'; font-weight: bold;");

    ui->description->setEditText(te->Description);
    ui->description->setEnabled(false);

    ui->duration->setText(te->Duration);
    ui->duration->setEnabled(false);

    ui->project->setText(te->ProjectAndTaskLabel);

    duration = te->DurationInSeconds;

    disconnect(this, SLOT(start()));
    disconnect(this, SLOT(stop()));

    connect(this, SIGNAL(buttonClicked()), this, SLOT(stop()));

    timer->start(1000);
}

void TimerWidget::displayStoppedTimerState() {
    ui->start->setText("Start");
    ui->start->setStyleSheet(
        "background-color: #47bc00; color:'white'; font-weight: bold;");

    if (!ui->description->hasFocus()) {
        ui->description->setEditText(descriptionPlaceholder);
    }
    ui->description->setEnabled(true);

    if (!ui->duration->hasFocus()) {
        ui->duration->setText("");
    }
    ui->duration->setEnabled(true);

    ui->project->setText("");

    duration = 0;

    disconnect(this, SLOT(start()));
    disconnect(this, SLOT(stop()));

    connect(this, SIGNAL(buttonClicked()), this, SLOT(start()));

    timer->stop();
}

void TimerWidget::on_start_clicked() {
    emit buttonClicked();
}

void TimerWidget::start() {
    uint64_t task_id(0);
    uint64_t project_id(0);

    QVariant data = ui->description->currentData();
    if (data.canConvert<AutocompleteView *>()) {
        AutocompleteView *view = data.value<AutocompleteView *>();
        task_id = view->TaskID;
        project_id = view->ProjectID;
    }

    QString description = ui->description->currentText();
    if (description == descriptionPlaceholder) {
        description = "";
    }

    TogglApi::instance->start(description,
                              ui->duration->text(),
                              task_id,
                              project_id);
}

void TimerWidget::stop() {
    TogglApi::instance->stop();
}

void TimerWidget::displayMinitimerAutocomplete(
    QVector<AutocompleteView *> list) {
    timeEntryAutocompleteUpdate = list;
    timeEntryAutocompleteNeedsUpdate = true;
    if (ui->description->hasFocus()) {
        return;
    }
    QString currentText = ui->description->currentText();
    ui->description->clear();
    ui->description->addItem("");
    foreach(AutocompleteView *view, timeEntryAutocompleteUpdate) {
        ui->description->addItem(view->Text, QVariant::fromValue(view));
    }
    timeEntryAutocompleteNeedsUpdate = false;
    ui->description->setEditText(currentText);
}

void TimerWidget::timeout() {
    if (!isVisible()) {
        return;
    }
    if (duration >= 0) {
        return;
    }
    ui->duration->setText(TogglApi::formatDurationInSecondsHHMMSS(duration));
}

void TimerWidget::on_description_currentIndexChanged(int index) {
    QVariant data = ui->description->currentData();
    if (data.canConvert<AutocompleteView *>()) {
        AutocompleteView *view = data.value<AutocompleteView *>();
        ui->description->setEditText(view->Description);
        ui->project->setText(view->ProjectAndTaskLabel);
    }
}

void TimerWidget::mousePressEvent(QMouseEvent *event) {
    TogglApi::instance->editRunningTimeEntry("");
    QWidget::mousePressEvent(event);
}

void TimerWidget::on_duration_returnPressed() {
    start();
}
<commit_msg>Added tooltips to timer (linux)<commit_after>// Copyright 2014 Toggl Desktop developers.

#include "./timerwidget.h"
#include "./ui_timerwidget.h"

#include <QApplication>  // NOLINT

#include "./autocompleteview.h"
#include "./timeentryview.h"
#include "./toggl.h"

TimerWidget::TimerWidget(QWidget *parent) : QWidget(parent),
ui(new Ui::TimerWidget),
timer(new QTimer(this)),
duration(0),
timeEntryAutocompleteNeedsUpdate(false) {
    ui->setupUi(this);

    connect(TogglApi::instance, SIGNAL(displayStoppedTimerState()),
            this, SLOT(displayStoppedTimerState()));

    connect(TogglApi::instance, SIGNAL(displayRunningTimerState(TimeEntryView*)),  // NOLINT
            this, SLOT(displayRunningTimerState(TimeEntryView*)));  // NOLINT

    connect(TogglApi::instance, SIGNAL(displayMinitimerAutocomplete(QVector<AutocompleteView*>)),  // NOLINT
            this, SLOT(displayMinitimerAutocomplete(QVector<AutocompleteView*>)));  // NOLINT

    connect(qApp, SIGNAL(focusChanged(QWidget*, QWidget*)),
            this, SLOT(focusChanged(QWidget*, QWidget*)));

    connect(timer, SIGNAL(timeout()), this, SLOT(timeout()));

    connect(ui->description->lineEdit(), SIGNAL(returnPressed()),
            this, SLOT(descriptionReturnPressed()));

    descriptionPlaceholder = "What are you doing?";
}

TimerWidget::~TimerWidget() {
    timer->stop();

    delete ui;
}

void TimerWidget::descriptionReturnPressed() {
    start();
}

void TimerWidget::focusChanged(QWidget *old, QWidget *now) {
    if (old == ui->description) {
        if (ui->description->currentText().length() == 0) {
            ui->description->setEditText(descriptionPlaceholder);
        }
        if (timeEntryAutocompleteNeedsUpdate) {
            displayMinitimerAutocomplete(timeEntryAutocompleteUpdate);
        }
    }
    if (now == ui->description &&
            ui->description->currentText() == descriptionPlaceholder) {
        ui->description->setEditText("");
    }
}

void TimerWidget::displayRunningTimerState(
    TimeEntryView *te) {
    ui->start->setText("Stop");
    ui->start->setStyleSheet(
        "background-color: #e20000; color:'white'; font-weight: bold;");

    ui->description->setEditText(te->Description);
    ui->description->setEnabled(false);

    ui->duration->setText(te->Duration);
    ui->duration->setEnabled(false);

    ui->project->setText(te->ProjectAndTaskLabel);

    duration = te->DurationInSeconds;

    if(te->Description.length()>0) {
        ui->description->setToolTip(
            QString("
"+te->Description+"
"));
    }
    if(te->ProjectAndTaskLabel.length()>0) {
        ui->project->setToolTip(
            QString("
"+te->ProjectAndTaskLabel+"
"));
    }

    disconnect(this, SLOT(start()));
    disconnect(this, SLOT(stop()));

    connect(this, SIGNAL(buttonClicked()), this, SLOT(stop()));

    timer->start(1000);
}

void TimerWidget::displayStoppedTimerState() {
    ui->start->setText("Start");
    ui->start->setStyleSheet(
        "background-color: #47bc00; color:'white'; font-weight: bold;");

    if (!ui->description->hasFocus()) {
        ui->description->setEditText(descriptionPlaceholder);
    }
    ui->description->setEnabled(true);

    if (!ui->duration->hasFocus()) {
        ui->duration->setText("");
    }
    ui->duration->setEnabled(true);

    ui->project->setText("");

    duration = 0;

    disconnect(this, SLOT(start()));
    disconnect(this, SLOT(stop()));

    connect(this, SIGNAL(buttonClicked()), this, SLOT(start()));

    timer->stop();
}

void TimerWidget::on_start_clicked() {
    emit buttonClicked();
}

void TimerWidget::start() {
    uint64_t task_id(0);
    uint64_t project_id(0);

    QVariant data = ui->description->currentData();
    if (data.canConvert<AutocompleteView *>()) {
        AutocompleteView *view = data.value<AutocompleteView *>();
        task_id = view->TaskID;
        project_id = view->ProjectID;
    }

    QString description = ui->description->currentText();
    if (description == descriptionPlaceholder) {
        description = "";
    }

    TogglApi::instance->start(description,
                              ui->duration->text(),
                              task_id,
                              project_id);
}

void TimerWidget::stop() {
    TogglApi::instance->stop();
}

void TimerWidget::displayMinitimerAutocomplete(
    QVector<AutocompleteView *> list) {
    timeEntryAutocompleteUpdate = list;
    timeEntryAutocompleteNeedsUpdate = true;
    if (ui->description->hasFocus()) {
        return;
    }
    QString currentText = ui->description->currentText();
    ui->description->clear();
    ui->description->addItem("");
    foreach(AutocompleteView *view, timeEntryAutocompleteUpdate) {
        ui->description->addItem(view->Text, QVariant::fromValue(view));
    }
    timeEntryAutocompleteNeedsUpdate = false;
    ui->description->setEditText(currentText);
}

void TimerWidget::timeout() {
    if (!isVisible()) {
        return;
    }
    if (duration >= 0) {
        return;
    }
    ui->duration->setText(TogglApi::formatDurationInSecondsHHMMSS(duration));
}

void TimerWidget::on_description_currentIndexChanged(int index) {
    QVariant data = ui->description->currentData();
    if (data.canConvert<AutocompleteView *>()) {
        AutocompleteView *view = data.value<AutocompleteView *>();
        ui->description->setEditText(view->Description);
        ui->project->setText(view->ProjectAndTaskLabel);
    }
}

void TimerWidget::mousePressEvent(QMouseEvent *event) {
    TogglApi::instance->editRunningTimeEntry("");
    QWidget::mousePressEvent(event);
}

void TimerWidget::on_duration_returnPressed() {
    start();
}
<|endoftext|>


<commit_before>#include "imu_tortuga.h"
//written by Jeremy Weed

ImuTortugaNode::ImuTortugaNode(std::shared_ptr<ros::NodeHandle> n, int rate, std::string name, std::string device) : RamNode(n){
	// JW: There are a lot of debug/error messages here, I'm not sure
	// if we want to leave them in or not
	ROS_DEBUG("beginning constructor");

	this->name = name;

	// JW: do I need this here?
	ros::Rate loop_rate(rate);

	imuPub = n->advertise<sensor_msgs::Imu>("qubo/imu/" + name, 1000);
	tempPub = n->advertise<std_msgs::Float64MultiArray>("qubo/imu/"+ name + "/temperature", 1000);
	quaternionPub = n->advertise<geometry_msgs::Quaternion>("qubo/imu/" + name + "/quaternion", 1000);
	magnetsPub = n->advertise<sensor_msgs::MagneticField>("qubo/imu/" + name + "/magnetometer", 1000);

	fd = openIMU(device.c_str());
	ROS_DEBUG("fd found: %d on %s", fd, device);
	if(fd <= 0){
            ROS_ERROR("(%s) Unable to open IMU board at: %s", name.c_str(), device.c_str());
	}

	ROS_DEBUG("end of publishers on %s", device);
	temperature.layout.dim.push_back(std_msgs::MultiArrayDimension());
	temperature.layout.data_offset = 0;
	temperature.layout.dim[0].label = "IMU Temperature";
	temperature.layout.dim[0].size = 3;
	temperature.layout.dim[0].stride = 3;

	ROS_DEBUG("finished constructor on %s", device);
}

ImuTortugaNode::~ImuTortugaNode(){
	close(fd);
}

void ImuTortugaNode::update(){
	ROS_DEBUG("updating imu method on %s", device);

	static double roll = 0, pitch = 0, yaw = 0, time_last = 0;
	ROS_DEBUG("does read hang?");
	checkError(readIMUData(fd, data.get()));
	ROS_DEBUG("nope");
	double time_current = ros::Time::now().toSec();

	msg.header.stamp = ros::Time::now();
	msg.header.seq = ++id;
	msg.header.frame_id = "0";

	msg.orientation_covariance[0] = -1;

	msg.linear_acceleration_covariance[0] = -1;

	// Our IMU returns values in G's, but we should be publishing in m/s^2
	msg.linear_acceleration.x = data->accelX * G_IN_MS2;
	msg.linear_acceleration.y = data->accelY * G_IN_MS2;
	msg.linear_acceleration.z = data->accelZ * G_IN_MS2;

	msg.angular_velocity_covariance[0] = -1;

	msg.angular_velocity.x = data->gyroX;
	msg.angular_velocity.y = data->gyroY;
	msg.angular_velocity.z = data->gyroZ;

	ROS_DEBUG("end of imu read on %s", device);

	//temperature data
	//its a float 64 array, in x, y, z order

	temperature.data[0] = data->tempX;
	temperature.data[1] = data->tempY;
	temperature.data[2] = data->tempZ;

	//magnetometer data
	mag.header.stamp = ros::Time::now();
	mag.header.seq = id;
	mag.header.frame_id = "0";

	mag.magnetic_field.x = data->magX;
	mag.magnetic_field.y = data->magY;
	mag.magnetic_field.z = data->magZ;

	double time_delta = time_current - time_last;

/*~~~This is gross and I don't like it~~~*/

	//normalize about 2pi radians
	roll += fmod(data->gyroX / time_delta, 2 * M_PI);
	pitch += fmod(data->gyroY / time_delta, 2 * M_PI);
	yaw += fmod(data->gyroZ / time_delta, 2 * M_PI);

	//quaternion - probably
	quaternion = tf::createQuaternionMsgFromRollPitchYaw(roll, pitch, yaw);

    // publish data
	imuPub.publish(msg);
	tempPub.publish(temperature);
	quaternionPub.publish(quaternion);
	magnetsPub.publish(mag);

	ros::spinOnce();
}
<commit_msg>modified and removed some debugging messages so I can build<commit_after>#include "imu_tortuga.h"
//written by Jeremy Weed

ImuTortugaNode::ImuTortugaNode(std::shared_ptr<ros::NodeHandle> n, int rate, std::string name, std::string device) : RamNode(n){
	// JW: There are a lot of debug/error messages here, I'm not sure
	// if we want to leave them in or not
	ROS_DEBUG("beginning constructor");

	this->name = name;

	// JW: do I need this here?
	ros::Rate loop_rate(rate);

	imuPub = n->advertise<sensor_msgs::Imu>("qubo/imu/" + name, 1000);
	tempPub = n->advertise<std_msgs::Float64MultiArray>("qubo/imu/"+ name + "/temperature", 1000);
	quaternionPub = n->advertise<geometry_msgs::Quaternion>("qubo/imu/" + name + "/quaternion", 1000);
	magnetsPub = n->advertise<sensor_msgs::MagneticField>("qubo/imu/" + name + "/magnetometer", 1000);

	fd = openIMU(device.c_str());
	ROS_DEBUG("fd found: %d on %s", fd, device.c_str());
	if(fd <= 0){
            ROS_ERROR("(%s) Unable to open IMU board at: %s", name.c_str(), device.c_str());
	}

	ROS_DEBUG("end of publishers on %s", device.c_str());
	temperature.layout.dim.push_back(std_msgs::MultiArrayDimension());
	temperature.layout.data_offset = 0;
	temperature.layout.dim[0].label = "IMU Temperature";
	temperature.layout.dim[0].size = 3;
	temperature.layout.dim[0].stride = 3;

	ROS_DEBUG("finished constructor on %s", device.c_str());
}

ImuTortugaNode::~ImuTortugaNode(){
	close(fd);
}

void ImuTortugaNode::update(){
	//ROS_DEBUG("updating imu method on %s", device.c_str());

	static double roll = 0, pitch = 0, yaw = 0, time_last = 0;
	ROS_DEBUG("does read hang?");
	checkError(readIMUData(fd, data.get()));
	ROS_DEBUG("nope");
	double time_current = ros::Time::now().toSec();

	msg.header.stamp = ros::Time::now();
	msg.header.seq = ++id;
	msg.header.frame_id = "0";

	msg.orientation_covariance[0] = -1;

	msg.linear_acceleration_covariance[0] = -1;

	// Our IMU returns values in G's, but we should be publishing in m/s^2
	msg.linear_acceleration.x = data->accelX * G_IN_MS2;
	msg.linear_acceleration.y = data->accelY * G_IN_MS2;
	msg.linear_acceleration.z = data->accelZ * G_IN_MS2;

	msg.angular_velocity_covariance[0] = -1;

	msg.angular_velocity.x = data->gyroX;
	msg.angular_velocity.y = data->gyroY;
	msg.angular_velocity.z = data->gyroZ;

	//ROS_DEBUG("end of imu read on %s", device.c_str());

	//temperature data
	//its a float 64 array, in x, y, z order

	temperature.data[0] = data->tempX;
	temperature.data[1] = data->tempY;
	temperature.data[2] = data->tempZ;

	//magnetometer data
	mag.header.stamp = ros::Time::now();
	mag.header.seq = id;
	mag.header.frame_id = "0";

	mag.magnetic_field.x = data->magX;
	mag.magnetic_field.y = data->magY;
	mag.magnetic_field.z = data->magZ;

	double time_delta = time_current - time_last;

/*~~~This is gross and I don't like it~~~*/

	//normalize about 2pi radians
	roll += fmod(data->gyroX / time_delta, 2 * M_PI);
	pitch += fmod(data->gyroY / time_delta, 2 * M_PI);
	yaw += fmod(data->gyroZ / time_delta, 2 * M_PI);

	//quaternion - probably
	quaternion = tf::createQuaternionMsgFromRollPitchYaw(roll, pitch, yaw);

    // publish data
	imuPub.publish(msg);
	tempPub.publish(temperature);
	quaternionPub.publish(quaternion);
	magnetsPub.publish(mag);

	ros::spinOnce();
}
<|endoftext|>


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

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

  =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbImageToLuminanceImageFilter.h"
#include "otbLuminanceToReflectanceImageFilter.h"
#include "otbReflectanceToSurfaceReflectanceImageFilter.h"
#include "otbMultiplyByScalarImageFilter.h"

namespace otb
{

  enum
    {
      Level_TOA,
      Level_TOC
    };

  enum
    {
      Aerosol_NoAerosol,
      Aerosol_Continental,
      Aerosol_Maritime,
      Aerosol_Urban,
      Aerosol_Desertic,
    };

  namespace Wrapper
  {

    class OpticalCalibration : public Application
    {

    public:
      /** Standard class typedefs. */
      typedef OpticalCalibration            Self;
      typedef Application                   Superclass;
      typedef itk::SmartPointer<Self>       Pointer;
      typedef itk::SmartPointer<const Self> ConstPointer;

      /** Standard macro */
      itkNewMacro(Self);

      itkTypeMacro(OpticalCalibration, Application);

      typedef ImageToLuminanceImageFilter<UInt16VectorImageType,
                                          DoubleVectorImageType>              ImageToLuminanceImageFilterType;

      typedef LuminanceToReflectanceImageFilter<DoubleVectorImageType,
                                                DoubleVectorImageType>        LuminanceToReflectanceImageFilterType;

      typedef otb::MultiplyByScalarImageFilter<DoubleVectorImageType,
                                               DoubleVectorImageType>         ScaleFilterType;

      typedef ReflectanceToSurfaceReflectanceImageFilter<DoubleVectorImageType,
                                                         DoubleVectorImageType>         ReflectanceToSurfaceReflectanceImageFilterType;
      typedef ReflectanceToSurfaceReflectanceImageFilterType::FilterFunctionValuesType  FilterFunctionValuesType;
      typedef FilterFunctionValuesType::ValuesVectorType                                ValuesVectorType;
      typedef AtmosphericCorrectionParameters                                           AtmosphericCorrectionParametersType;
      typedef AtmosphericCorrectionParametersType::AerosolModelType                     AerosolModelType;

    private:
      void DoInit()
      {
        SetName("OpticalCalibration");
        SetDescription("Perform optical calibration TOA/TOC (Top Of Atmosphere/Top Of Canopy). Supported sensors: QuickBird, Ikonos, WorldView2, Formosat, Spot5");
        // Documentation
        SetDocName("Optical calibration");
        SetDocLongDescription("The application allows to convert pixel values from DN (for Digital Numbers) to physically interpretable and comparable values. Calibrated values are called surface reflectivity and its values lie in the range [0, 1].\nThe first level is called Top Of Atmosphere (TOA) reflectivity. It takes into account the sensor gain, sensor spectral response and the solar illumination.\nThe second level is called Top Of Canopy (TOC) reflectivity. In addition to sensor gain and solar illumination, it takes into account the optical thickness of the atmosphere, the atmospheric pressure, the water vapor amount, the ozone amount, as well as the composition and amount of aerosol gasses.\nIt is also possible to indicate an AERONET file which contains atmospheric parameters (version 1 and version 2 of Aeronet file are supported.");
        SetDocLimitations("None");
        SetDocAuthors("OTB-Team");
        SetDocSeeAlso("The OTB CookBook");

        AddDocTag(Tags::Calibration);

        AddParameter(ParameterType_InputImage,  "in",  "Input");
        SetParameterDescription("in", "Input image filename (values in DN)");

        AddParameter(ParameterType_OutputImage, "out", "Output");
        SetParameterDescription("out","Output calibrated image filename");

        AddRAMParameter();

        AddParameter(ParameterType_Choice,   "level", "Calibration Level");
        AddChoice("level.toa",     "TOA : Top Of Atmosphere");
        AddChoice("level.toc",     "TOC : Top Of Canopy (EXPERIMENTAL)");
        SetParameterString("level", "toa");

        AddParameter(ParameterType_Empty, "milli", "Convert to milli reflectance");
        SetParameterDescription("milli", "Flag to use milli-reflectance instead of reflectance.\n"
                                "This allows to save the image with integer pixel type (in the range [0, 1000]  instead of floating point in the range [0, 1]. In order to do that, use this option and set the output pixel type (-out filename uint16 for example)");
        DisableParameter("milli");
        MandatoryOff("milli");

        AddParameter(ParameterType_InputFilename, "rsr", "Relative Spectral Response File");
        std::ostringstream oss;
        oss << "Sensor relative spectral response file"<<std::endl;
        oss << "By default the application gets these informations in the metadata";
        SetParameterDescription("rsr", oss.str());
        MandatoryOff("rsr");

        AddParameter(ParameterType_Group,"atmo","Atmospheric parameters");
        SetParameterDescription("atmo","This group allows to set the atmospheric parameters.");
        AddParameter(ParameterType_Choice,   "atmo.aerosol", "Aerosol Model");
        AddChoice("atmo.aerosol.noaersol",    "No Aerosol Model");
        AddChoice("atmo.aerosol.continental", "Continental");
        AddChoice("atmo.aerosol.maritime",    "Maritime");
        AddChoice("atmo.aerosol.urban",       "Urban");
        AddChoice("atmo.aerosol.desertic",    "Desertic");

        AddParameter(ParameterType_Float, "atmo.oz",   "Ozone Amount");
        SetParameterDescription("atmo.oz", "Ozone Amount");

        AddParameter(ParameterType_Float, "atmo.wa",   "Water Vapor Amount");
        SetParameterDescription("atmo.wa", "Water Vapor Amount (in saturation fraction of water)");

        AddParameter(ParameterType_Float, "atmo.pressure", "Atmospheric Pressure");
        SetParameterDescription("atmo.pressure", "Atmospheric Pressure (in hPa)");

        AddParameter(ParameterType_Float, "atmo.opt",  "Aerosol Optical Thickness");
        SetParameterDescription("atmo.opt", "Aerosol Optical Thickness");

        SetDefaultParameterFloat("atmo.oz", 0.);
        SetDefaultParameterFloat("atmo.wa",  2.5);
        SetDefaultParameterFloat("atmo.pressure", 1030.);

        SetDefaultParameterFloat("atmo.opt", 0.2);
        MandatoryOff("atmo.oz");
        MandatoryOff("atmo.wa");
        MandatoryOff("atmo.pressure");
        MandatoryOff("atmo.opt");

        AddParameter(ParameterType_InputFilename, "atmo.aeronet", "Aeronet File");
        SetParameterDescription("atmo.aeronet","Aeronet file containing atmospheric parameters");
        MandatoryOff("atmo.aeronet");

        // Doc example parameter settings
        SetDocExampleParameterValue("in", "QB_1_ortho.tif");
        SetDocExampleParameterValue("level", "toa");
        SetDocExampleParameterValue("out", "OpticalCalibration.tif");
      }

      void DoUpdateParameters()
      {
        // Nothing to update
      }

      void DoExecute()
      {
        UInt16VectorImageType::Pointer inImage = GetParameterUInt16VectorImage("in");

        //Check if valid metadata informations are available to compute ImageToLuminance and LuminanceToReflectance
        itk::MetaDataDictionary             dict = inImage->GetMetaDataDictionary();
        OpticalImageMetadataInterface::Pointer lImageMetadataInterface = OpticalImageMetadataInterfaceFactory::CreateIMI(dict);

        // Test if needed data are available : an exception will be thrown
        // if one the following Get* return failure. the exception is then
        // caught in the Wrapper::Application class which redirect it to
        // the logger
        // ImageToLuminance
        lImageMetadataInterface->GetPhysicalGain();
        lImageMetadataInterface->GetPhysicalBias();

        // LuminanceToReflectance
        lImageMetadataInterface->GetDay();
        lImageMetadataInterface->GetMonth();

        lImageMetadataInterface->GetSolarIrradiance();
        lImageMetadataInterface->GetSunElevation();

        m_ImageToLuminanceFilter                = ImageToLuminanceImageFilterType::New();
        m_LuminanceToReflectanceFilter          = LuminanceToReflectanceImageFilterType::New();
        m_ReflectanceToSurfaceReflectanceFilter = ReflectanceToSurfaceReflectanceImageFilterType::New();

        m_ImageToLuminanceFilter->SetInput(inImage);
        m_LuminanceToReflectanceFilter->SetInput(m_ImageToLuminanceFilter->GetOutput());
        m_ReflectanceToSurfaceReflectanceFilter->SetInput(m_LuminanceToReflectanceFilter->GetOutput());

        m_ScaleFilter = ScaleFilterType::New();
        m_ScaleFilter->InPlaceOn();

        switch ( GetParameterInt("level") )
          {
          case Level_TOA:
            {
              m_LuminanceToReflectanceFilter->UpdateOutputInformation();
              m_ScaleFilter->SetInput(m_LuminanceToReflectanceFilter->GetOutput());
            }
            break;
          case Level_TOC:
            {
              m_ReflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(false);
              m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(true);
              m_ReflectanceToSurfaceReflectanceFilter->UpdateOutputInformation();
              m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false);

              m_AtmosphericParam = m_ReflectanceToSurfaceReflectanceFilter->GetCorrectionParameters();
              //AerosolModelType aeroMod = AtmosphericCorrectionParametersType::NO_AEROSOL;

              switch ( GetParameterInt("atmo.aerosol") )
                {
                case Aerosol_Desertic:
                  {
                    // Aerosol_Desertic correspond to 4 in the enum but actually in
                    // the class atmosphericParam it is known as parameter 5
                    m_AtmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(5));
                  }
                  break;
                default:
                  {
                    m_AtmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(GetParameterInt("atmo.aerosol")));
                  }
                  break;
                }
              // Set the atmospheric param
              m_AtmosphericParam->SetOzoneAmount(GetParameterFloat("atmo.oz"));
              m_AtmosphericParam->SetWaterVaporAmount(GetParameterFloat("atmo.wa"));
              m_AtmosphericParam->SetAtmosphericPressure(GetParameterFloat("atmo.pressure"));
              m_AtmosphericParam->SetAerosolOptical(GetParameterFloat("atmo.opt"));

              // Relative Spectral Response File
              if (IsParameterEnabled("rsr"))
                {
                  m_ReflectanceToSurfaceReflectanceFilter->SetFilterFunctionValuesFileName(GetParameterString("rsr"));
                }
              else
                {
                  m_ReflectanceToSurfaceReflectanceFilter->SetFilterFunctionCoef(lImageMetadataInterface->GetSpectralSensitivity());
                }

              // Aeronet file
              if (IsParameterEnabled("atmo.aeronet"))
                {
                  m_ReflectanceToSurfaceReflectanceFilter->SetAeronetFileName(GetParameterString("atmo.aeronet"));
                }

              m_ReflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(false);
              m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(true);
              m_ReflectanceToSurfaceReflectanceFilter->GenerateParameters();
              m_ReflectanceToSurfaceReflectanceFilter->UpdateOutputInformation();
              m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false);

             std::ostringstream oss;
              oss.str("");
              oss << m_AtmosphericParam;

             AtmosphericRadiativeTerms::Pointer atmoTerms =  m_ReflectanceToSurfaceReflectanceFilter->GetAtmosphericRadiativeTerms();
              oss << std::endl << std::endl << atmoTerms;

             GetLogger()->Info("Atmospheric correction parameters : " + oss.str());
              //rescale the surface reflectance in milli-reflectance

              m_ReflectanceToSurfaceReflectanceFilter->UpdateOutputInformation();
              m_ScaleFilter->SetInput(m_ReflectanceToSurfaceReflectanceFilter->GetOutput());
            }
            break;
          }

        // Output Image
        const double scale = IsParameterEnabled("milli") ? 1000.0 : 1.0;
        m_ScaleFilter->SetCoef(scale);

        SetParameterOutputImage("out", m_ScaleFilter->GetOutput());
      }

      ImageToLuminanceImageFilterType ::Pointer               m_ImageToLuminanceFilter;
      LuminanceToReflectanceImageFilterType::Pointer          m_LuminanceToReflectanceFilter;
      ReflectanceToSurfaceReflectanceImageFilterType::Pointer m_ReflectanceToSurfaceReflectanceFilter;
      ScaleFilterType::Pointer                                m_ScaleFilter;
      AtmosphericCorrectionParametersType::Pointer            m_AtmosphericParam;
    };

  }// namespace Wrapper
} // namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::OpticalCalibration)
<commit_msg>ENH: add Pleiades in the list of supported sensors in toa optical calibration app<commit_after>/*=========================================================================

  Program:   ORFEO Toolbox
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Centre National d'Etudes Spatiales. All rights reserved.
  See OTBCopyright.txt for details.

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

  =========================================================================*/
#include "otbWrapperApplication.h"
#include "otbWrapperApplicationFactory.h"

#include "otbImageToLuminanceImageFilter.h"
#include "otbLuminanceToReflectanceImageFilter.h"
#include "otbReflectanceToSurfaceReflectanceImageFilter.h"
#include "otbMultiplyByScalarImageFilter.h"

namespace otb
{

  enum
    {
      Level_TOA,
      Level_TOC
    };

  enum
    {
      Aerosol_NoAerosol,
      Aerosol_Continental,
      Aerosol_Maritime,
      Aerosol_Urban,
      Aerosol_Desertic,
    };

  namespace Wrapper
  {

    class OpticalCalibration : public Application
    {

    public:
      /** Standard class typedefs. */
      typedef OpticalCalibration            Self;
      typedef Application                   Superclass;
      typedef itk::SmartPointer<Self>       Pointer;
      typedef itk::SmartPointer<const Self> ConstPointer;

      /** Standard macro */
      itkNewMacro(Self);

      itkTypeMacro(OpticalCalibration, Application);

      typedef ImageToLuminanceImageFilter<UInt16VectorImageType,
                                          DoubleVectorImageType>              ImageToLuminanceImageFilterType;

      typedef LuminanceToReflectanceImageFilter<DoubleVectorImageType,
                                                DoubleVectorImageType>        LuminanceToReflectanceImageFilterType;

      typedef otb::MultiplyByScalarImageFilter<DoubleVectorImageType,
                                               DoubleVectorImageType>         ScaleFilterType;

      typedef ReflectanceToSurfaceReflectanceImageFilter<DoubleVectorImageType,
                                                         DoubleVectorImageType>         ReflectanceToSurfaceReflectanceImageFilterType;
      typedef ReflectanceToSurfaceReflectanceImageFilterType::FilterFunctionValuesType  FilterFunctionValuesType;
      typedef FilterFunctionValuesType::ValuesVectorType                                ValuesVectorType;
      typedef AtmosphericCorrectionParameters                                           AtmosphericCorrectionParametersType;
      typedef AtmosphericCorrectionParametersType::AerosolModelType                     AerosolModelType;

    private:
      void DoInit()
      {
        SetName("OpticalCalibration");
        SetDescription("Perform optical calibration TOA/TOC (Top Of Atmosphere/Top Of Canopy). Supported sensors: QuickBird, Ikonos, WorldView2, Formosat, Spot5, Pleiades");
        // Documentation
        SetDocName("Optical calibration");
        SetDocLongDescription("The application allows to convert pixel values from DN (for Digital Numbers) to physically interpretable and comparable values. Calibrated values are called surface reflectivity and its values lie in the range [0, 1].\nThe first level is called Top Of Atmosphere (TOA) reflectivity. It takes into account the sensor gain, sensor spectral response and the solar illumination.\nThe second level is called Top Of Canopy (TOC) reflectivity. In addition to sensor gain and solar illumination, it takes into account the optical thickness of the atmosphere, the atmospheric pressure, the water vapor amount, the ozone amount, as well as the composition and amount of aerosol gasses.\nIt is also possible to indicate an AERONET file which contains atmospheric parameters (version 1 and version 2 of Aeronet file are supported.");
        SetDocLimitations("None");
        SetDocAuthors("OTB-Team");
        SetDocSeeAlso("The OTB CookBook");

        AddDocTag(Tags::Calibration);

        AddParameter(ParameterType_InputImage,  "in",  "Input");
        SetParameterDescription("in", "Input image filename (values in DN)");

        AddParameter(ParameterType_OutputImage, "out", "Output");
        SetParameterDescription("out","Output calibrated image filename");

        AddRAMParameter();

        AddParameter(ParameterType_Choice,   "level", "Calibration Level");
        AddChoice("level.toa",     "TOA : Top Of Atmosphere");
        AddChoice("level.toc",     "TOC : Top Of Canopy (EXPERIMENTAL)");
        SetParameterString("level", "toa");

        AddParameter(ParameterType_Empty, "milli", "Convert to milli reflectance");
        SetParameterDescription("milli", "Flag to use milli-reflectance instead of reflectance.\n"
                                "This allows to save the image with integer pixel type (in the range [0, 1000]  instead of floating point in the range [0, 1]. In order to do that, use this option and set the output pixel type (-out filename uint16 for example)");
        DisableParameter("milli");
        MandatoryOff("milli");

        AddParameter(ParameterType_InputFilename, "rsr", "Relative Spectral Response File");
        std::ostringstream oss;
        oss << "Sensor relative spectral response file"<<std::endl;
        oss << "By default the application gets these informations in the metadata";
        SetParameterDescription("rsr", oss.str());
        MandatoryOff("rsr");

        AddParameter(ParameterType_Group,"atmo","Atmospheric parameters");
        SetParameterDescription("atmo","This group allows to set the atmospheric parameters.");
        AddParameter(ParameterType_Choice,   "atmo.aerosol", "Aerosol Model");
        AddChoice("atmo.aerosol.noaersol",    "No Aerosol Model");
        AddChoice("atmo.aerosol.continental", "Continental");
        AddChoice("atmo.aerosol.maritime",    "Maritime");
        AddChoice("atmo.aerosol.urban",       "Urban");
        AddChoice("atmo.aerosol.desertic",    "Desertic");

        AddParameter(ParameterType_Float, "atmo.oz",   "Ozone Amount");
        SetParameterDescription("atmo.oz", "Ozone Amount");

        AddParameter(ParameterType_Float, "atmo.wa",   "Water Vapor Amount");
        SetParameterDescription("atmo.wa", "Water Vapor Amount (in saturation fraction of water)");

        AddParameter(ParameterType_Float, "atmo.pressure", "Atmospheric Pressure");
        SetParameterDescription("atmo.pressure", "Atmospheric Pressure (in hPa)");

        AddParameter(ParameterType_Float, "atmo.opt",  "Aerosol Optical Thickness");
        SetParameterDescription("atmo.opt", "Aerosol Optical Thickness");

        SetDefaultParameterFloat("atmo.oz", 0.);
        SetDefaultParameterFloat("atmo.wa",  2.5);
        SetDefaultParameterFloat("atmo.pressure", 1030.);

        SetDefaultParameterFloat("atmo.opt", 0.2);
        MandatoryOff("atmo.oz");
        MandatoryOff("atmo.wa");
        MandatoryOff("atmo.pressure");
        MandatoryOff("atmo.opt");

        AddParameter(ParameterType_InputFilename, "atmo.aeronet", "Aeronet File");
        SetParameterDescription("atmo.aeronet","Aeronet file containing atmospheric parameters");
        MandatoryOff("atmo.aeronet");

        // Doc example parameter settings
        SetDocExampleParameterValue("in", "QB_1_ortho.tif");
        SetDocExampleParameterValue("level", "toa");
        SetDocExampleParameterValue("out", "OpticalCalibration.tif");
      }

      void DoUpdateParameters()
      {
        // Nothing to update
      }

      void DoExecute()
      {
        UInt16VectorImageType::Pointer inImage = GetParameterUInt16VectorImage("in");

        //Check if valid metadata informations are available to compute ImageToLuminance and LuminanceToReflectance
        itk::MetaDataDictionary             dict = inImage->GetMetaDataDictionary();
        OpticalImageMetadataInterface::Pointer lImageMetadataInterface = OpticalImageMetadataInterfaceFactory::CreateIMI(dict);

        // Test if needed data are available : an exception will be thrown
        // if one the following Get* return failure. the exception is then
        // caught in the Wrapper::Application class which redirect it to
        // the logger
        // ImageToLuminance
        lImageMetadataInterface->GetPhysicalGain();
        lImageMetadataInterface->GetPhysicalBias();

        // LuminanceToReflectance
        lImageMetadataInterface->GetDay();
        lImageMetadataInterface->GetMonth();

        lImageMetadataInterface->GetSolarIrradiance();
        lImageMetadataInterface->GetSunElevation();

        m_ImageToLuminanceFilter                = ImageToLuminanceImageFilterType::New();
        m_LuminanceToReflectanceFilter          = LuminanceToReflectanceImageFilterType::New();
        m_ReflectanceToSurfaceReflectanceFilter = ReflectanceToSurfaceReflectanceImageFilterType::New();

        m_ImageToLuminanceFilter->SetInput(inImage);
        m_LuminanceToReflectanceFilter->SetInput(m_ImageToLuminanceFilter->GetOutput());
        m_ReflectanceToSurfaceReflectanceFilter->SetInput(m_LuminanceToReflectanceFilter->GetOutput());

        m_ScaleFilter = ScaleFilterType::New();
        m_ScaleFilter->InPlaceOn();

        switch ( GetParameterInt("level") )
          {
          case Level_TOA:
            {
              m_LuminanceToReflectanceFilter->UpdateOutputInformation();
              m_ScaleFilter->SetInput(m_LuminanceToReflectanceFilter->GetOutput());
            }
            break;
          case Level_TOC:
            {
              m_ReflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(false);
              m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(true);
              m_ReflectanceToSurfaceReflectanceFilter->UpdateOutputInformation();
              m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false);

              m_AtmosphericParam = m_ReflectanceToSurfaceReflectanceFilter->GetCorrectionParameters();
              //AerosolModelType aeroMod = AtmosphericCorrectionParametersType::NO_AEROSOL;

              switch ( GetParameterInt("atmo.aerosol") )
                {
                case Aerosol_Desertic:
                  {
                    // Aerosol_Desertic correspond to 4 in the enum but actually in
                    // the class atmosphericParam it is known as parameter 5
                    m_AtmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(5));
                  }
                  break;
                default:
                  {
                    m_AtmosphericParam->SetAerosolModel(static_cast<AerosolModelType>(GetParameterInt("atmo.aerosol")));
                  }
                  break;
                }
              // Set the atmospheric param
              m_AtmosphericParam->SetOzoneAmount(GetParameterFloat("atmo.oz"));
              m_AtmosphericParam->SetWaterVaporAmount(GetParameterFloat("atmo.wa"));
              m_AtmosphericParam->SetAtmosphericPressure(GetParameterFloat("atmo.pressure"));
              m_AtmosphericParam->SetAerosolOptical(GetParameterFloat("atmo.opt"));

              // Relative Spectral Response File
              if (IsParameterEnabled("rsr"))
                {
                  m_ReflectanceToSurfaceReflectanceFilter->SetFilterFunctionValuesFileName(GetParameterString("rsr"));
                }
              else
                {
                  m_ReflectanceToSurfaceReflectanceFilter->SetFilterFunctionCoef(lImageMetadataInterface->GetSpectralSensitivity());
                  OpticalImageMetadataInterface::WavelengthSpectralBandVectorType tmp = lImageMetadataInterface->GetSpectralSensitivity();
                  std::cout << "ICI" << std::endl;
                  std::cout << "tmp->GetNthElement(0)->GetFilterFunctionValues()[0] " << tmp->GetNthElement(0)->GetFilterFunctionValues()[0] << std::endl;
                }

              // Aeronet file
              if (IsParameterEnabled("atmo.aeronet"))
                {
                  m_ReflectanceToSurfaceReflectanceFilter->SetAeronetFileName(GetParameterString("atmo.aeronet"));
                }

              m_ReflectanceToSurfaceReflectanceFilter->SetIsSetAtmosphericRadiativeTerms(false);
              m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(true);
              m_ReflectanceToSurfaceReflectanceFilter->GenerateParameters();
              m_ReflectanceToSurfaceReflectanceFilter->UpdateOutputInformation();
              m_ReflectanceToSurfaceReflectanceFilter->SetUseGenerateParameters(false);

             std::ostringstream oss;
              oss.str("");
              oss << m_AtmosphericParam;

             AtmosphericRadiativeTerms::Pointer atmoTerms =  m_ReflectanceToSurfaceReflectanceFilter->GetAtmosphericRadiativeTerms();
              oss << std::endl << std::endl << atmoTerms;

             GetLogger()->Info("Atmospheric correction parameters : " + oss.str());
              //rescale the surface reflectance in milli-reflectance

              m_ReflectanceToSurfaceReflectanceFilter->UpdateOutputInformation();
              m_ScaleFilter->SetInput(m_ReflectanceToSurfaceReflectanceFilter->GetOutput());
            }
            break;
          }

        // Output Image
        const double scale = IsParameterEnabled("milli") ? 1000.0 : 1.0;
        m_ScaleFilter->SetCoef(scale);

        SetParameterOutputImage("out", m_ScaleFilter->GetOutput());
      }

      ImageToLuminanceImageFilterType ::Pointer               m_ImageToLuminanceFilter;
      LuminanceToReflectanceImageFilterType::Pointer          m_LuminanceToReflectanceFilter;
      ReflectanceToSurfaceReflectanceImageFilterType::Pointer m_ReflectanceToSurfaceReflectanceFilter;
      ScaleFilterType::Pointer                                m_ScaleFilter;
      AtmosphericCorrectionParametersType::Pointer            m_AtmosphericParam;
    };

  }// namespace Wrapper
} // namespace otb

OTB_APPLICATION_EXPORT(otb::Wrapper::OpticalCalibration)
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: rscconst.hxx,v $
 *
 *  $Revision: 1.6 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-08 13:30:21 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _RSCCONST_HXX
#define _RSCCONST_HXX

#ifndef _RSCALL_H
#include <rscall.h>
#endif
#ifndef _RSCERROR_H
#include <rscerror.h>
#endif
#ifndef _RSCHASH_HXX
#include <rschash.hxx>
#endif
#ifndef _RSCTOP_HXX
#include <rsctop.hxx>
#endif

/******************* R s c C o n s t *************************************/
class RscConst : public RscTop
{
protected:
    struct VarEle {
        Atom    nId;    // Name der Konstante
        INT32   lValue; // Wert der Konstante
    };
    VarEle *    pVarArray;  // Zeiger auf das Feld mit Konstanten
    sal_uInt32      nEntries;   // Anzahle der Eintraege im Feld
public:
                    RscConst( Atom nId, sal_uInt32 nTypId );
                    ~RscConst();
    virtual RSCCLASS_TYPE   GetClassType() const;
    sal_uInt32          GetEntryCount() const { return nEntries; }
                    // Die erlaubten Werte werden gesetzt
    ERRTYPE         SetConstant( Atom nVarName, INT32 lValue );
    Atom            GetConstant( sal_uInt32 nPos );
    BOOL            GetConstValue( Atom nConstId, INT32 * pVal ) const;
    BOOL            GetValueConst( INT32 nValue, Atom  * pConstId ) const;
    sal_uInt32          GetConstPos( Atom nConstId );
    virtual void    WriteSyntax( FILE * fOutput, RscTypCont * pTC );
    virtual void    WriteRcAccess( FILE * fOutput, RscTypCont * pTC,
                                    const char * );
};

/******************* R s c E n u m ***************************************/
class RscEnum : public RscConst {
    struct RscEnumInst {
        sal_uInt32  nValue; // Position der Konstanten im Array
        BOOL    bDflt;  // Ist Default
    };
    sal_uInt32          nSize;
public:
                    RscEnum( Atom nId, sal_uInt32 nTypId );
    RSCINST         Create( RSCINST * pInst, const RSCINST & rDfltInst, BOOL );
    sal_uInt32          Size(){ return nSize; }

    virtual void    SetToDefault( const RSCINST & rInst )
                    {
                        ((RscEnumInst*)rInst.pData)->bDflt = TRUE;
                    }
    BOOL            IsDefault( const RSCINST & rInst )
                    {
                        return( ((RscEnumInst*)rInst.pData)->bDflt );
                    };
                    // Als Default setzen
    BOOL            IsValueDefault( const RSCINST & rInst, CLASS_DATA pDef );

    ERRTYPE         SetConst( const RSCINST & rInst, Atom nValueId,
                              INT32 nValue );
    ERRTYPE         SetNumber( const RSCINST & rInst, INT32 nValue );
    ERRTYPE         GetConst( const RSCINST & rInst, Atom * );
    ERRTYPE         GetNumber( const RSCINST & rInst, INT32 * nValue );
    void            WriteSrc( const RSCINST &rInst, FILE * fOutput,
                              RscTypCont * pTC, sal_uInt32 nTab, const char * );
    ERRTYPE         WriteRc( const RSCINST & rInst, RscWriteRc & aMem,
                             RscTypCont * pTC, sal_uInt32, BOOL bExtra );
};

class RscNameTable;

sal_uInt32 GetLangId( const ByteString& alang);

class RscLangEnum : public RscEnum
{
public:
    RscLangEnum();

    void Init( RscNameTable& rNames );
};

#endif // _RSCCONST_HXX
<commit_msg>INTEGRATION: CWS rsclangvar (1.6.90); FILE MERGED 2007/11/05 15:04:06 pl 1.6.90.1: #i79665# parse on the fly languages<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: rscconst.hxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2008-01-04 15:58:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#ifndef _RSCCONST_HXX
#define _RSCCONST_HXX

#ifndef _RSCALL_H
#include <rscall.h>
#endif
#ifndef _RSCERROR_H
#include <rscerror.h>
#endif
#ifndef _RSCHASH_HXX
#include <rschash.hxx>
#endif
#ifndef _RSCTOP_HXX
#include <rsctop.hxx>
#endif

/******************* R s c C o n s t *************************************/
class RscConst : public RscTop
{
protected:
    struct VarEle {
        Atom    nId;    // Name der Konstante
        INT32   lValue; // Wert der Konstante
    };
    VarEle *    pVarArray;  // Zeiger auf das Feld mit Konstanten
    sal_uInt32      nEntries;   // Anzahle der Eintraege im Feld
public:
                    RscConst( Atom nId, sal_uInt32 nTypId );
                    ~RscConst();
    virtual RSCCLASS_TYPE   GetClassType() const;
    sal_uInt32          GetEntryCount() const { return nEntries; }
                    // Die erlaubten Werte werden gesetzt
    ERRTYPE         SetConstant( Atom nVarName, INT32 lValue );
    Atom            GetConstant( sal_uInt32 nPos );
    BOOL            GetConstValue( Atom nConstId, INT32 * pVal ) const;
    BOOL            GetValueConst( INT32 nValue, Atom  * pConstId ) const;
    sal_uInt32          GetConstPos( Atom nConstId );
    virtual void    WriteSyntax( FILE * fOutput, RscTypCont * pTC );
    virtual void    WriteRcAccess( FILE * fOutput, RscTypCont * pTC,
                                    const char * );
};

/******************* R s c E n u m ***************************************/
class RscEnum : public RscConst {
    struct RscEnumInst {
        sal_uInt32  nValue; // Position der Konstanten im Array
        BOOL    bDflt;  // Ist Default
    };
    sal_uInt32          nSize;
public:
                    RscEnum( Atom nId, sal_uInt32 nTypId );
    RSCINST         Create( RSCINST * pInst, const RSCINST & rDfltInst, BOOL );
    sal_uInt32          Size(){ return nSize; }

    virtual void    SetToDefault( const RSCINST & rInst )
                    {
                        ((RscEnumInst*)rInst.pData)->bDflt = TRUE;
                    }
    BOOL            IsDefault( const RSCINST & rInst )
                    {
                        return( ((RscEnumInst*)rInst.pData)->bDflt );
                    };
                    // Als Default setzen
    BOOL            IsValueDefault( const RSCINST & rInst, CLASS_DATA pDef );

    ERRTYPE         SetConst( const RSCINST & rInst, Atom nValueId,
                              INT32 nValue );
    ERRTYPE         SetNumber( const RSCINST & rInst, INT32 nValue );
    ERRTYPE         GetConst( const RSCINST & rInst, Atom * );
    ERRTYPE         GetNumber( const RSCINST & rInst, INT32 * nValue );
    void            WriteSrc( const RSCINST &rInst, FILE * fOutput,
                              RscTypCont * pTC, sal_uInt32 nTab, const char * );
    ERRTYPE         WriteRc( const RSCINST & rInst, RscWriteRc & aMem,
                             RscTypCont * pTC, sal_uInt32, BOOL bExtra );
};

class RscNameTable;

sal_uInt32 GetLangId( const ByteString& alang);

class RscLangEnum : public RscEnum
{
    long mnLangId;
public:
    RscLangEnum();

    void Init( RscNameTable& rNames );

    Atom AddLanguage( const char* pLang, RscNameTable& rNames );
};

#endif // _RSCCONST_HXX
<|endoftext|>


<commit_before>//---------------------------------------------------------------------------//
//!
//! \file   MonteCarlo_PhotonScatteringDistribution.hpp
//! \author Alex Robinson
//! \brief  The photon scattering distribution base class
//!
//---------------------------------------------------------------------------//

#ifndef MONTE_CARLO_PHOTON_SCATTERING_DISTRIBUTION_HPP
#define MONTE_CARLO_PHOTON_SCATTERING_DISTRIBUTION_HPP

// FRENSIE Includes
#include "MonteCarlo_PhotonState.hpp"
#include "MonteCarlo_ParticleBank.hpp"
#include "MonteCarlo_SubshellType.hpp"
#include "MonteCarlo_ScatteringDistribution.hpp"

namespace MonteCarlo{

//! The photon scattering distribution base class
class PhotonScatteringDistribution : public ScatteringDistribution
{

public:

  //! Constructor
  PhotonScatteringDistribution()
  { /* ... */ }

  //! Destructor
  virtual ~PhotonScatteringDistribution()
  { /* ... */ }

  //! Evaluate the distribution
  virtual double evaluate( const double incoming_energy,
			   const double scattering_angle_cosine ) const = 0;

  //! Evaluate the PDF
  virtual double evaluatePDF( const double incoming_energy,
			      const double scattering_angle_cosine ) const = 0;

  //! Evaluate the integrated cross section (cm^2)
  virtual double evaluateIntegratedCrossSection(
					    const double incoming_energy,
					    const double precision ) const = 0;

  //! Sample an outgoing energy and direction from the distribution
  virtual void sample( const double incoming_energy,
		       double& outgoing_energy,
		       double& scattering_angle_cosine,
		       SubshellType& shell_of_interaction ) const = 0;

  //! Sample an outgoing energy and direction and record the number of trials
  virtual void sampleAndRecordTrials( const double incoming_energy,
				      double& outgoing_energy,
				      double& scattering_angle_cosine,
				      SubshellType& shell_of_interaction,
				      unsigned& trials ) const = 0;

  //! Randomly scatter the photon and return the shell that was interacted with
  virtual void scatterPhoton( PhotonState& photon,
			      ParticleBank& bank ) const = 0;
};

} // end MonteCarlo namespace

#endif // end MONTE_CARLO_PHOTON_SCATTERING_DISTRIBUTION_HPP

//---------------------------------------------------------------------------//
// end MonteCarlo_PhotonScatteringDistribution.hpp
//---------------------------------------------------------------------------//
<commit_msg>Fixed an error in the photon scattering distribution that had been introduced<commit_after>//---------------------------------------------------------------------------//
//!
//! \file   MonteCarlo_PhotonScatteringDistribution.hpp
//! \author Alex Robinson
//! \brief  The photon scattering distribution base class
//!
//---------------------------------------------------------------------------//

#ifndef MONTE_CARLO_PHOTON_SCATTERING_DISTRIBUTION_HPP
#define MONTE_CARLO_PHOTON_SCATTERING_DISTRIBUTION_HPP

// FRENSIE Includes
#include "MonteCarlo_PhotonState.hpp"
#include "MonteCarlo_ParticleBank.hpp"
#include "MonteCarlo_SubshellType.hpp"
#include "MonteCarlo_ScatteringDistribution.hpp"

namespace MonteCarlo{

//! The scattering distribution base class
class PhotonScatteringDistribution : public ScatteringDistribution
{

public:

  //! Constructor
  PhotonScatteringDistribution()
  { /* ... */ }

  //! Destructor
  virtual ~PhotonScatteringDistribution()
  { /* ... */ }

  //! Evaluate the distribution
  virtual double evaluate( const double incoming_energy,
			   const double scattering_angle_cosine ) const = 0;

  //! Evaluate the PDF
  virtual double evaluatePDF( const double incoming_energy,
			      const double scattering_angle_cosine ) const = 0;

  //! Evaluate the integrated cross section (cm^2)
  virtual double evaluateIntegratedCrossSection(
					    const double incoming_energy,
					    const double precision ) const = 0;

  //! Sample an outgoing energy and direction from the distribution
  virtual void sample( const double incoming_energy,
		       double& outgoing_energy,
		       double& scattering_angle_cosine,
		       SubshellType& shell_of_interaction ) const = 0;

  //! Sample an outgoing energy and direction and record the number of trials
  virtual void sampleAndRecordTrials( const double incoming_energy,
				      double& outgoing_energy,
				      double& scattering_angle_cosine,
				      SubshellType& shell_of_interaction,
				      unsigned& trials ) const = 0;

  //! Randomly scatter the photon and return the shell that was interacted with
  virtual void scatterPhoton( PhotonState& photon,
			      ParticleBank& bank,
			      SubshellType& shell_of_interaction ) const = 0;
};

} // end MonteCarlo namespace

#endif // end MONTE_CARLO_PHOTON_SCATTERING_DISTRIBUTION_HPP

//---------------------------------------------------------------------------//
// end MonteCarlo_PhotonScatteringDistribution.hpp
//---------------------------------------------------------------------------//
<|endoftext|>