<commit_before>#include "Moose.h"
#include "Factory.h"
#include "NonlinearSystem.h"
#include "PetscSupport.h"
#include "ActionWarehouse.h"
#include "ActionFactory.h"

// objects that can be created by MOOSE
#include "TimeDerivative.h"
#include "Diffusion.h"
#include "CoupledForce.h"
#include "UserForcingFunction.h"
#include "BodyForce.h"
#include "ImplicitEuler.h"
#include "Reaction.h"
#include "RealPropertyOutput.h"
// bcs
#include "DirichletBC.h"
#include "NeumannBC.h"
#include "FunctionDirichletBC.h"
#include "FunctionNeumannBC.h"
#include "MatchedValueBC.h"
#include "VacuumBC.h"

// auxkernels
#include "CoupledAux.h"
#include "ConstantAux.h"
#include "FunctionAux.h"
#include "NearestNodeDistanceAux.h"
#include "NearestNodeValueAux.h"
#include "PenetrationAux.h"
#include "ProcessorIDAux.h"
#include "GapValueAux.h"

// dirac kernels
#include "ConstantPointSource.h"
// ics
#include "ConstantIC.h"
#include "BoundingBoxIC.h"
#include "FunctionIC.h"
#include "RandomIC.h"
// mesh modifiers
#include "ElementDeleter.h"
// executioners
#include "Steady.h"
#include "Transient.h"
#include "LooseCoupling.h"
#include "SolutionTimeAdaptive.h"
// functions
#include "ParsedFunction.h"
#include "ParsedGradFunction.h"
#include "PiecewiseLinear.h"
#include "SolutionFunction.h"
#include "SphereFunction.h"
// materials
#include "GenericConstantMaterial.h"
// PPS
#include "AverageElementSize.h"
#include "AverageNodalVariableValue.h"
#include "ElementAverageValue.h"
#include "ElementH1Error.h"
#include "ElementH1SemiError.h"
#include "ElementIntegral.h"
#include "ElementL2Error.h"
#include "EmptyPostprocessor.h"
#include "NodalVariableValue.h"
#include "PrintDOFs.h"
#include "PrintDT.h"
#include "PrintNumElems.h"
#include "PrintNumNodes.h"
#include "Reporter.h"
#include "SideAverageValue.h"
#include "SideFluxIntegral.h"
#include "SideIntegral.h"
// stabilizers
#include "ConvectionDiffusionSUPG.h"
// dampers
#include "ConstantDamper.h"
#include "MaxIncrement.h"

// Actions
#include "AddMeshModifierAction.h"
#include "AddBCAction.h"
#include "AddDiracKernelAction.h"
#include "AddICAction.h"
#include "AddKernelAction.h"
#include "AddPeriodicBCAction.h"
#include "AddVariableAction.h"
#include "AddPostprocessorAction.h"
#include "AddDamperAction.h"
#include "AddStabilizerAction.h"
#include "AddFunctionAction.h"
#include "CreateExecutionerAction.h"
#include "CreateMeshAction.h"
#include "EmptyAction.h"
#include "InitProblemAction.h"
#include "CopyNodalVarsAction.h"
#include "SetupMeshAction.h"
#include "SetupOutputAction.h"
#include "AddMaterialAction.h"
#include "GlobalParamsAction.h"
#include "SetupPBPAction.h"
#include "AdaptivityAction.h"
#include "SetupDampersAction.h"
#include "CheckIntegrityAction.h"

namespace Moose {

static bool registered = false;

void
registerObjects()
{
  if (registered)
    return;

  registerObject(TimeDerivative);

  // kernels
  registerObject(Diffusion);
  registerObject(CoupledForce);
  registerObject(UserForcingFunction);
  registerObject(BodyForce);
  registerObject(ImplicitEuler);
  registerObject(Reaction);
  registerObject(RealPropertyOutput);
  // bcs
  registerObject(DirichletBC);
  registerObject(NeumannBC);
  registerObject(FunctionDirichletBC);
  registerObject(FunctionNeumannBC);
  registerObject(MatchedValueBC);
  registerObject(VacuumBC);
  // dirac kernels
  registerObject(ConstantPointSource);

  // aux kernels
  registerObject(CoupledAux);
  registerObject(ConstantAux);
  registerObject(FunctionAux);
  registerObject(NearestNodeDistanceAux);
  registerObject(NearestNodeValueAux);
  registerObject(PenetrationAux);
  registerObject(ProcessorIDAux);
  registerObject(GapValueAux);

  // Initial Conditions
  registerObject(ConstantIC);
  registerObject(BoundingBoxIC);
  registerObject(FunctionIC);
  registerObject(RandomIC);
  // Mesh Modifiers
  registerObject(ElementDeleter);
  // executioners
  registerObject(Steady);
  registerObject(Transient);
  registerObject(LooseCoupling);
  registerObject(SolutionTimeAdaptive);
  // functions
  registerObject(ParsedFunction);
  registerObject(ParsedGradFunction);
  registerObject(PiecewiseLinear);
  registerObject(SolutionFunction);
  registerObject(SphereFunction);
  // materials
  registerObject(GenericConstantMaterial);
  // PPS
  registerObject(AverageElementSize);
  registerObject(AverageNodalVariableValue);
  registerObject(ElementAverageValue);
  registerObject(ElementH1Error);
  registerObject(ElementH1SemiError);
  registerObject(ElementIntegral);
  registerObject(ElementL2Error);
  registerObject(EmptyPostprocessor);
  registerObject(NodalVariableValue);
  registerObject(PrintDOFs);
  registerObject(PrintDT);
  registerObject(PrintNumElems);
  registerObject(PrintNumNodes);
  registerObject(Reporter);
  registerObject(SideAverageValue);
  registerObject(SideFluxIntegral);
  registerObject(SideIntegral);
  // stabilizers
  registerObject(ConvectionDiffusionSUPG);
  // dampers
  registerObject(ConstantDamper);
  registerObject(MaxIncrement);

  addActionTypes();
  registerActions();

  registered = true;
}

void
addActionTypes()
{
  /**************************/
  /**** Register Actions ****/
  /**************************/
  /// Minimal Problem
  registerActionName("setup_mesh", true);
  registerActionName("add_variable", true);
  registerActionName("add_kernel", true);
  registerActionName("setup_executioner", true);
  registerActionName("setup_output", true);
  registerActionName("init_problem", true);
  registerActionName("copy_nodal_vars", true);
  registerActionName("add_bc", false);  // Does this need to be true?  Not if you have periodic boundaries...
  registerActionName("setup_dampers", true);
  registerActionName("check_integrity", true);

  /// Additional Actions
  registerActionName("no_action", false);  // Used for Empty Action placeholders
  registerActionName("set_global_params", false);
  registerActionName("create_mesh", false);
  registerActionName("add_mesh_modifier", false);
  registerActionName("add_material", false);
  registerActionName("add_function", false);
  registerActionName("add_aux_variable", false);
  registerActionName("add_aux_kernel", false);
  registerActionName("add_aux_bc", false);
  registerActionName("add_dirac_kernel", false);
  registerActionName("add_ic", false);
  registerActionName("add_postprocessor", false);
  registerActionName("add_damper", false);
  registerActionName("add_stabilizer", false);
  registerActionName("add_periodic_bc", false);
  registerActionName("add_preconditioning", false);
  registerActionName("setup_adaptivity", false);

  // Dummy Actions (useful for sync points in the dependencies)
  registerActionName("setup_mesh_complete", false);
  registerActionName("setup_function_complete", false);
  registerActionName("setup_variable_complete", false);
  registerActionName("ready_to_init", false);
  registerActionName("setup_pps_complete", false);

  /**************************/
  /****** Dependencies ******/
  /**************************/

/*
  /// Mesh Actions
  action_warehouse.addDependency("setup_mesh", "create_mesh");
  action_warehouse.addDependency("add_mesh_modifier", "setup_mesh");
  action_warehouse.addDependency("setup_mesh_complete", "setup_mesh");

  /// Executioner
  action_warehouse.addDependency("setup_executioner", "setup_mesh_complete");
  action_warehouse.addDependency("setup_adaptivity", "setup_executioner");

  /// Functions
  action_warehouse.addDependency("add_function", "setup_adaptivity");
  action_warehouse.addDependency("setup_function_complete", "add_function");

  /// Variable Actions
  action_warehouse.addDependency("add_variable", "setup_function_complete");

  /// AuxVariable Actions
  action_warehouse.addDependency("add_aux_variable", "setup_function_complete");
  action_warehouse.addDependency("setup_variable_complete", "add_aux_variable");

  /// ICs
  action_warehouse.addDependency("add_ic", "setup_variable_complete");

  /// PeriodicBCs
  action_warehouse.addDependency("add_periodic_bc", "setup_variable_complete");

  /// Preconditioning
  action_warehouse.addDependency("add_preconditioning", "add_periodic_bc");
  action_warehouse.addDependency("ready_to_init", "add_preconditioning");

  /// InitProblem
  action_warehouse.addDependency("setup_dampers", "ready_to_init");
  action_warehouse.addDependency("init_problem", "setup_dampers");
  action_warehouse.addDependency("copy_nodal_vars", "init_problem");

  /// Materials
  action_warehouse.addDependency("add_material", "copy_nodal_vars");

  /// Postprocessors
  action_warehouse.addDependency("add_postprocessor", "add_material");
  action_warehouse.addDependency("setup_pps_complete", "add_postprocessor");

  /// Dampers
  action_warehouse.addDependency("add_damper", "setup_pps_complete");

  /// Stabilizers
  action_warehouse.addDependency("add_stabilizer", "setup_pps_complete");

  /// Kernels
  action_warehouse.addDependency("add_kernel", "setup_pps_complete");

  /// AuxKernels
  action_warehouse.addDependency("add_aux_kernel", "setup_pps_complete");

  /// BCs
  action_warehouse.addDependency("add_bc", "setup_pps_complete");

  /// AuxBCs
  action_warehouse.addDependency("add_aux_bc", "setup_pps_complete");

  /// Dirac Kernels
  action_warehouse.addDependency("add_dirac_kernel", "setup_pps_complete");

  /// Ouput
  action_warehouse.addDependency("setup_output", "setup_pps_complete");

  /// Check Integrity
  action_warehouse.addDependency("check_integrity", "setup_output");
*/

  /**
   * The following is the default set of action dependencies for a basic MOOSE problem.  The formatting
   * of this string is important.  Each line represents a set of dependencies that depend on the previous
   * line.  Items on the same line have equal weight and can be executed in any order.  */
  action_warehouse.addDependencySets(
"(create_mesh, set_global_params)"
"(setup_mesh)"
"(add_mesh_modifier, setup_mesh_complete)"
"(setup_executioner)"
"(add_function)"
"(setup_function_complete)"
"(add_aux_variable, add_variable)"
"(setup_variable_complete)"
"(setup_adaptivity)"
"(add_ic, add_periodic_bc)"
"(add_preconditioning)"
"(ready_to_init)"
"(setup_dampers)"
"(init_problem)"
"(copy_nodal_vars)"
"(add_material)"
"(add_postprocessor)"
"(setup_pps_complete)"
"(add_aux_bc, add_aux_kernel, add_bc, add_damper, add_dirac_kernel, add_kernel, add_stabilizer, setup_output)"
"(check_integrity)"
);

}

void
registerActions()
{
  registerAction(CreateMeshAction, "Mesh/Generation", "create_mesh");
  registerAction(SetupMeshAction, "Mesh", "setup_mesh");
  registerAction(AddFunctionAction, "Functions/*", "add_function");
  registerAction(CreateExecutionerAction, "Executioner", "setup_executioner");
  registerAction(SetupOutputAction, "Output", "setup_output");
  registerAction(GlobalParamsAction, "GlobalParams", "set_global_params");

  /// MooseObjectActions
  registerAction(AddMeshModifierAction, "Mesh/*", "add_mesh_modifier");
  registerAction(AddVariableAction, "Variables/*", "add_variable");
  registerAction(AddVariableAction, "AuxVariables/*", "add_aux_variable");
  registerAction(AddICAction, "Variables/*/InitialCondition", "add_ic");
  registerAction(AddICAction, "AuxVariables/*/InitialCondition", "add_ic");
  registerAction(AddKernelAction, "Kernels/*", "add_kernel");
  registerAction(AddKernelAction, "AuxKernels/*", "add_aux_kernel");
  registerAction(AddBCAction, "BCs/*", "add_bc");
  registerAction(EmptyAction, "BCs/Periodic", "no_action");  // placeholder
  registerAction(AddPeriodicBCAction, "BCs/Periodic/*", "add_periodic_bc");
  registerAction(AddBCAction, "AuxBCs/*", "add_aux_bc");
  registerAction(AddMaterialAction, "Materials/*", "add_material");
  registerAction(AddPostprocessorAction, "Postprocessors/*", "add_postprocessor");
  registerAction(EmptyAction, "Postprocessors/Residual", "no_action");   // placeholder
  registerAction(EmptyAction, "Postprocessors/Jacobian", "no_action");   // placeholder
  registerAction(EmptyAction, "Postprocessors/NewtonIter", "no_action"); // placeholder
  registerAction(AddPostprocessorAction, "Postprocessors/Residual/*", "add_postprocessor");
  registerAction(AddPostprocessorAction, "Postprocessors/Jacobian/*", "add_postprocessor");
  registerAction(AddPostprocessorAction, "Postprocessors/NewtonIter/*", "add_postprocessor");
  registerAction(AddDamperAction, "Dampers/*", "add_damper");
  registerAction(AddStabilizerAction, "Stabilizers/*", "add_stabilizer");
  registerAction(SetupPBPAction, "Preconditioning/PBP", "add_preconditioning");
  registerAction(AdaptivityAction, "Executioner/Adaptivity", "setup_adaptivity");

  registerAction(AddDiracKernelAction, "DiracKernels/*", "add_dirac_kernel");

  // NonParsedActions
  registerNonParsedAction(SetupDampersAction, "setup_dampers");
  registerNonParsedAction(InitProblemAction, "init_problem");
  registerNonParsedAction(CopyNodalVarsAction, "copy_nodal_vars");
  registerNonParsedAction(CheckIntegrityAction, "check_integrity");
}

void
setSolverDefaults(MProblem & problem)
{
#ifdef LIBMESH_HAVE_PETSC
  Moose::PetscSupport::petscSetDefaults(problem);
#endif //LIBMESH_HAVE_PETSC
}

ActionWarehouse action_warehouse;

} // namespace Moose
<commit_msg>Some objects were not registered<commit_after>#include "Moose.h"
#include "Factory.h"
#include "NonlinearSystem.h"
#include "PetscSupport.h"
#include "ActionWarehouse.h"
#include "ActionFactory.h"

// objects that can be created by MOOSE
#include "TimeDerivative.h"
#include "Diffusion.h"
#include "CoupledForce.h"
#include "UserForcingFunction.h"
#include "BodyForce.h"
#include "ImplicitEuler.h"
#include "Reaction.h"
#include "RealPropertyOutput.h"
// bcs
#include "ConvectiveFluxBC.h"
#include "DirichletBC.h"
#include "NeumannBC.h"
#include "FunctionDirichletBC.h"
#include "FunctionNeumannBC.h"
#include "MatchedValueBC.h"
#include "VacuumBC.h"

// auxkernels
#include "CoupledAux.h"
#include "ConstantAux.h"
#include "FunctionAux.h"
#include "NearestNodeDistanceAux.h"
#include "NearestNodeValueAux.h"
#include "PenetrationAux.h"
#include "ProcessorIDAux.h"
#include "GapValueAux.h"

// dirac kernels
#include "ConstantPointSource.h"
// ics
#include "ConstantIC.h"
#include "BoundingBoxIC.h"
#include "FunctionIC.h"
#include "RandomIC.h"
// mesh modifiers
#include "ElementDeleter.h"
// executioners
#include "Steady.h"
#include "Transient.h"
#include "LooseCoupling.h"
#include "SolutionTimeAdaptive.h"
// functions
#include "ParsedFunction.h"
#include "ParsedGradFunction.h"
#include "PiecewiseLinear.h"
#include "SolutionFunction.h"
#include "SphereFunction.h"
// materials
#include "GenericConstantMaterial.h"
// PPS
#include "AverageElementSize.h"
#include "AverageNodalVariableValue.h"
#include "ElementAverageValue.h"
#include "ElementH1Error.h"
#include "ElementH1SemiError.h"
#include "ElementIntegral.h"
#include "ElementL2Error.h"
#include "EmptyPostprocessor.h"
#include "NodalVariableValue.h"
#include "PrintDOFs.h"
#include "PrintDT.h"
#include "PrintNumElems.h"
#include "PrintNumNodes.h"
#include "Reporter.h"
#include "SideAverageValue.h"
#include "SideFluxIntegral.h"
#include "SideIntegral.h"
// stabilizers
#include "ConvectionDiffusionSUPG.h"
// dampers
#include "ConstantDamper.h"
#include "MaxIncrement.h"

// Actions
#include "AddMeshModifierAction.h"
#include "AddBCAction.h"
#include "AddDiracKernelAction.h"
#include "AddICAction.h"
#include "AddKernelAction.h"
#include "AddPeriodicBCAction.h"
#include "AddVariableAction.h"
#include "AddPostprocessorAction.h"
#include "AddDamperAction.h"
#include "AddStabilizerAction.h"
#include "AddFunctionAction.h"
#include "CreateExecutionerAction.h"
#include "CreateMeshAction.h"
#include "EmptyAction.h"
#include "InitProblemAction.h"
#include "CopyNodalVarsAction.h"
#include "SetupMeshAction.h"
#include "SetupOutputAction.h"
#include "AddMaterialAction.h"
#include "GlobalParamsAction.h"
#include "SetupPBPAction.h"
#include "AdaptivityAction.h"
#include "SetupDampersAction.h"
#include "CheckIntegrityAction.h"

namespace Moose {

static bool registered = false;

void
registerObjects()
{
  if (registered)
    return;

  registerObject(TimeDerivative);

  // kernels
  registerObject(Diffusion);
  registerObject(CoupledForce);
  registerObject(UserForcingFunction);
  registerObject(BodyForce);
  registerObject(ImplicitEuler);
  registerObject(Reaction);
  registerObject(RealPropertyOutput);
  // bcs
  registerObject(ConvectiveFluxBC);
  registerObject(DirichletBC);
  registerObject(NeumannBC);
  registerObject(FunctionDirichletBC);
  registerObject(FunctionNeumannBC);
  registerObject(MatchedValueBC);
  registerObject(VacuumBC);
  // dirac kernels
  registerObject(ConstantPointSource);

  // aux kernels
  registerObject(CoupledAux);
  registerObject(ConstantAux);
  registerObject(FunctionAux);
  registerObject(NearestNodeDistanceAux);
  registerObject(NearestNodeValueAux);
  registerObject(PenetrationAux);
  registerObject(ProcessorIDAux);
  registerObject(GapValueAux);

  // Initial Conditions
  registerObject(ConstantIC);
  registerObject(BoundingBoxIC);
  registerObject(FunctionIC);
  registerObject(RandomIC);
  // Mesh Modifiers
  registerObject(ElementDeleter);
  // executioners
  registerObject(Steady);
  registerObject(Transient);
  registerObject(LooseCoupling);
  registerObject(SolutionTimeAdaptive);
  // functions
  registerObject(ParsedFunction);
  registerObject(ParsedGradFunction);
  registerObject(PiecewiseLinear);
  registerObject(SolutionFunction);
  registerObject(SphereFunction);
  // materials
  registerObject(GenericConstantMaterial);
  // PPS
  registerObject(AverageElementSize);
  registerObject(AverageNodalVariableValue);
  registerObject(ElementAverageValue);
  registerObject(ElementH1Error);
  registerObject(ElementH1SemiError);
  registerObject(ElementIntegral);
  registerObject(ElementL2Error);
  registerObject(EmptyPostprocessor);
  registerObject(NodalVariableValue);
  registerObject(PrintDOFs);
  registerObject(PrintDT);
  registerObject(PrintNumElems);
  registerObject(PrintNumNodes);
  registerObject(Reporter);
  registerObject(SideAverageValue);
  registerObject(SideFluxIntegral);
  registerObject(SideIntegral);
  // stabilizers
  registerObject(ConvectionDiffusionSUPG);
  // dampers
  registerObject(ConstantDamper);
  registerObject(MaxIncrement);

  addActionTypes();
  registerActions();

  registered = true;
}

void
addActionTypes()
{
  /**************************/
  /**** Register Actions ****/
  /**************************/
  /// Minimal Problem
  registerActionName("setup_mesh", true);
  registerActionName("add_variable", true);
  registerActionName("add_kernel", true);
  registerActionName("setup_executioner", true);
  registerActionName("setup_output", true);
  registerActionName("init_problem", true);
  registerActionName("copy_nodal_vars", true);
  registerActionName("add_bc", false);  // Does this need to be true?  Not if you have periodic boundaries...
  registerActionName("setup_dampers", true);
  registerActionName("check_integrity", true);

  /// Additional Actions
  registerActionName("no_action", false);  // Used for Empty Action placeholders
  registerActionName("set_global_params", false);
  registerActionName("create_mesh", false);
  registerActionName("add_mesh_modifier", false);
  registerActionName("add_material", false);
  registerActionName("add_function", false);
  registerActionName("add_aux_variable", false);
  registerActionName("add_aux_kernel", false);
  registerActionName("add_aux_bc", false);
  registerActionName("add_dirac_kernel", false);
  registerActionName("add_ic", false);
  registerActionName("add_postprocessor", false);
  registerActionName("add_damper", false);
  registerActionName("add_stabilizer", false);
  registerActionName("add_periodic_bc", false);
  registerActionName("add_preconditioning", false);
  registerActionName("setup_adaptivity", false);

  // Dummy Actions (useful for sync points in the dependencies)
  registerActionName("setup_mesh_complete", false);
  registerActionName("setup_function_complete", false);
  registerActionName("setup_variable_complete", false);
  registerActionName("ready_to_init", false);
  registerActionName("setup_pps_complete", false);

  /**************************/
  /****** Dependencies ******/
  /**************************/

/*
  /// Mesh Actions
  action_warehouse.addDependency("setup_mesh", "create_mesh");
  action_warehouse.addDependency("add_mesh_modifier", "setup_mesh");
  action_warehouse.addDependency("setup_mesh_complete", "setup_mesh");

  /// Executioner
  action_warehouse.addDependency("setup_executioner", "setup_mesh_complete");
  action_warehouse.addDependency("setup_adaptivity", "setup_executioner");

  /// Functions
  action_warehouse.addDependency("add_function", "setup_adaptivity");
  action_warehouse.addDependency("setup_function_complete", "add_function");

  /// Variable Actions
  action_warehouse.addDependency("add_variable", "setup_function_complete");

  /// AuxVariable Actions
  action_warehouse.addDependency("add_aux_variable", "setup_function_complete");
  action_warehouse.addDependency("setup_variable_complete", "add_aux_variable");

  /// ICs
  action_warehouse.addDependency("add_ic", "setup_variable_complete");

  /// PeriodicBCs
  action_warehouse.addDependency("add_periodic_bc", "setup_variable_complete");

  /// Preconditioning
  action_warehouse.addDependency("add_preconditioning", "add_periodic_bc");
  action_warehouse.addDependency("ready_to_init", "add_preconditioning");

  /// InitProblem
  action_warehouse.addDependency("setup_dampers", "ready_to_init");
  action_warehouse.addDependency("init_problem", "setup_dampers");
  action_warehouse.addDependency("copy_nodal_vars", "init_problem");

  /// Materials
  action_warehouse.addDependency("add_material", "copy_nodal_vars");

  /// Postprocessors
  action_warehouse.addDependency("add_postprocessor", "add_material");
  action_warehouse.addDependency("setup_pps_complete", "add_postprocessor");

  /// Dampers
  action_warehouse.addDependency("add_damper", "setup_pps_complete");

  /// Stabilizers
  action_warehouse.addDependency("add_stabilizer", "setup_pps_complete");

  /// Kernels
  action_warehouse.addDependency("add_kernel", "setup_pps_complete");

  /// AuxKernels
  action_warehouse.addDependency("add_aux_kernel", "setup_pps_complete");

  /// BCs
  action_warehouse.addDependency("add_bc", "setup_pps_complete");

  /// AuxBCs
  action_warehouse.addDependency("add_aux_bc", "setup_pps_complete");

  /// Dirac Kernels
  action_warehouse.addDependency("add_dirac_kernel", "setup_pps_complete");

  /// Ouput
  action_warehouse.addDependency("setup_output", "setup_pps_complete");

  /// Check Integrity
  action_warehouse.addDependency("check_integrity", "setup_output");
*/

  /**
   * The following is the default set of action dependencies for a basic MOOSE problem.  The formatting
   * of this string is important.  Each line represents a set of dependencies that depend on the previous
   * line.  Items on the same line have equal weight and can be executed in any order.  */
  action_warehouse.addDependencySets(
"(create_mesh, set_global_params)"
"(setup_mesh)"
"(add_mesh_modifier, setup_mesh_complete)"
"(setup_executioner)"
"(add_function)"
"(setup_function_complete)"
"(add_aux_variable, add_variable)"
"(setup_variable_complete)"
"(setup_adaptivity)"
"(add_ic, add_periodic_bc)"
"(add_preconditioning)"
"(ready_to_init)"
"(setup_dampers)"
"(init_problem)"
"(copy_nodal_vars)"
"(add_material)"
"(add_postprocessor)"
"(setup_pps_complete)"
"(add_aux_bc, add_aux_kernel, add_bc, add_damper, add_dirac_kernel, add_kernel, add_stabilizer, setup_output)"
"(check_integrity)"
);

}

void
registerActions()
{
  registerAction(CreateMeshAction, "Mesh/Generation", "create_mesh");
  registerAction(SetupMeshAction, "Mesh", "setup_mesh");
  registerAction(AddFunctionAction, "Functions/*", "add_function");
  registerAction(CreateExecutionerAction, "Executioner", "setup_executioner");
  registerAction(SetupOutputAction, "Output", "setup_output");
  registerAction(GlobalParamsAction, "GlobalParams", "set_global_params");

  /// MooseObjectActions
  registerAction(AddMeshModifierAction, "Mesh/*", "add_mesh_modifier");
  registerAction(AddVariableAction, "Variables/*", "add_variable");
  registerAction(AddVariableAction, "AuxVariables/*", "add_aux_variable");
  registerAction(AddICAction, "Variables/*/InitialCondition", "add_ic");
  registerAction(AddICAction, "AuxVariables/*/InitialCondition", "add_ic");
  registerAction(AddKernelAction, "Kernels/*", "add_kernel");
  registerAction(AddKernelAction, "AuxKernels/*", "add_aux_kernel");
  registerAction(AddBCAction, "BCs/*", "add_bc");
  registerAction(EmptyAction, "BCs/Periodic", "no_action");  // placeholder
  registerAction(AddPeriodicBCAction, "BCs/Periodic/*", "add_periodic_bc");
  registerAction(AddBCAction, "AuxBCs/*", "add_aux_bc");
  registerAction(AddMaterialAction, "Materials/*", "add_material");
  registerAction(AddPostprocessorAction, "Postprocessors/*", "add_postprocessor");
  registerAction(EmptyAction, "Postprocessors/Residual", "no_action");   // placeholder
  registerAction(EmptyAction, "Postprocessors/Jacobian", "no_action");   // placeholder
  registerAction(EmptyAction, "Postprocessors/NewtonIter", "no_action"); // placeholder
  registerAction(AddPostprocessorAction, "Postprocessors/Residual/*", "add_postprocessor");
  registerAction(AddPostprocessorAction, "Postprocessors/Jacobian/*", "add_postprocessor");
  registerAction(AddPostprocessorAction, "Postprocessors/NewtonIter/*", "add_postprocessor");
  registerAction(AddDamperAction, "Dampers/*", "add_damper");
  registerAction(AddStabilizerAction, "Stabilizers/*", "add_stabilizer");
  registerAction(SetupPBPAction, "Preconditioning/PBP", "add_preconditioning");
  registerAction(AdaptivityAction, "Executioner/Adaptivity", "setup_adaptivity");

  registerAction(AddDiracKernelAction, "DiracKernels/*", "add_dirac_kernel");

  // NonParsedActions
  registerNonParsedAction(SetupDampersAction, "setup_dampers");
  registerNonParsedAction(InitProblemAction, "init_problem");
  registerNonParsedAction(CopyNodalVarsAction, "copy_nodal_vars");
  registerNonParsedAction(CheckIntegrityAction, "check_integrity");
}

void
setSolverDefaults(MProblem & problem)
{
#ifdef LIBMESH_HAVE_PETSC
  Moose::PetscSupport::petscSetDefaults(problem);
#endif //LIBMESH_HAVE_PETSC
}

ActionWarehouse action_warehouse;

} // namespace Moose
<|endoftext|>


<commit_before>#include "Platform.hpp"

#include <cmath>

#include "util/Log.hpp"

using Diggler::Util::Log;
using namespace Diggler::Util::Logging::LogLevels;

static const char *TAG = "Platform";

const char *Diggler::UserdataDirsName = "Diggler";

static struct PathCache {
  std::string
    executableBin,
    executableDir,
    configDir,
    cacheDir;
} pathCache;

#if defined(BUILDINFO_PLATFORM_WINDOWS) // Windows

#include <cmath>
#include <cstring>
#include <shlobj.h>
#include <windows.h>
#include "platform/Fixes.hpp"

std::string Diggler::proc::getExecutablePath() {
  if (pathCache.executableBin.length() == 0) {
    HMODULE hModule = GetModuleHandleW(NULL);
    WCHAR path[MAX_PATH];
    GetModuleFileNameW(hModule, path, MAX_PATH);
    char utf8Path[MAX_PATH];
    WideCharToMultiByte(CP_UTF8, 0, path, -1, utf8Path, MAX_PATH, nullptr, nullptr);
    pathCache.executableBin = utf8Path;
  }
  return pathCache.executableBin;
}

std::string Diggler::proc::getExecutableDirectory() {
  if (pathCache.executableDir.length() == 0) {
    std::string filename(getExecutablePath());
    const size_t last_sep_idx = std::max(filename.rfind('/'), filename.rfind('\\'));
    if (last_sep_idx != std::string::npos) {
      pathCache.executableDir = filename.substr(0, last_sep_idx);
    } else {
      Log(Warning, TAG) << "Ill-formed executable path: " << filename;
      pathCache.executableDir = filename;
    }
  }
  return pathCache.executableDir;
}

std::string Diggler::getCacheDirectory() {
  if (pathCache.cacheDir.length() == 0) {
    WCHAR ucs2Path[MAX_PATH];
    SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, 0, ucs2Path);
    char utf8Path[MAX_PATH];
    WideCharToMultiByte(CP_UTF8, 0, ucs2Path, -1, utf8Path, MAX_PATH, nullptr, nullptr);
    pathCache.cacheDir = std::string(utf8Path) + "/" + UserdataDirsName + "/cache/";
  }
  return pathCache.cacheDir;
}

std::string Diggler::getConfigDirectory() {
  if (pathCache.cacheDir.length() == 0) {
    WCHAR ucs2Path[MAX_PATH];
    SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, 0, ucs2Path);
    char utf8Path[MAX_PATH];
    WideCharToMultiByte(CP_UTF8, 0, ucs2Path, -1, utf8Path, MAX_PATH, nullptr, nullptr);
    pathCache.configDir = std::string(utf8Path) + "/" + UserdataDirsName + "/config/";
  }
  return pathCache.configDir;
}

#elif defined(BUILDINFO_PLATFORM_UNIXLIKE) // Linux and UNIX alike

#include <sstream>
#include <unistd.h>
#include <dirent.h>
#include <cstdio>

std::string do_readlink(const char *path);
std::string do_readlink(const std::string &path);

#if defined(BUILDINFO_PLATFORM_LINUX)
std::string Diggler::proc::getExecutablePath() {
  if (pathCache.executableBin.length() == 0) {
    pid_t pid = getpid();
    // Assuming 32-bit pid -> max of 10 digits, we need only "/proc/xxxxxxxxxx/exe" space
    char path[21];
    std::snprintf(path, 21, "/proc/%d/exe", pid);
    pathCache.executableBin = do_readlink(path);
  }
  return pathCache.executableBin;
}
#else
// TODO: getExecutablePath for those without procfs
#endif

std::string Diggler::proc::getExecutableDirectory() {
  if (pathCache.executableDir.length() == 0) {
    std::string filename(getExecutablePath());
    const size_t last_slash_idx = filename.rfind('/');
    if (last_slash_idx != std::string::npos) {
      pathCache.executableDir = filename.substr(0, last_slash_idx);
    } else {
      Log(Warning, TAG) << "Ill-formed executable path: " << filename;
      pathCache.executableDir = filename;
    }
  }
  return pathCache.executableDir;
}

std::string Diggler::getCacheDirectory() {
  if (pathCache.cacheDir.length() == 0) {
    const char *xdgCache = std::getenv("XDG_CACHE_HOME");
    if (xdgCache) {
      pathCache.cacheDir = std::string(xdgCache) + "/" + UserdataDirsName;
    } else {
      pathCache.cacheDir = std::string(std::getenv("HOME")) + "/.cache/" + UserdataDirsName;
    }
  }
  return pathCache.cacheDir;
}

std::string Diggler::getConfigDirectory() {
  if (pathCache.configDir.length() == 0) {
    const char *xdgCache = std::getenv("XDG_CONFIG_HOME");
    if (xdgCache) {
      pathCache.configDir = std::string(xdgCache) + "/" + UserdataDirsName;
    } else {
      pathCache.configDir = std::string(std::getenv("HOME")) + "/.config/" + UserdataDirsName;
    }
  }
  return pathCache.configDir;
}

#elif defined(BUILDINFO_PLATFORM_MAC) // Mac

// Put Mac code here

#else // Any other

// Stub?

#endif

namespace Diggler {

std::string getAssetsDirectory() {
  return proc::getExecutableDirectory() + "/assets";
}

std::string getAssetsDirectory(const std::string &type) {
  return proc::getExecutableDirectory() + "/assets/" + type + '/';
}

std::string getAssetPath(const std::string &name) {
  return proc::getExecutableDirectory() + "/assets/" + name;
}

std::string getAssetPath(const std::string &type, const std::string &name) {
  return proc::getExecutableDirectory() + "/assets/" + type + '/' + name;
}

float rmod(float x, float y) {
  float ret = fmod(x, y);
  if (ret < 0)
    return y+ret;
  return ret;
}

double rmod(double x, double y) {
  double ret = fmod(x, y);
  if (ret < 0)
    return y+ret;
  return ret;
}

}
<commit_msg>Windows: fix Diggler::proc::getExecutableDirectory failing<commit_after>#include "Platform.hpp"

#include <cmath>

#include "util/Log.hpp"

using Diggler::Util::Log;
using namespace Diggler::Util::Logging::LogLevels;

static const char *TAG = "Platform";

const char *Diggler::UserdataDirsName = "Diggler";

static struct PathCache {
  std::string
    executableBin,
    executableDir,
    configDir,
    cacheDir;
} pathCache;

#if defined(BUILDINFO_PLATFORM_WINDOWS) // Windows

#include <cmath>
#include <cstring>
#include <shlobj.h>
#include <windows.h>
#include "platform/Fixes.hpp"

std::string Diggler::proc::getExecutablePath() {
  if (pathCache.executableBin.length() == 0) {
    HMODULE hModule = GetModuleHandleW(NULL);
    WCHAR path[MAX_PATH];
    GetModuleFileNameW(hModule, path, MAX_PATH);
    char utf8Path[MAX_PATH];
    WideCharToMultiByte(CP_UTF8, 0, path, -1, utf8Path, MAX_PATH, nullptr, nullptr);
    pathCache.executableBin = utf8Path;
  }
  return pathCache.executableBin;
}

std::string Diggler::proc::getExecutableDirectory() {
  if (pathCache.executableDir.length() == 0) {
    std::string filename(getExecutablePath());
    const size_t last_sep_idx = filename.rfind('\\');
    if (last_sep_idx != std::string::npos) {
      pathCache.executableDir = filename.substr(0, last_sep_idx);
    } else {
      Log(Warning, TAG) << "Ill-formed executable path: " << filename;
      pathCache.executableDir = filename;
    }
  }
  return pathCache.executableDir;
}

std::string Diggler::getCacheDirectory() {
  if (pathCache.cacheDir.length() == 0) {
    WCHAR ucs2Path[MAX_PATH];
    SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, 0, ucs2Path);
    char utf8Path[MAX_PATH];
    WideCharToMultiByte(CP_UTF8, 0, ucs2Path, -1, utf8Path, MAX_PATH, nullptr, nullptr);
    pathCache.cacheDir = std::string(utf8Path) + "/" + UserdataDirsName + "/cache/";
  }
  return pathCache.cacheDir;
}

std::string Diggler::getConfigDirectory() {
  if (pathCache.cacheDir.length() == 0) {
    WCHAR ucs2Path[MAX_PATH];
    SHGetFolderPath(nullptr, CSIDL_APPDATA, nullptr, 0, ucs2Path);
    char utf8Path[MAX_PATH];
    WideCharToMultiByte(CP_UTF8, 0, ucs2Path, -1, utf8Path, MAX_PATH, nullptr, nullptr);
    pathCache.configDir = std::string(utf8Path) + "/" + UserdataDirsName + "/config/";
  }
  return pathCache.configDir;
}

#elif defined(BUILDINFO_PLATFORM_UNIXLIKE) // Linux and UNIX alike

#include <sstream>
#include <unistd.h>
#include <dirent.h>
#include <cstdio>

std::string do_readlink(const char *path);
std::string do_readlink(const std::string &path);

#if defined(BUILDINFO_PLATFORM_LINUX)
std::string Diggler::proc::getExecutablePath() {
  if (pathCache.executableBin.length() == 0) {
    pid_t pid = getpid();
    // Assuming 32-bit pid -> max of 10 digits, we need only "/proc/xxxxxxxxxx/exe" space
    char path[21];
    std::snprintf(path, 21, "/proc/%d/exe", pid);
    pathCache.executableBin = do_readlink(path);
  }
  return pathCache.executableBin;
}
#else
// TODO: getExecutablePath for those without procfs
#endif

std::string Diggler::proc::getExecutableDirectory() {
  if (pathCache.executableDir.length() == 0) {
    std::string filename(getExecutablePath());
    const size_t last_slash_idx = filename.rfind('/');
    if (last_slash_idx != std::string::npos) {
      pathCache.executableDir = filename.substr(0, last_slash_idx);
    } else {
      Log(Warning, TAG) << "Ill-formed executable path: " << filename;
      pathCache.executableDir = filename;
    }
  }
  return pathCache.executableDir;
}

std::string Diggler::getCacheDirectory() {
  if (pathCache.cacheDir.length() == 0) {
    const char *xdgCache = std::getenv("XDG_CACHE_HOME");
    if (xdgCache) {
      pathCache.cacheDir = std::string(xdgCache) + "/" + UserdataDirsName;
    } else {
      pathCache.cacheDir = std::string(std::getenv("HOME")) + "/.cache/" + UserdataDirsName;
    }
  }
  return pathCache.cacheDir;
}

std::string Diggler::getConfigDirectory() {
  if (pathCache.configDir.length() == 0) {
    const char *xdgCache = std::getenv("XDG_CONFIG_HOME");
    if (xdgCache) {
      pathCache.configDir = std::string(xdgCache) + "/" + UserdataDirsName;
    } else {
      pathCache.configDir = std::string(std::getenv("HOME")) + "/.config/" + UserdataDirsName;
    }
  }
  return pathCache.configDir;
}

#elif defined(BUILDINFO_PLATFORM_MAC) // Mac

// Put Mac code here

#else // Any other

// Stub?

#endif

namespace Diggler {

std::string getAssetsDirectory() {
  return proc::getExecutableDirectory() + "/assets";
}

std::string getAssetsDirectory(const std::string &type) {
  return proc::getExecutableDirectory() + "/assets/" + type + '/';
}

std::string getAssetPath(const std::string &name) {
  return proc::getExecutableDirectory() + "/assets/" + name;
}

std::string getAssetPath(const std::string &type, const std::string &name) {
  return proc::getExecutableDirectory() + "/assets/" + type + '/' + name;
}

float rmod(float x, float y) {
  float ret = fmod(x, y);
  if (ret < 0)
    return y+ret;
  return ret;
}

double rmod(double x, double y) {
  double ret = fmod(x, y);
  if (ret < 0)
    return y+ret;
  return ret;
}

}
<|endoftext|>


<commit_before>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef Transform_INCLUDE_ONCE
#define Transform_INCLUDE_ONCE

#include <vl/vlnamespace.hpp>
#include <vl/Object.hpp>
#include <vl/Matrix4.hpp>
#include <vector>

namespace vl
{
  class Camera;

  //------------------------------------------------------------------------------
  // Transform
  //------------------------------------------------------------------------------
  /** Implements a 4x4 matrix transform used to define the position and orientation of an Actor.
    *
    * Transforms can be linked together to create a tree-like hierarchy.
    *
    * \par Optimizing Your Transforms
    *
    * - Don't use them unless strictly necessary: if an Actor uses an I (identity) transform you do not need one, just call \p vl::Actor::setTransform(NULL).
    *
    * - Don't create Transform hierarchies if not needed. Just call setLocalAndWorldMatrix() per-Transform if you have a set of parent-less Transforms.
    *
    * - If the root of a hierarchy is an I (identity) transform, let VL know it by calling \p setAssumeIdentityWorldMatrix(true). This will save
    *   unnecessary matrix multiplications since multiplying by an identity matrix has no effect.
    *
    * - Call computeWorldMatrix() / computeWorldMatrixRecursive() not at each frame but only if the local matrix has actually changed.
    *
    * - Do not add a Transform hierarchy to vl::Rendering::transform() if such Transforms are not animated every frame,
    *   this will cause VL unnecessarily update the Transforms at each frame.
    *
    * - Remember: VL does not require your Actors to have a Transform or such Transforms to be part of any hierarchy, it just expect that the
    *   worldMatrix() of an Actor's Transform (if it has any) is up to date at rendering time. How and when they are updated can be fine
    *   tuned by the user according to the specific application needs.
    *
    * \sa setLocalAndWorldMatrix(), setAssumeIdentityWorldMatrix(), Rendering::transform()
    * \sa Actor, Rendering, Effect, Renderable, Geometry */
  class Transform: public Object
  {
  public:
    virtual const char* className() { return "Transform"; }

    /** Constructor. */
    Transform(): mParent(NULL), mWorldMatrixUpdateTick(0), mAssumeIdentityWorldMatrix(false)
    {
      #ifndef NDEBUG
        mObjectName = className();
      #endif
    }

    /** Constructor. The \p matrix parameter is used to set both the local and world matrix. */
    Transform(const mat4& matrix): mParent(NULL), mAssumeIdentityWorldMatrix(false)
    {
      setLocalMatrix(matrix);
      setWorldMatrix(matrix);
      #ifndef NDEBUG
        mObjectName = className();
      #endif
    }

    /** Returns the children Transforms. */
    const std::vector< ref<Transform> >& children() const { return mChildren; }

    /** Adds a child transform. */
    void addChild(Transform* child);

    /** Adds \p count children transforms. */
    void addChildren(Transform* const *, size_t count);

    /** Adds \p count children transforms. */
    void addChildren(const ref<Transform>*, size_t count);

    /** Adds the specified \p children transforms. */
    void addChildren(const std::vector< Transform* >& children);

    /** Adds the specified \p children transforms. */
    void addChildren(const std::vector< ref<Transform> >& children);

    /** Minimizes the amount of memory used to store the children Transforms. */
    void shrink();

    /** Minimizes recursively the amount of memory used to store the children Transforms. */
    void shrinkRecursive();

    /** Sets the \p index-th child. */
    void setChild(int index, Transform* child);

    /** Returns the number of children a Transform has. */
    int childCount() const;

    /** Returns the i-th child Transform. */
    Transform* child(int i);

    /** Returns the last child. */
    Transform* lastChild();

    /** Removes the given \p child Transform. */
    void eraseChild(Transform* child);

    /** Removes \p count children Transforms starting at position \p index. */
    void eraseChildren(int index, int count);

    /** Removes all the children of a Transform. */
    void eraseAllChildren();

    /** Removes all the children of a Transform recursively descending the hierachy. */
    void eraseAllChildrenRecursive();

    /** Returns the parent of a Transform. */
    const Transform* parent() const { return mParent; }

    /** Returns the parent of a Transform. */
    Transform* parent() { return mParent; }

    /** Returns the matrix computed concatenating this Transform's local matrix with its parents' local matrices. */
    mat4 getComputedWorldMatrix();

    /** Returns the local matrix. */
    const mat4& localMatrix() const;

    /** Sets the local matrix.
      * After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
    void setLocalMatrix(const mat4& matrix);

    /** Utility function equivalent to \p setLocalMatrix( mat4::translation(x,y,z)*localMatrix() ).
      * After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
    void translate(Real x, Real y, Real z);

    /** Utility function equivalent to \p setLocalMatrix( mat4::translation(t)*localMatrix() ).
      * After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
    void translate(const vec3& t);

    /** Utility function equivalent to \p setLocalMatrix( mat4::scaling(x,y,z)*localMatrix() ).
      * After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
    void scale(Real x, Real y, Real z);

    /** Utility function equivalent to \p setLocalMatrix( mat4::rotation(degrees,x,y,z)*localMatrix() ).
      * After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
    void rotate(Real degrees, Real x, Real y, Real z);

    /** Utility function equivalent to \p setLocalMatrix( mat4::rotation(from,to)*localMatrix() ).
      * After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
    void rotate(const vec3& from, const vec3& to);

    /** Sets both the local and the world matrices.
      * This function is useful to quickly set those Transforms that do not have a parent, for which
      * is equivalent to: \p setLocalMatrix(matrix); \p computeWorldMatrix(NULL); */
    void setLocalAndWorldMatrix(const mat4& matrix)
    {
      mLocalMatrix = matrix;
      setWorldMatrix(matrix);
    }

    /** Computes the world matrix by concatenating the parent's world matrix with this' local matrix. */
    virtual void computeWorldMatrix(Camera* camera=NULL);

    /** Computes the world matrix by concatenating the parent's world matrix with this' local matrix, recursively descending to the children. */
    void computeWorldMatrixRecursive(Camera* camera=NULL);

    /** Returns the world matrix used for rendering. */
    const mat4& worldMatrix() const;

    /** Returns the internal update tick used to avoid unnecessary computations. The world matrix thick
      * gets incremented every time the setWorldMatrix() or setLocalAndWorldMatrix() functions are called. */
    long long worldMatrixUpdateTick() const { return mWorldMatrixUpdateTick; }

    /** If set to true the world matrix of this transform will always be considered and identity.
      * Is usually used to save calculations for top Transforms with many sub-Transforms. */
    void setAssumeIdentityWorldMatrix(bool assume_I) { mAssumeIdentityWorldMatrix = assume_I; }

    /** If set to true the world matrix of this transform will always be considered and identity.
      * Is usually used to save calculations for top Transforms with many sub-Transforms. */
    bool assumeIdentityWorldMatrix() { return mAssumeIdentityWorldMatrix; }

    /** Checks whether there are duplicated entries in the Transform's children list. */
    bool hasDuplicatedChildren() const;

    /** Normally you should not use directly this function, call it only if you are sure you cannot do otherwise.
      * Calling this function will also increment the worldMatrixUpdateTick(). */
    void setWorldMatrix(const mat4& matrix);

  protected:
    mat4 mWorldMatrix;
    mat4 mLocalMatrix;
    std::vector< ref<Transform> > mChildren;
    Transform* mParent;
    long long mWorldMatrixUpdateTick;
    bool mAssumeIdentityWorldMatrix;
  };
}

#endif
<commit_msg>added Transform::reserveChildren() function.<commit_after>/**************************************************************************************/
/*                                                                                */
/*  Visualization Library                                                             */
/*  http://www.visualizationlibrary.com                                               */
/*                                                                                */
/*  Copyright (c) 2005-2010, Michele Bosi                                             */
/*  All rights reserved.                                                              */
/*                                                                                */
/*  Redistribution and use in source and binary forms, with or without modification,  */
/*  are permitted provided that the following conditions are met:                     */
/*                                                                                */
/*  - Redistributions of source code must retain the above copyright notice, this     */
/*  list of conditions and the following disclaimer.                                  */
/*                                                                                */
/*  - Redistributions in binary form must reproduce the above copyright notice, this  */
/*  list of conditions and the following disclaimer in the documentation and/or       */
/*  other materials provided with the distribution.                                   */
/*                                                                                */
/*  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND   */
/*  ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED     */
/*  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE            */
/*  DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR  */
/*  ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES    */
/*  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;      */
/*  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON    */
/*  ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT           */
/*  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS     */
/*  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.                      */
/*                                                                                */
/**************************************************************************************/

#ifndef Transform_INCLUDE_ONCE
#define Transform_INCLUDE_ONCE

#include <vl/vlnamespace.hpp>
#include <vl/Object.hpp>
#include <vl/Matrix4.hpp>
#include <vector>

namespace vl
{
  class Camera;

  //------------------------------------------------------------------------------
  // Transform
  //------------------------------------------------------------------------------
  /** Implements a 4x4 matrix transform used to define the position and orientation of an Actor.
    *
    * Transforms can be linked together to create a tree-like hierarchy.
    *
    * \par Optimizing Your Transforms
    *
    * - Don't use them unless strictly necessary: if an Actor uses an I (identity) transform you do not need one, just call \p vl::Actor::setTransform(NULL).
    *
    * - Don't create Transform hierarchies if not needed. Just call setLocalAndWorldMatrix() per-Transform if you have a set of parent-less Transforms.
    *
    * - If the root of a hierarchy is an I (identity) transform, let VL know it by calling \p setAssumeIdentityWorldMatrix(true). This will save
    *   unnecessary matrix multiplications since multiplying by an identity matrix has no effect.
    *
    * - Call computeWorldMatrix() / computeWorldMatrixRecursive() not at each frame but only if the local matrix has actually changed.
    *
    * - Do not add a Transform hierarchy to vl::Rendering::transform() if such Transforms are not animated every frame,
    *   this will cause VL unnecessarily update the Transforms at each frame.
    *
    * - Remember: VL does not require your Actors to have a Transform or such Transforms to be part of any hierarchy, it just expect that the
    *   worldMatrix() of an Actor's Transform (if it has any) is up to date at rendering time. How and when they are updated can be fine
    *   tuned by the user according to the specific application needs.
    *
    * \sa setLocalAndWorldMatrix(), setAssumeIdentityWorldMatrix(), Rendering::transform()
    * \sa Actor, Rendering, Effect, Renderable, Geometry */
  class Transform: public Object
  {
  public:
    virtual const char* className() { return "Transform"; }

    /** Constructor. */
    Transform(): mParent(NULL), mWorldMatrixUpdateTick(0), mAssumeIdentityWorldMatrix(false)
    {
      #ifndef NDEBUG
        mObjectName = className();
      #endif
    }

    /** Constructor. The \p matrix parameter is used to set both the local and world matrix. */
    Transform(const mat4& matrix): mParent(NULL), mAssumeIdentityWorldMatrix(false)
    {
      setLocalMatrix(matrix);
      setWorldMatrix(matrix);
      #ifndef NDEBUG
        mObjectName = className();
      #endif
    }

    /** Returns the children Transforms. */
    const std::vector< ref<Transform> >& children() const { return mChildren; }

    /** Adds a child transform. */
    void addChild(Transform* child);

    /** Adds \p count children transforms. */
    void addChildren(Transform* const *, size_t count);

    /** Adds \p count children transforms. */
    void addChildren(const ref<Transform>*, size_t count);

    /** Adds the specified \p children transforms. */
    void addChildren(const std::vector< Transform* >& children);

    /** Adds the specified \p children transforms. */
    void addChildren(const std::vector< ref<Transform> >& children);

    /** Minimizes the amount of memory used to store the children Transforms. */
    void shrink();

    /** Minimizes recursively the amount of memory used to store the children Transforms. */
    void shrinkRecursive();

    /** Reserves space for \p count children. This function is very useful when you need to add one by one a large number of children transforms.
      * \note This function does not affect the number of children, it only reallocates the buffer used to store them
      * so that it's large enough to \p eventually contain \p count of them. This will make subsequent calls to addChild() quicker
      * as fewer or no reallocations of the buffer will be needed. */
    void reserveChildren(size_t count) { mChildren.reserve(count); }

    /** Sets the \p index-th child. */
    void setChild(int index, Transform* child);

    /** Returns the number of children a Transform has. */
    int childCount() const;

    /** Returns the i-th child Transform. */
    Transform* child(int i);

    /** Returns the last child. */
    Transform* lastChild();

    /** Removes the given \p child Transform. */
    void eraseChild(Transform* child);

    /** Removes \p count children Transforms starting at position \p index. */
    void eraseChildren(int index, int count);

    /** Removes all the children of a Transform. */
    void eraseAllChildren();

    /** Removes all the children of a Transform recursively descending the hierachy. */
    void eraseAllChildrenRecursive();

    /** Returns the parent of a Transform. */
    const Transform* parent() const { return mParent; }

    /** Returns the parent of a Transform. */
    Transform* parent() { return mParent; }

    /** Returns the matrix computed concatenating this Transform's local matrix with its parents' local matrices. */
    mat4 getComputedWorldMatrix();

    /** Returns the local matrix. */
    const mat4& localMatrix() const;

    /** Sets the local matrix.
      * After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
    void setLocalMatrix(const mat4& matrix);

    /** Utility function equivalent to \p setLocalMatrix( mat4::translation(x,y,z)*localMatrix() ).
      * After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
    void translate(Real x, Real y, Real z);

    /** Utility function equivalent to \p setLocalMatrix( mat4::translation(t)*localMatrix() ).
      * After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
    void translate(const vec3& t);

    /** Utility function equivalent to \p setLocalMatrix( mat4::scaling(x,y,z)*localMatrix() ).
      * After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
    void scale(Real x, Real y, Real z);

    /** Utility function equivalent to \p setLocalMatrix( mat4::rotation(degrees,x,y,z)*localMatrix() ).
      * After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
    void rotate(Real degrees, Real x, Real y, Real z);

    /** Utility function equivalent to \p setLocalMatrix( mat4::rotation(from,to)*localMatrix() ).
      * After calling this you might want to call computeWorldMatrix() or computeWorldMatrixRecursive(). */
    void rotate(const vec3& from, const vec3& to);

    /** Sets both the local and the world matrices.
      * This function is useful to quickly set those Transforms that do not have a parent, for which
      * is equivalent to: \p setLocalMatrix(matrix); \p computeWorldMatrix(NULL); */
    void setLocalAndWorldMatrix(const mat4& matrix)
    {
      mLocalMatrix = matrix;
      setWorldMatrix(matrix);
    }

    /** Computes the world matrix by concatenating the parent's world matrix with this' local matrix. */
    virtual void computeWorldMatrix(Camera* camera=NULL);

    /** Computes the world matrix by concatenating the parent's world matrix with this' local matrix, recursively descending to the children. */
    void computeWorldMatrixRecursive(Camera* camera=NULL);

    /** Returns the world matrix used for rendering. */
    const mat4& worldMatrix() const;

    /** Returns the internal update tick used to avoid unnecessary computations. The world matrix thick
      * gets incremented every time the setWorldMatrix() or setLocalAndWorldMatrix() functions are called. */
    long long worldMatrixUpdateTick() const { return mWorldMatrixUpdateTick; }

    /** If set to true the world matrix of this transform will always be considered and identity.
      * Is usually used to save calculations for top Transforms with many sub-Transforms. */
    void setAssumeIdentityWorldMatrix(bool assume_I) { mAssumeIdentityWorldMatrix = assume_I; }

    /** If set to true the world matrix of this transform will always be considered and identity.
      * Is usually used to save calculations for top Transforms with many sub-Transforms. */
    bool assumeIdentityWorldMatrix() { return mAssumeIdentityWorldMatrix; }

    /** Checks whether there are duplicated entries in the Transform's children list. */
    bool hasDuplicatedChildren() const;

    /** Normally you should not use directly this function, call it only if you are sure you cannot do otherwise.
      * Calling this function will also increment the worldMatrixUpdateTick(). */
    void setWorldMatrix(const mat4& matrix);

  protected:
    mat4 mWorldMatrix;
    mat4 mLocalMatrix;
    std::vector< ref<Transform> > mChildren;
    Transform* mParent;
    long long mWorldMatrixUpdateTick;
    bool mAssumeIdentityWorldMatrix;
  };
}

#endif
<|endoftext|>


<commit_before>/**
 * @brief This file is the execution node of the Human Tracking
 * @copyright Copyright (2011) Willow Garage
 * @authors Koen Buys, Anatoly Baksheev
 **/
#include <pcl/pcl_base.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/common/time.h>
#include <pcl/console/parse.h>
#include <pcl/io/pcd_io.h>
#include <pcl/gpu/people/people_detector.h>
#include <pcl/visualization/image_viewer.h>
#include <boost/lexical_cast.hpp>

#include <pcl/io/png_io.h>

#include <iostream>

using namespace pcl::visualization;
using namespace pcl::console;
using namespace std;

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

class PeoplePCDApp
{
public:
  typedef pcl::gpu::people::PeopleDetector PeopleDetector;

  enum { COLS = 640, ROWS = 480 };

  PeoplePCDApp () : counter_(0), cmap_device_(ROWS, COLS), final_view_("Final labeling")//, image_view_("Input image")
  {
    final_view_.setSize (COLS, ROWS);
    //image_view_.setSize (COLS, ROWS);

    final_view_.setPosition (0, 0);
    //image_view_.setPosition (650, 0);
  }

 void cloud_cb (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
 {
   people_detector_.process(cloud);
   ++counter_;

   //visualizeAndWrite(cloud);
 }

 void
 visualizeAndWrite(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
 {
   const pcl::gpu::people::RDFBodyPartsDetector::Labels& labels = people_detector_.rdf_detector_->getLabels();
   people_detector_.rdf_detector_->colorizeLabels(labels, cmap_device_);

   int c;
   pcl::PointCloud<pcl::RGB> cmap(cmap_device_.cols(), cmap_device_.rows());
   cmap_device_.download(cmap.points, c);

   final_view_.showRGBImage<pcl::RGB>(cmap);
   final_view_.spinOnce(1, true);

   //image_view_.showRGBImage<pcl::PointXYZRGB>(cloud);
   //image_view_.spinOnce(1, true);

   savePNGFile("ii_" + boost::lexical_cast<string>(counter_) + ".png", *cloud);
   savePNGFile("c2_" + boost::lexical_cast<string>(counter_) + ".png", cmap);
   savePNGFile("s2_" + boost::lexical_cast<string>(counter_) + ".png", labels);

   savePNGFile("d_"  + boost::lexical_cast<string>(counter_) + ".png", people_detector_.depth_device1_);
   savePNGFile("d2_" + boost::lexical_cast<string>(counter_) + ".png", people_detector_.depth_device2_);
 }

  template<typename T>
  void savePNGFile(const std::string& filename, const pcl::gpu::DeviceArray2D<T>& arr)
  {
    int c;
    pcl::PointCloud<T> cloud(arr.cols(), arr.rows());
    arr.download(cloud.points, c);
    pcl::io::savePNGFile(filename, cloud);
  }

  template <typename T> void
  savePNGFile (const std::string& filename, const pcl::PointCloud<T>& cloud)
  {
    pcl::io::savePNGFile(filename, cloud);
  }

  int counter_;
  PeopleDetector people_detector_;
  PeopleDetector::Image cmap_device_;

  ImageViewer final_view_;
  //ImageViewer image_view_;
};

void print_help()
{
  cout << "\nPeople tracking app options:" << endl;
  cout << "\t -numTrees \t<int> \tnumber of trees to load" << endl;
  cout << "\t -tree0 \t<path_to_tree_file>" << endl;
  cout << "\t -tree1 \t<path_to_tree_file>" << endl;
  cout << "\t -tree2 \t<path_to_tree_file>" << endl;
  cout << "\t -tree3 \t<path_to_tree_file>" << endl;
  cout << "\t -pcd   \t<path_to_pcd_file>" << endl;
}

int main(int argc, char** argv)
{
  if(find_switch (argc, argv, "--help") || find_switch (argc, argv, "-h"))
    return print_help(), 0;

  std::string treeFilenames[4] =
  {
    "d:/TreeData/results/forest1/tree_20.txt",
    "d:/TreeData/results/forest3/tree_20.txt",
    "d:/TreeData/results/forest3/tree_20.txt",
    "d:/TreeData/results/forest3/tree_20.txt"
  };
  int numTrees = 4;
  parse_argument (argc, argv, "-numTrees", numTrees);
  parse_argument (argc, argv, "-tree0", treeFilenames[0]);
  parse_argument (argc, argv, "-tree1", treeFilenames[1]);
  parse_argument (argc, argv, "-tree2", treeFilenames[2]);
  parse_argument (argc, argv, "-tree3", treeFilenames[3]);

  if (numTrees == 0 || numTrees > 4)
      return cout << "Invalid number of trees" << endl, -1;

  string pcdname = "d:/git/pcl/gpu/people/tools/test.pcd";
  parse_argument (argc, argv, "-pcd", pcdname);

  // loading cloud file
  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
  int res = pcl::io::loadPCDFile<pcl::PointXYZRGB> (pcdname, *cloud);
  if (res == -1) //* load the file
    return cout << "Couldn't read tree file" << endl, -1;

  cout << "Loaded " << cloud->width * cloud->height << " data points from " << pcdname << endl;

  // loading trees
  using pcl::gpu::people::RDFBodyPartsDetector;
  vector<string> names_vector(treeFilenames, treeFilenames + numTrees);
  RDFBodyPartsDetector::Ptr rdf(new RDFBodyPartsDetector(names_vector));

  // Create the app
  PeoplePCDApp app;
  app.people_detector_.rdf_detector_ = rdf;

  /// Run the app
  {
    pcl::ScopeTime frame_time("frame_time");
    app.cloud_cb(cloud);
  }

  app.visualizeAndWrite(cloud);
  app.final_view_.spin();

  return 0;
}
<commit_msg>compilation<commit_after>/**
 * @brief This file is the execution node of the Human Tracking
 * @copyright Copyright (2011) Willow Garage
 * @authors Koen Buys, Anatoly Baksheev
 **/
#include <pcl/pcl_base.h>
#include <pcl/point_types.h>
#include <pcl/point_cloud.h>
#include <pcl/common/time.h>
#include <pcl/console/parse.h>
#include <pcl/io/pcd_io.h>
#include <pcl/gpu/people/people_detector.h>
#include <pcl/visualization/image_viewer.h>
#include <boost/lexical_cast.hpp>

#include <pcl/io/png_io.h>

#include <iostream>

using namespace pcl::visualization;
using namespace pcl::console;
using namespace std;

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

class PeoplePCDApp
{
public:
  typedef pcl::gpu::people::PeopleDetector PeopleDetector;

  enum { COLS = 640, ROWS = 480 };

  PeoplePCDApp () : counter_(0), cmap_device_(ROWS, COLS), final_view_("Final labeling")//, image_view_("Input image")
  {
    final_view_.setSize (COLS, ROWS);
    //image_view_.setSize (COLS, ROWS);

    final_view_.setPosition (0, 0);
    //image_view_.setPosition (650, 0);
  }

 void cloud_cb (const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
 {
   people_detector_.process(cloud);
   ++counter_;

   //visualizeAndWrite(cloud);
 }

 void
 visualizeAndWrite(const pcl::PointCloud<pcl::PointXYZRGB>::ConstPtr &cloud)
 {
   const pcl::gpu::people::RDFBodyPartsDetector::Labels& labels = people_detector_.rdf_detector_->getLabels();
   people_detector_.rdf_detector_->colorizeLabels(labels, cmap_device_);

   int c;
   pcl::PointCloud<pcl::RGB> cmap(cmap_device_.cols(), cmap_device_.rows());
   cmap_device_.download(cmap.points, c);

   final_view_.showRGBImage<pcl::RGB>(cmap);
   final_view_.spinOnce(1, true);

   //image_view_.showRGBImage<pcl::PointXYZRGB>(cloud);
   //image_view_.spinOnce(1, true);

   savePNGFile("ii_" + boost::lexical_cast<string>(counter_) + ".png", *cloud);
   savePNGFile("c2_" + boost::lexical_cast<string>(counter_) + ".png", cmap);
   savePNGFile("s2_" + boost::lexical_cast<string>(counter_) + ".png", labels);

   savePNGFile("d_"  + boost::lexical_cast<string>(counter_) + ".png", people_detector_.depth_device_);
   savePNGFile("d2_" + boost::lexical_cast<string>(counter_) + ".png", people_detector_.depth_device2_);
 }

  template<typename T>
  void savePNGFile(const std::string& filename, const pcl::gpu::DeviceArray2D<T>& arr)
  {
    int c;
    pcl::PointCloud<T> cloud(arr.cols(), arr.rows());
    arr.download(cloud.points, c);
    pcl::io::savePNGFile(filename, cloud);
  }

  template <typename T> void
  savePNGFile (const std::string& filename, const pcl::PointCloud<T>& cloud)
  {
    pcl::io::savePNGFile(filename, cloud);
  }

  int counter_;
  PeopleDetector people_detector_;
  PeopleDetector::Image cmap_device_;

  ImageViewer final_view_;
  //ImageViewer image_view_;
};

void print_help()
{
  cout << "\nPeople tracking app options:" << endl;
  cout << "\t -numTrees \t<int> \tnumber of trees to load" << endl;
  cout << "\t -tree0 \t<path_to_tree_file>" << endl;
  cout << "\t -tree1 \t<path_to_tree_file>" << endl;
  cout << "\t -tree2 \t<path_to_tree_file>" << endl;
  cout << "\t -tree3 \t<path_to_tree_file>" << endl;
  cout << "\t -pcd   \t<path_to_pcd_file>" << endl;
}

int main(int argc, char** argv)
{
  if(find_switch (argc, argv, "--help") || find_switch (argc, argv, "-h"))
    return print_help(), 0;

  std::string treeFilenames[4] =
  {
    "d:/TreeData/results/forest1/tree_20.txt",
    "d:/TreeData/results/forest3/tree_20.txt",
    "d:/TreeData/results/forest3/tree_20.txt",
    "d:/TreeData/results/forest3/tree_20.txt"
  };
  int numTrees = 4;
  parse_argument (argc, argv, "-numTrees", numTrees);
  parse_argument (argc, argv, "-tree0", treeFilenames[0]);
  parse_argument (argc, argv, "-tree1", treeFilenames[1]);
  parse_argument (argc, argv, "-tree2", treeFilenames[2]);
  parse_argument (argc, argv, "-tree3", treeFilenames[3]);

  if (numTrees == 0 || numTrees > 4)
      return cout << "Invalid number of trees" << endl, -1;

  string pcdname = "d:/git/pcl/gpu/people/tools/test.pcd";
  parse_argument (argc, argv, "-pcd", pcdname);

  // loading cloud file
  pcl::PointCloud<pcl::PointXYZRGB>::Ptr cloud (new pcl::PointCloud<pcl::PointXYZRGB>);
  int res = pcl::io::loadPCDFile<pcl::PointXYZRGB> (pcdname, *cloud);
  if (res == -1) //* load the file
    return cout << "Couldn't read tree file" << endl, -1;

  cout << "Loaded " << cloud->width * cloud->height << " data points from " << pcdname << endl;

  // loading trees
  using pcl::gpu::people::RDFBodyPartsDetector;
  vector<string> names_vector(treeFilenames, treeFilenames + numTrees);
  RDFBodyPartsDetector::Ptr rdf(new RDFBodyPartsDetector(names_vector));

  // Create the app
  PeoplePCDApp app;
  app.people_detector_.rdf_detector_ = rdf;

  /// Run the app
  {
    pcl::ScopeTime frame_time("frame_time");
    app.cloud_cb(cloud);
  }

  app.visualizeAndWrite(cloud);
  app.final_view_.spin();

  return 0;
}
<|endoftext|>


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

#include "OVR_SDL2_obj.hpp"

//------------------------------------------------------------------------------

const char *vert_src = R"(
    #version 150

    uniform mat4 ProjectionMatrix;
    uniform mat4 ModelViewMatrix;
    uniform mat3 NormalMatrix;
    uniform vec4 LightPosition;

    in vec4 vPosition;
    in vec3 vNormal;
    in vec2 vTexCoord;

    out vec3 fView;
    out vec3 fLight;
    out vec3 fNormal;
    out vec2 fTexCoord;

    void main()
    {
        vec4 vLight = LightPosition - vPosition;

        fView     = vec3(ModelViewMatrix * vPosition);
        fLight    = vec3(ModelViewMatrix * vLight);
        fNormal   = vec3(NormalMatrix    * vNormal);
        fTexCoord = vTexCoord;

        gl_Position = ProjectionMatrix * ModelViewMatrix * vPosition;
    }
)";

const char *frag_src = R"(
    #version 150

    uniform vec4 AmbientLight;

    uniform vec4 DiffuseColor;
    uniform vec4 SpecularColor;

    uniform sampler2D DiffuseTexture;
    uniform sampler2D SpecularTexture;

    in vec3 fView;
    in vec3 fLight;
    in vec3 fNormal;
    in vec2 fTexCoord;

    out vec4 fOutput;

    void main()
    {
        // Sample the materials.

        vec3 cD = texture(DiffuseTexture,  fTexCoord).rgb + DiffuseColor.rgb;
        vec3 cS = texture(SpecularTexture, fTexCoord).rgb + SpecularColor.rgb;

        // Determine the per-fragment lighting vectors.

        vec3  N = normalize(fNormal);
        vec3  L = normalize(fLight);
        vec3  V = normalize(fView);
        float d = length(fView);
        vec3  R = reflect(L, N);

        // Compute the diffuse shading.

        float kd =     max(dot(L, N), 0.0);
        float ks = pow(max(dot(V, R), 0.0), 8.0);

        // Calculate the fragment color.

        float f = clamp(4.0 / d, 0.0, 1.0);

        fOutput = vec4((AmbientLight.rgb * cD + kd * cD + ks * cS) * f, 1.0);
    }
)";

//------------------------------------------------------------------------------

OVR_SDL2_obj::OVR_SDL2_obj(int argc, char **argv) : program(0)
{
    // Compile and link the shaders.

    if ((program = init_program(init_shader(GL_VERTEX_SHADER,   vert_src),
                                init_shader(GL_FRAGMENT_SHADER, frag_src))))
    {
        glUseProgram(program);

        // Query the program uniform locations.

        ProjectionMatrixLoc = glGetUniformLocation(program, "ProjectionMatrix");
        ModelViewMatrixLoc  = glGetUniformLocation(program, "ModelViewMatrix");
        NormalMatrixLoc     = glGetUniformLocation(program, "NormalMatrix");
        LightPositionLoc    = glGetUniformLocation(program, "LightPosition");
        AmbientLightLoc     = glGetUniformLocation(program, "AmbientLight");

        DiffuseColorLoc     = glGetUniformLocation(program, "DiffuseColor");
        SpecularColorLoc    = glGetUniformLocation(program, "SpecularColor");
        DiffuseTextureLoc   = glGetUniformLocation(program, "DiffuseTexture");
        SpecularTextureLoc  = glGetUniformLocation(program, "SpecularTexture");

        // Query the vertex attribute locations.

        vNormalLoc   = glGetAttribLocation(program, "vNormal");
        vTexCoordLoc = glGetAttribLocation(program, "vTexCoord");
        vPositionLoc = glGetAttribLocation(program, "vPosition");

        // Configure the scene.

        init_objects(argc, argv);
        init_background();

        glUniform4f(AmbientLightLoc,  0.2, 0.2, 0.2, 1.0);
        glUniform4f(LightPositionLoc, 0.0, 3.0, 3.0, 1.0);

        glUseProgram(0);
    }

    // Set the necessary OpenGL state.

    glEnable(GL_DEPTH_TEST);
}

OVR_SDL2_obj::~OVR_SDL2_obj()
{
    for (auto i : objects)
        obj_delete(i.first);
}

void OVR_SDL2_obj::draw()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(program);
    glUniformMatrix4fv(ProjectionMatrixLoc, 1, GL_TRUE, projection());

    // Render all objects.

    for (auto i : objects)
    {
        mat4 M = view() * translation(offset) * translation(i.second);

        glUniformMatrix4fv(ModelViewMatrixLoc, 1, GL_TRUE, M);
        glUniformMatrix3fv(NormalMatrixLoc,    1, GL_TRUE, normal(M));

        obj_render(i.first);
    }

    // Unbind our state.

    glBindVertexArray(0);
    glUseProgram(0);
}

//------------------------------------------------------------------------------

/// Load a series of OBJ files named on the command line. Configure them for
/// rendering with the current program. Arrange theo bjects along the X axis,
/// center the scene on the origin, and move the camera to a reasonable
/// starting position.

void OVR_SDL2_obj::init_objects(int argc, char **argv)
{
    float w = 0;
    float x = 0;
    float y = 0;
    float z = 0;

    // Loop over the command line argument array.

    for (int i = 1; i < argc; i++)
    {
        // Load the named OBJ.

        if (obj *o = obj_create(argv[i]))
        {
            // Configure the object's vertex attributes.

            obj_set_vert_loc(o, -1, vNormalLoc,
                                    vTexCoordLoc,
                                    vPositionLoc);

            obj_set_prop_loc(o, OBJ_KD, DiffuseColorLoc,  DiffuseTextureLoc,  -1);
            obj_set_prop_loc(o, OBJ_KS, SpecularColorLoc, SpecularTextureLoc, -1);

            // Position the object along the X axis.

            float b[6];

            obj_bound(o, b);

            objects[o] = vec3(x - b[0], -b[1], -0.5 * (b[5] + b[2]));

            w = x + (b[3] - b[0]);
            x = x + (b[3] - b[0]) * 1.25;

            y = std::max(y, b[4] - b[1]);
            z = std::max(z, b[5] - b[2]);
        }
    }

    // Position the scene and camera.

    offset   = vec3(-0.5 * w, 0.0, 0.0);
    position = vec3(0.0, y, z);
}

/// Generate a checkerboard background. For simplicity, the OBJ module.

void OVR_SDL2_obj::init_background()
{
    if (obj *o = obj_create(0))
    {
        float v[3] = { 0, 0, 0 };
        float n[3] = { 0, 1, 0 };

        int m = 48;

        // Generate a grid of vertices.

        for     (int i = 0; i <= m; i++)
            for (int j = 0; j <= m; j++)
            {
                int k = obj_add_vert(o);

                v[0] = j - 0.5 * m;
                v[2] = i - 0.5 * m;

                obj_set_vert_v(o, k, v);
                obj_set_vert_n(o, k, n);
            }

        // Generate a pair of materials, one for each tile color.

        int ma = obj_add_mtrl(o);
        int mb = obj_add_mtrl(o);

        float ca[4] = { 0.2f, 0.2f, 0.2f, 1.0f };
        float cb[4] = { 0.3f, 0.3f, 0.3f, 1.0f };

        obj_set_mtrl_c(o, ma, OBJ_KD, ca);
        obj_set_mtrl_c(o, mb, OBJ_KD, cb);

        // Generate a pair of surfaces, one for each material.

        int a = obj_add_surf(o);
        int b = obj_add_surf(o);

        obj_set_surf(o, a, ma);
        obj_set_surf(o, b, mb);

        // Generate a mesh of triangles connecting the vertices.

        for     (int i = 0; i < m; ++i)
            for (int j = 0; j < m; ++j)
            {
                int k[3], c = (i % 2 == j % 2) ? a : b;

                k[0] = (i    ) * (m + 1) + (j    );
                k[1] = (i    ) * (m + 1) + (j + 1);
                k[2] = (i + 1) * (m + 1) + (j + 1);

                obj_set_poly(o, c, obj_add_poly(o, c), k);

                k[0] = (i + 1) * (m + 1) + (j + 1);
                k[1] = (i + 1) * (m + 1) + (j    );
                k[2] = (i    ) * (m + 1) + (j    );

                obj_set_poly(o, c, obj_add_poly(o, c), k);
            }

        // Configure the object's vertex attributes.

        obj_set_vert_loc(o, -1, vNormalLoc,
                                vTexCoordLoc,
                                vPositionLoc);

        obj_set_prop_loc(o, OBJ_KD, DiffuseColorLoc,  DiffuseTextureLoc,  -1);
        obj_set_prop_loc(o, OBJ_KS, SpecularColorLoc, SpecularTextureLoc, -1);

        objects[o] = vec3(0.0, 0.0, 0.0);
    }
}

//------------------------------------------------------------------------------

int main(int argc, char **argv)
{
    OVR_SDL2_obj app(argc, argv);
    app.run();
    return 0;
}
<commit_msg>Tune fog<commit_after>// Copyright (c) 2014 Robert Kooima
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the "Software"),
// to deal in the Software without restriction, including without limitation
// the rights to use, copy, modify, merge, publish, distribute, sublicense,
// and/or sell copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

#include "OVR_SDL2_obj.hpp"

//------------------------------------------------------------------------------

const char *vert_src = R"(
    #version 150

    uniform mat4 ProjectionMatrix;
    uniform mat4 ModelViewMatrix;
    uniform mat3 NormalMatrix;
    uniform vec4 LightPosition;

    in vec4 vPosition;
    in vec3 vNormal;
    in vec2 vTexCoord;

    out vec3 fView;
    out vec3 fLight;
    out vec3 fNormal;
    out vec2 fTexCoord;

    void main()
    {
        vec4 vLight = LightPosition - vPosition;

        fView     = vec3(ModelViewMatrix * vPosition);
        fLight    = vec3(ModelViewMatrix * vLight);
        fNormal   = vec3(NormalMatrix    * vNormal);
        fTexCoord = vTexCoord;

        gl_Position = ProjectionMatrix * ModelViewMatrix * vPosition;
    }
)";

const char *frag_src = R"(
    #version 150

    uniform vec4 AmbientLight;

    uniform vec4 DiffuseColor;
    uniform vec4 SpecularColor;

    uniform sampler2D DiffuseTexture;
    uniform sampler2D SpecularTexture;

    in vec3 fView;
    in vec3 fLight;
    in vec3 fNormal;
    in vec2 fTexCoord;

    out vec4 fOutput;

    void main()
    {
        // Sample the materials.

        vec3 cD = texture(DiffuseTexture,  fTexCoord).rgb + DiffuseColor.rgb;
        vec3 cS = texture(SpecularTexture, fTexCoord).rgb + SpecularColor.rgb;

        // Determine the per-fragment lighting vectors.

        vec3  N = normalize(fNormal);
        vec3  L = normalize(fLight);
        vec3  V = normalize(fView);
        float d = length(fView);
        vec3  R = reflect(L, N);

        // Compute the diffuse shading.

        float kd =     max(dot(L, N), 0.0);
        float ks = pow(max(dot(V, R), 0.0), 8.0);

        // Calculate the fragment color.

        vec3 f = AmbientLight.rgb * cD + kd * cD + ks * cS;

        float fog = clamp(2.0 - 0.1 * d, 0.0, 1.0);

        fOutput = vec4(mix(AmbientLight.rgb, f, fog), 1.0);
    }
)";

//------------------------------------------------------------------------------

OVR_SDL2_obj::OVR_SDL2_obj(int argc, char **argv) : program(0)
{
    // Compile and link the shaders.

    if ((program = init_program(init_shader(GL_VERTEX_SHADER,   vert_src),
                                init_shader(GL_FRAGMENT_SHADER, frag_src))))
    {
        glUseProgram(program);

        // Query the program uniform locations.

        ProjectionMatrixLoc = glGetUniformLocation(program, "ProjectionMatrix");
        ModelViewMatrixLoc  = glGetUniformLocation(program, "ModelViewMatrix");
        NormalMatrixLoc     = glGetUniformLocation(program, "NormalMatrix");
        LightPositionLoc    = glGetUniformLocation(program, "LightPosition");
        AmbientLightLoc     = glGetUniformLocation(program, "AmbientLight");

        DiffuseColorLoc     = glGetUniformLocation(program, "DiffuseColor");
        SpecularColorLoc    = glGetUniformLocation(program, "SpecularColor");
        DiffuseTextureLoc   = glGetUniformLocation(program, "DiffuseTexture");
        SpecularTextureLoc  = glGetUniformLocation(program, "SpecularTexture");

        // Query the vertex attribute locations.

        vNormalLoc   = glGetAttribLocation(program, "vNormal");
        vTexCoordLoc = glGetAttribLocation(program, "vTexCoord");
        vPositionLoc = glGetAttribLocation(program, "vPosition");

        // Configure the scene.

        init_objects(argc, argv);
        init_background();

        glUniform4f(AmbientLightLoc,  0.1f, 0.1f, 0.1f, 1.0f);
        glUniform4f(LightPositionLoc, 0.0f, 3.0f, 3.0f, 1.0f);

        glUseProgram(0);
    }

    // Set the necessary OpenGL state.

    glEnable(GL_DEPTH_TEST);
    glClearColor(0.1f, 0.1f, 0.1f, 0.0f);
}

OVR_SDL2_obj::~OVR_SDL2_obj()
{
    for (auto i : objects)
        obj_delete(i.first);
}

void OVR_SDL2_obj::draw()
{
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    glUseProgram(program);
    glUniformMatrix4fv(ProjectionMatrixLoc, 1, GL_TRUE, projection());

    // Render all objects.

    for (auto i : objects)
    {
        mat4 M = view() * translation(offset) * translation(i.second);

        glUniformMatrix4fv(ModelViewMatrixLoc, 1, GL_TRUE, M);
        glUniformMatrix3fv(NormalMatrixLoc,    1, GL_TRUE, normal(M));

        obj_render(i.first);
    }

    // Unbind our state.

    glBindVertexArray(0);
    glUseProgram(0);
}

//------------------------------------------------------------------------------

/// Load a series of OBJ files named on the command line. Configure them for
/// rendering with the current program. Arrange theo bjects along the X axis,
/// center the scene on the origin, and move the camera to a reasonable
/// starting position.

void OVR_SDL2_obj::init_objects(int argc, char **argv)
{
    float w = 0;
    float x = 0;
    float y = 0;
    float z = 0;

    // Loop over the command line argument array.

    for (int i = 1; i < argc; i++)
    {
        // Load the named OBJ.

        if (obj *o = obj_create(argv[i]))
        {
            // Configure the object's vertex attributes.

            obj_set_vert_loc(o, -1, vNormalLoc,
                                    vTexCoordLoc,
                                    vPositionLoc);

            obj_set_prop_loc(o, OBJ_KD, DiffuseColorLoc,  DiffuseTextureLoc,  -1);
            obj_set_prop_loc(o, OBJ_KS, SpecularColorLoc, SpecularTextureLoc, -1);

            // Position the object along the X axis.

            float b[6];

            obj_bound(o, b);

            objects[o] = vec3(x - b[0], -b[1], -0.5 * (b[5] + b[2]));

            w = x + (b[3] - b[0]);
            x = x + (b[3] - b[0]) * 1.25;

            y = std::max(y, b[4] - b[1]);
            z = std::max(z, b[5] - b[2]);
        }
    }

    // Position the scene and camera.

    offset   = vec3(-0.5 * w, 0.0, 0.0);
    position = vec3(0.0, y, z);
}

/// Generate a checkerboard background. For simplicity, the OBJ module.

void OVR_SDL2_obj::init_background()
{
    if (obj *o = obj_create(0))
    {
        float v[3] = { 0, 0, 0 };
        float n[3] = { 0, 1, 0 };

        int m = 48;

        // Generate a grid of vertices.

        for     (int i = 0; i <= m; i++)
            for (int j = 0; j <= m; j++)
            {
                int k = obj_add_vert(o);

                v[0] = j - 0.5 * m;
                v[2] = i - 0.5 * m;

                obj_set_vert_v(o, k, v);
                obj_set_vert_n(o, k, n);
            }

        // Generate a pair of materials, one for each tile color.

        int ma = obj_add_mtrl(o);
        int mb = obj_add_mtrl(o);

        float ca[4] = { 0.2f, 0.2f, 0.2f, 1.0f };
        float cb[4] = { 0.3f, 0.3f, 0.3f, 1.0f };

        obj_set_mtrl_c(o, ma, OBJ_KD, ca);
        obj_set_mtrl_c(o, mb, OBJ_KD, cb);

        // Generate a pair of surfaces, one for each material.

        int a = obj_add_surf(o);
        int b = obj_add_surf(o);

        obj_set_surf(o, a, ma);
        obj_set_surf(o, b, mb);

        // Generate a mesh of triangles connecting the vertices.

        for     (int i = 0; i < m; ++i)
            for (int j = 0; j < m; ++j)
            {
                int k[3], c = (i % 2 == j % 2) ? a : b;

                k[0] = (i    ) * (m + 1) + (j    );
                k[1] = (i    ) * (m + 1) + (j + 1);
                k[2] = (i + 1) * (m + 1) + (j + 1);

                obj_set_poly(o, c, obj_add_poly(o, c), k);

                k[0] = (i + 1) * (m + 1) + (j + 1);
                k[1] = (i + 1) * (m + 1) + (j    );
                k[2] = (i    ) * (m + 1) + (j    );

                obj_set_poly(o, c, obj_add_poly(o, c), k);
            }

        // Configure the object's vertex attributes.

        obj_set_vert_loc(o, -1, vNormalLoc,
                                vTexCoordLoc,
                                vPositionLoc);

        obj_set_prop_loc(o, OBJ_KD, DiffuseColorLoc,  DiffuseTextureLoc,  -1);
        obj_set_prop_loc(o, OBJ_KS, SpecularColorLoc, SpecularTextureLoc, -1);

        objects[o] = vec3(0.0, 0.0, 0.0);
    }
}

//------------------------------------------------------------------------------

int main(int argc, char **argv)
{
    OVR_SDL2_obj app(argc, argv);
    app.run();
    return 0;
}
<|endoftext|>