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

#include <QsLog.h>

#include "trikScriptRunner.h"
#include "trikJavaScriptRunner.h"
#include "trikPythonRunner.h"

using namespace trikScriptRunner;

/// Constructor.
/// @param brick - reference to trikControl::Brick instance.
/// @param mailbox - mailbox object used to communicate with other robots.
TrikScriptRunner::TrikScriptRunner(trikControl::BrickInterface &brick
								   , trikNetwork::MailboxInterface * const mailbox
								   )
	: brick(brick), mailbox(mailbox), mLastRunner(JAVASCRIPT)
{}

TrikScriptRunner::~TrikScriptRunner()
{
	for (size_t i = 0; i < ScriptTypeLength; i++) { // stop and delete all working interpretators
		if (mScriptRunnerArray[i] != nullptr) {
			mScriptRunnerArray[i]->abort();
			delete mScriptRunnerArray[i];
		}
	}
}

void TrikScriptRunner::registerUserFunction(const QString &name, QScriptEngine::FunctionSignature function) {}
void TrikScriptRunner::addCustomEngineInitStep(const std::function<void (QScriptEngine *)> &step) {}

void TrikScriptRunner::run(const QString &script, const QString &fileName)
{
	if (fileName.endsWith(".py")) {
		run(script, PYTHON, fileName);
	} else { // default JS
		run(script, JAVASCRIPT, fileName);
	}
}

void TrikScriptRunner::run(const QString &script, const ScriptType &stype, const QString &fileName)
{
	for (size_t i = 0; i < ScriptTypeLength; i++) { // stop all working interpretators
		if (mScriptRunnerArray[i] != nullptr) {
			mScriptRunnerArray[i]->abort();
		}
	}
	if (mScriptRunnerArray[stype] == nullptr) { // lazy creation
		switch (stype) {
			case JAVASCRIPT:
				mScriptRunnerArray[stype] = new TrikJavaScriptRunner(brick, mailbox);
				break;
			case PYTHON:
				mScriptRunnerArray[stype] = new TrikPythonRunner(brick, mailbox);
				break;
			default:
				QLOG_ERROR() << "Can't handle script with unrecognized type: " << stype;
				return;
		}
		// subscribe on wrapped objects signals
		connect(mScriptRunnerArray[stype], SIGNAL(completed(QString, int)),
				this, SIGNAL(completed(QString, int)));
		connect(mScriptRunnerArray[stype], SIGNAL(startedScript(const QString &, int)),
				this, SIGNAL(startedScript(const QString &, int)));
		connect(mScriptRunnerArray[stype], SIGNAL(startedDirectScript(int)),
				this, SIGNAL(startedDirectScript(int)));
		connect(mScriptRunnerArray[stype], SIGNAL(sendMessage(const QString &)),
				this, SIGNAL(sendMessage(const QString &)));
	}

	mScriptRunnerArray[stype]->run(script, fileName);
}

void TrikScriptRunner::runDirectCommand(const QString &command)
{
	mScriptRunnerArray[mLastRunner]->runDirectCommand(command);
}

void TrikScriptRunner::abort()
{
	mScriptRunnerArray[mLastRunner]->abort();
}

void TrikScriptRunner::brickBeep()
{
	mScriptRunnerArray[mLastRunner]->brickBeep();
}
<commit_msg>lastRunner change fix<commit_after>/* Copyright 2014 - 2015 CyberTech Labs Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License. */

#include <QsLog.h>

#include "trikScriptRunner.h"
#include "trikJavaScriptRunner.h"
#include "trikPythonRunner.h"

using namespace trikScriptRunner;

/// Constructor.
/// @param brick - reference to trikControl::Brick instance.
/// @param mailbox - mailbox object used to communicate with other robots.
TrikScriptRunner::TrikScriptRunner(trikControl::BrickInterface &brick
								   , trikNetwork::MailboxInterface * const mailbox
								   )
	: brick(brick), mailbox(mailbox), mLastRunner(JAVASCRIPT)
{}

TrikScriptRunner::~TrikScriptRunner()
{
	for (size_t i = 0; i < ScriptTypeLength; i++) { // stop and delete all working interpretators
		if (mScriptRunnerArray[i] != nullptr) {
			mScriptRunnerArray[i]->abort();
			delete mScriptRunnerArray[i];
		}
	}
}

void TrikScriptRunner::registerUserFunction(const QString &name, QScriptEngine::FunctionSignature function) {}
void TrikScriptRunner::addCustomEngineInitStep(const std::function<void (QScriptEngine *)> &step) {}

void TrikScriptRunner::run(const QString &script, const QString &fileName)
{
	if (fileName.endsWith(".py")) {
		run(script, PYTHON, fileName);
	} else { // default JS
		run(script, JAVASCRIPT, fileName);
	}
}

void TrikScriptRunner::run(const QString &script, const ScriptType &stype, const QString &fileName)
{
	for (size_t i = 0; i < ScriptTypeLength; i++) { // stop all working interpretators
		if (mScriptRunnerArray[i] != nullptr) {
			mScriptRunnerArray[i]->abort();
		}
	}
	if (mScriptRunnerArray[stype] == nullptr) { // lazy creation
		switch (stype) {
			case JAVASCRIPT:
				mScriptRunnerArray[stype] = new TrikJavaScriptRunner(brick, mailbox);
				break;
			case PYTHON:
				mScriptRunnerArray[stype] = new TrikPythonRunner(brick, mailbox);
				break;
			default:
				QLOG_ERROR() << "Can't handle script with unrecognized type: " << stype;
				return;
		}
		// subscribe on wrapped objects signals
		connect(mScriptRunnerArray[stype], SIGNAL(completed(QString, int)),
				this, SIGNAL(completed(QString, int)));
		connect(mScriptRunnerArray[stype], SIGNAL(startedScript(const QString &, int)),
				this, SIGNAL(startedScript(const QString &, int)));
		connect(mScriptRunnerArray[stype], SIGNAL(startedDirectScript(int)),
				this, SIGNAL(startedDirectScript(int)));
		connect(mScriptRunnerArray[stype], SIGNAL(sendMessage(const QString &)),
				this, SIGNAL(sendMessage(const QString &)));
	}

	mScriptRunnerArray[stype]->run(script, fileName);
	mLastRunner = stype;
}

void TrikScriptRunner::runDirectCommand(const QString &command)
{
	mScriptRunnerArray[mLastRunner]->runDirectCommand(command);
}

void TrikScriptRunner::abort()
{
	mScriptRunnerArray[mLastRunner]->abort();
}

void TrikScriptRunner::brickBeep()
{
	mScriptRunnerArray[mLastRunner]->brickBeep();
}
<|endoftext|>


<commit_before>/*
   All permutation (string).

   Constructs all permutations of a given input string via backtracking.
   Note that repetitions occur if there are letters in the input string
   that appear more than once.

   (c) 2015 Josef Ziegler (ippeb24@gmail.com)

*/

#include <iostream>
#include <cstring>
using namespace std;

void permute(string& S, int at) {
  if (at == S.length())
    cout << S << endl;

  for (int i = at; i < S.length(); i++) {
    char tmp = S[at];
    S[at]=S[i];
    S[i]=tmp;
    permute(S, at + 1);
    S[i]=S[at]; // two lines only needed if we pass
    S[at]=tmp;  // S as a reference
  }
}

int main() {
  string tmp;
  cin >> tmp;
  permute(tmp, 0);
}
<commit_msg>combinatorics: All permutation file renaming.<commit_after><|endoftext|>


<commit_before>// $Id: equation_systems.C,v 1.17 2003-02-17 01:23:01 benkirk Exp $

// The Next Great Finite Element Library.
// Copyright (C) 2002  Benjamin S. Kirk, John W. Peterson

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

// 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

// System includes
#include <sstream>

// Local Includes
//#include "enum_solver_package.h"
#include "libmesh.h"
#include "fe_interface.h"
//#include "petsc_vector.h"
//#include "petsc_matrix.h"
//#include "petsc_interface.h"
#include "linear_solver_interface.h"
#include "equation_systems.h"
#include "general_system.h"

// Forward Declarations

// ------------------------------------------------------------
// EquationSystem class implementation
EquationSystems::EquationSystems (Mesh& m,
				  const SolverPackage sp) :
  _mesh(m),
  _solver_package(sp)
{
  // Default parameters
  set_parameter("linear solver tolerance")          = 1.e-12;
  set_parameter("linear solver maximum iterations") = 5000;
}

EquationSystems::~EquationSystems ()
{
  clear();

  assert (!libMesh::closed());
}

void EquationSystems::clear ()
{
  for (std::map<std::string, GeneralSystem*>::iterator
	 pos = _systems.begin(); pos != _systems.end();
       ++pos)
    delete pos->second;

  _systems.clear ();

  _flags.clear ();

  _parameters.clear ();
}

void EquationSystems::init ()
{
  const unsigned int n_sys = n_systems();

  assert (n_sys != 0);

//   /**
//    * Tell all the \p DofObject entities how many systems
//    * there are.
//    */
//   {
//     // All the nodes
//     node_iterator       node_it  (_mesh.nodes_begin());
//     const node_iterator node_end (_mesh.nodes_end());

//     for ( ; node_it != node_end; ++node_it)
//       (*node_it)->set_n_systems(n_sys);

//     // All the elements
//     elem_iterator       elem_it (_mesh.elements_begin());
//     const elem_iterator elem_end(_mesh.elements_end());

//     for ( ; elem_it != elem_end; ++elem_it)
//       (*elem_it)->set_n_systems(n_sys);
//   }

  for (std::map<std::string, GeneralSystem*>::iterator
	 sys = _systems.begin(); sys != _systems.end();
       ++sys)
    {
      /**
       * Initialize the system.
       */
      sys->second->init();
    }
}

void EquationSystems::add_system (const std::string& name)
{
  if (!_systems.count(name))
    {
      const unsigned int num = n_systems();

      _systems.insert (std::pair<std::string,
		                 GeneralSystem*>(name,
						 new GeneralSystem(*this,
								   name,
								   num,
								   _solver_package)
						 )
		       );
    }
  else
    {
      std::cerr << "ERROR: There was already a system"
		<< " named " << name
		<< std::endl;

      error();
    }

  /**
   * Tell all the \p DofObject entities to add a system.
   */
  {
    // All the nodes
    node_iterator       node_it  (_mesh.nodes_begin());
    const node_iterator node_end (_mesh.nodes_end());

    for ( ; node_it != node_end; ++node_it)
      (*node_it)->add_system();

    // All the elements
    elem_iterator       elem_it (_mesh.elements_begin());
    const elem_iterator elem_end(_mesh.elements_end());

    for ( ; elem_it != elem_end; ++elem_it)
      (*elem_it)->add_system();
  }
}

void EquationSystems::delete_system (const std::string& name)
{
  if (!_systems.count(name))
    {
      std::cerr << "ERROR: no system named "
		<< name  << std::endl;

      error();
    }

  delete _systems[name];

  _systems.erase (name);
}

unsigned int EquationSystems::n_vars () const
{
  if (_systems.empty())
    return 0;

  unsigned int tot=0;

  for (std::map<std::string, GeneralSystem*>::const_iterator
	 pos = _systems.begin(); pos != _systems.end(); ++pos)
    tot += pos->second->n_vars();

  return tot;
}

unsigned int EquationSystems::n_dofs () const
{
  if (_systems.empty())
    return 0;

  unsigned int tot=0;

  for (std::map<std::string, GeneralSystem*>::const_iterator
	 pos = _systems.begin(); pos != _systems.end(); ++pos)
    tot += pos->second->n_dofs();

  return tot;
}

GeneralSystem & EquationSystems::operator () (const std::string& name)
{
  std::map<std::string, GeneralSystem*>::iterator
    pos = _systems.find(name);

  if (pos == _systems.end())
    {
      std::cerr << "ERROR: system "
		<< name
		<< " not found!"
		<< std::endl;

      error();
    }

  return *pos->second;
}

const GeneralSystem & EquationSystems::operator () (const std::string& name) const
{
  std::map<std::string, GeneralSystem*>::const_iterator
    pos = _systems.find(name);

  if (pos == _systems.end())
    {
      std::cerr << "ERROR: system "
		<< name
		<< " not found!"
		<< std::endl;

      error();
    }

  return *pos->second;
}

const std::string & EquationSystems::name (const unsigned int num) const
{
  assert (num < n_systems());

  std::map<std::string, GeneralSystem*>::const_iterator
    pos = _systems.begin();

  // New code
#if (__GNUC__ == 2)
  std::advance (pos, static_cast<int>(num));
#else
  std::advance (pos, num);
#endif

  // Old code
//  for (unsigned int i=0; i<num; i++)
//    ++pos;

  return pos->first;
}

GeneralSystem & EquationSystems::operator () (const unsigned int num)
{
  assert (num < n_systems());

  std::map<std::string, GeneralSystem*>::iterator
    pos = _systems.begin();

  // New code
#if (__GNUC__ == 2)
  std::advance (pos, static_cast<int>(num));
#else
  std::advance (pos, num);
#endif

  // Old code
//  for (unsigned int i=0; i<num; i++)
//    ++pos;

  return *pos->second;
}

const GeneralSystem & EquationSystems::operator ()  (const unsigned int num) const
{
  assert (num < n_systems());

  std::map<std::string, GeneralSystem*>::const_iterator
    pos = _systems.begin();

    // New code
#if (__GNUC__ == 2)
  std::advance (pos, static_cast<int>(num));
#else
  std::advance (pos, num);
#endif

  // Old code
  //  for (unsigned int i=0; i<num; i++)
//    ++pos;

  return *pos->second;
}

bool EquationSystems::flag (const std::string& fl) const
{
  return (_flags.count(fl) != 0);
}

void EquationSystems::set_flag (const std::string& fl)
{
#ifdef DEBUG
  /*
  // Make sure the parameter isn't already set
  if (flags.count(fl))
    std::cerr << "WARNING: flag "
      	      << "\""
	      << fl
      	      << "\""
	      << " is already set!"
	      << std::endl;
  */
#endif

  _flags.insert (fl);
}

void EquationSystems::unset_flag (const std::string& fl)
{
  // Look for the flag in the database
  if (!_flags.count(fl))
    {
      std::cerr << "ERROR: flag " << fl
		<< " was not set!"
		<< std::endl;
      error();
    }

  // Remove the flag
  _flags.erase (fl);
}

Real EquationSystems::parameter (const std::string& id) const
{
  // Look for the id in the database
  std::map<std::string, Real>::const_iterator
    pos = _parameters.find(id);

  if (pos == _parameters.end())
    {
      std::cerr << "ERROR: parameter " << id
		<< " was not set!"
		<< std::endl;
      error();
    }

  // Return the parameter value if found
  return pos->second;
}

Real & EquationSystems::set_parameter (const std::string& id)
{
#ifdef DEBUG
  /*
  // Make sure the parameter isn't already set
  if (parameters.count(id))
    std::cerr << "WARNING: parameter "
	      << "\""
	      << id
	      << "\""
	      << " is already set!"
	      << std::endl;
  */
#endif

  // Insert the parameter/value pair into the database
  return _parameters[id];
}

void EquationSystems::unset_parameter (const std::string& id)
{
  // Look for the id in the database
  std::map<std::string, Real>::iterator
    pos = _parameters.find(id);

  // Make sure the parameter was found
  if (pos == _parameters.end())
    {
      std::cerr << "ERROR: parameter " << id
		<< " was not set!"
		<< std::endl;
      error();
    }

  // Erase the entry
  _parameters.erase(pos);
}

void EquationSystems::build_variable_names (std::vector<std::string>& var_names)
{
  assert (n_systems());

  var_names.resize (n_vars());

  unsigned int var_num=0;

  for (unsigned int sys=0; sys<n_systems(); sys++)
    for (unsigned int vn=0; vn < (*this)(sys).n_vars(); vn++)
      var_names[var_num++] = (*this)(sys).variable_name(vn);
}

void EquationSystems::build_solution_vector (std::vector<Complex>& soln)
{
  assert (n_systems());

  const unsigned int dim = _mesh.mesh_dimension();
  const unsigned int nn  = _mesh.n_nodes();
  const unsigned int nv  = n_vars();

  if (_mesh.processor_id() == 0)
    soln.resize(nn*nv);

  std::vector<Complex> sys_soln;

  unsigned int var_num=0;

  for (unsigned int sys=0; sys<n_systems(); sys++)
    {
      const GeneralSystem& system  = (*this)(sys);
      const unsigned int nv_sys    = system.n_vars();

      system.update_global_solution (sys_soln);

      if (_mesh.processor_id() == 0)
	{
	  std::vector<Complex>      elem_soln;   // The finite element solution
	  std::vector<Complex>      nodal_soln;  // The finite elemnt solution interpolated to the nodes
	  std::vector<unsigned int> dof_indices; // The DOF indices for the finite element

	  for (unsigned int var=0; var<nv_sys; var++)
	    {
	      const FEType& fe_type    = system.variable_type(var);

	      for (unsigned int e=0; e<_mesh.n_elem(); e++)
		if (_mesh.elem(e)->active())
		  {
		    const Elem* elem = _mesh.elem(e);
		    system.get_dof_map().dof_indices (elem, dof_indices, var);

		    elem_soln.resize(dof_indices.size());

		    for (unsigned int i=0; i<dof_indices.size(); i++)
		      elem_soln[i] = sys_soln[dof_indices[i]];

		    FEInterface::nodal_soln (dim, fe_type, elem,
					     elem_soln, nodal_soln);

		    assert (nodal_soln.size() == elem->n_nodes());

		    for (unsigned int n=0; n<elem->n_nodes(); n++)
		      soln[nv*(elem->node(n)) + (var + var_num)] =
			nodal_soln[n];
		  }
	    }
	}

      var_num += nv_sys;
    }
}

std::string EquationSystems::get_info () const
{
  std::ostringstream out;

  out << " EquationSystems:" << std::endl
      << "  n_systems()=" << n_systems() << std::endl;

  for (std::map<std::string, GeneralSystem*>::const_iterator it=_systems.begin();
       it != _systems.end(); ++it)
    {
      const std::string& sys_name    = it->first;
      const GeneralSystem&  system   = *it->second;

      out << "   System \"" << sys_name << "\"" << std::endl
	  << "    Variables=";
      for (unsigned int vn=0; vn<system.n_vars(); vn++)
	out << "\"" << system.variable_name(vn) << "\" ";

      out << std::endl;

#ifndef ENABLE_INFINITE_ELEMENTS
      out << "    Finite Element Types=";
      for (unsigned int vn=0; vn<system.n_vars(); vn++)
      {
	out << "\"" << system.get_dof_map().component_type(vn).family << "\" ";
      }
#else
      out << "    Finite Element Types=";
      for (unsigned int vn=0; vn<system.n_vars(); vn++)
      {
	out << "\"" << system.get_dof_map().variable_type(vn).family << "\", ";
	out << "\"" << system.get_dof_map().variable_type(vn).radial_family << "\" ";
      }

      out << std::endl << "    Infinite Element Mapping=";
      for (unsigned int vn=0; vn<system.n_vars(); vn++)
      {
	out << "\"" << system.get_dof_map().variable_type(vn).inf_map << "\" ";
      }
#endif

      out << std::endl;

      out << "    Approximation Orders=";
      for (unsigned int vn=0; vn<system.n_vars(); vn++)
      {
#ifndef ENABLE_INFINITE_ELEMENTS
	out << "\"" << system.get_dof_map().variable_type(vn).order << "\" ";
#else
	out << "\"" << system.get_dof_map().variable_type(vn).order << "\", ";
	out << "\"" << system.get_dof_map().variable_type(vn).radial_order << "\" ";
#endif
      }

      out << std::endl;

      out << "    n_dofs()="             << system.n_dofs()             << std::endl;
      out << "    n_local_dofs()="       << system.n_local_dofs()       << std::endl;
#ifdef ENABLE_AMR
      out << "    n_constrained_dofs()=" << system.n_constrained_dofs() << std::endl;
#endif
    }

  if (!_flags.empty())
    {
      out << "  Flags:" << std::endl;

      for (std::set<std::string>::const_iterator flag = _flags.begin();
	   flag != _flags.end(); ++flag)
	out << "   "
	    << "\""
	    << *flag
	    << "\""
	    << std::endl;
    }

  if (!_parameters.empty())
    {
      out << "  Parameters:" << std::endl;

      for (std::map<std::string, Real>::const_iterator
	     param = _parameters.begin(); param != _parameters.end();
	   ++param)
	out << "   "
	    << "\""
	    << param->first
	    << "\""
	    << "="
	    << param->second
	    << std::endl;
    }

  return out.str();
}
<commit_msg>one final DofMap::component changed to variable<commit_after>// $Id: equation_systems.C,v 1.18 2003-02-17 05:33:09 jwpeterson Exp $

// The Next Great Finite Element Library.
// Copyright (C) 2002  Benjamin S. Kirk, John W. Peterson

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

// 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

// System includes
#include <sstream>

// Local Includes
//#include "enum_solver_package.h"
#include "libmesh.h"
#include "fe_interface.h"
//#include "petsc_vector.h"
//#include "petsc_matrix.h"
//#include "petsc_interface.h"
#include "linear_solver_interface.h"
#include "equation_systems.h"
#include "general_system.h"

// Forward Declarations

// ------------------------------------------------------------
// EquationSystem class implementation
EquationSystems::EquationSystems (Mesh& m,
				  const SolverPackage sp) :
  _mesh(m),
  _solver_package(sp)
{
  // Default parameters
  set_parameter("linear solver tolerance")          = 1.e-12;
  set_parameter("linear solver maximum iterations") = 5000;
}

EquationSystems::~EquationSystems ()
{
  clear();

  assert (!libMesh::closed());
}

void EquationSystems::clear ()
{
  for (std::map<std::string, GeneralSystem*>::iterator
	 pos = _systems.begin(); pos != _systems.end();
       ++pos)
    delete pos->second;

  _systems.clear ();

  _flags.clear ();

  _parameters.clear ();
}

void EquationSystems::init ()
{
  const unsigned int n_sys = n_systems();

  assert (n_sys != 0);

//   /**
//    * Tell all the \p DofObject entities how many systems
//    * there are.
//    */
//   {
//     // All the nodes
//     node_iterator       node_it  (_mesh.nodes_begin());
//     const node_iterator node_end (_mesh.nodes_end());

//     for ( ; node_it != node_end; ++node_it)
//       (*node_it)->set_n_systems(n_sys);

//     // All the elements
//     elem_iterator       elem_it (_mesh.elements_begin());
//     const elem_iterator elem_end(_mesh.elements_end());

//     for ( ; elem_it != elem_end; ++elem_it)
//       (*elem_it)->set_n_systems(n_sys);
//   }

  for (std::map<std::string, GeneralSystem*>::iterator
	 sys = _systems.begin(); sys != _systems.end();
       ++sys)
    {
      /**
       * Initialize the system.
       */
      sys->second->init();
    }
}

void EquationSystems::add_system (const std::string& name)
{
  if (!_systems.count(name))
    {
      const unsigned int num = n_systems();

      _systems.insert (std::pair<std::string,
		                 GeneralSystem*>(name,
						 new GeneralSystem(*this,
								   name,
								   num,
								   _solver_package)
						 )
		       );
    }
  else
    {
      std::cerr << "ERROR: There was already a system"
		<< " named " << name
		<< std::endl;

      error();
    }

  /**
   * Tell all the \p DofObject entities to add a system.
   */
  {
    // All the nodes
    node_iterator       node_it  (_mesh.nodes_begin());
    const node_iterator node_end (_mesh.nodes_end());

    for ( ; node_it != node_end; ++node_it)
      (*node_it)->add_system();

    // All the elements
    elem_iterator       elem_it (_mesh.elements_begin());
    const elem_iterator elem_end(_mesh.elements_end());

    for ( ; elem_it != elem_end; ++elem_it)
      (*elem_it)->add_system();
  }
}

void EquationSystems::delete_system (const std::string& name)
{
  if (!_systems.count(name))
    {
      std::cerr << "ERROR: no system named "
		<< name  << std::endl;

      error();
    }

  delete _systems[name];

  _systems.erase (name);
}

unsigned int EquationSystems::n_vars () const
{
  if (_systems.empty())
    return 0;

  unsigned int tot=0;

  for (std::map<std::string, GeneralSystem*>::const_iterator
	 pos = _systems.begin(); pos != _systems.end(); ++pos)
    tot += pos->second->n_vars();

  return tot;
}

unsigned int EquationSystems::n_dofs () const
{
  if (_systems.empty())
    return 0;

  unsigned int tot=0;

  for (std::map<std::string, GeneralSystem*>::const_iterator
	 pos = _systems.begin(); pos != _systems.end(); ++pos)
    tot += pos->second->n_dofs();

  return tot;
}

GeneralSystem & EquationSystems::operator () (const std::string& name)
{
  std::map<std::string, GeneralSystem*>::iterator
    pos = _systems.find(name);

  if (pos == _systems.end())
    {
      std::cerr << "ERROR: system "
		<< name
		<< " not found!"
		<< std::endl;

      error();
    }

  return *pos->second;
}

const GeneralSystem & EquationSystems::operator () (const std::string& name) const
{
  std::map<std::string, GeneralSystem*>::const_iterator
    pos = _systems.find(name);

  if (pos == _systems.end())
    {
      std::cerr << "ERROR: system "
		<< name
		<< " not found!"
		<< std::endl;

      error();
    }

  return *pos->second;
}

const std::string & EquationSystems::name (const unsigned int num) const
{
  assert (num < n_systems());

  std::map<std::string, GeneralSystem*>::const_iterator
    pos = _systems.begin();

  // New code
#if (__GNUC__ == 2)
  std::advance (pos, static_cast<int>(num));
#else
  std::advance (pos, num);
#endif

  // Old code
//  for (unsigned int i=0; i<num; i++)
//    ++pos;

  return pos->first;
}

GeneralSystem & EquationSystems::operator () (const unsigned int num)
{
  assert (num < n_systems());

  std::map<std::string, GeneralSystem*>::iterator
    pos = _systems.begin();

  // New code
#if (__GNUC__ == 2)
  std::advance (pos, static_cast<int>(num));
#else
  std::advance (pos, num);
#endif

  // Old code
//  for (unsigned int i=0; i<num; i++)
//    ++pos;

  return *pos->second;
}

const GeneralSystem & EquationSystems::operator ()  (const unsigned int num) const
{
  assert (num < n_systems());

  std::map<std::string, GeneralSystem*>::const_iterator
    pos = _systems.begin();

    // New code
#if (__GNUC__ == 2)
  std::advance (pos, static_cast<int>(num));
#else
  std::advance (pos, num);
#endif

  // Old code
  //  for (unsigned int i=0; i<num; i++)
//    ++pos;

  return *pos->second;
}

bool EquationSystems::flag (const std::string& fl) const
{
  return (_flags.count(fl) != 0);
}

void EquationSystems::set_flag (const std::string& fl)
{
#ifdef DEBUG
  /*
  // Make sure the parameter isn't already set
  if (flags.count(fl))
    std::cerr << "WARNING: flag "
      	      << "\""
	      << fl
      	      << "\""
	      << " is already set!"
	      << std::endl;
  */
#endif

  _flags.insert (fl);
}

void EquationSystems::unset_flag (const std::string& fl)
{
  // Look for the flag in the database
  if (!_flags.count(fl))
    {
      std::cerr << "ERROR: flag " << fl
		<< " was not set!"
		<< std::endl;
      error();
    }

  // Remove the flag
  _flags.erase (fl);
}

Real EquationSystems::parameter (const std::string& id) const
{
  // Look for the id in the database
  std::map<std::string, Real>::const_iterator
    pos = _parameters.find(id);

  if (pos == _parameters.end())
    {
      std::cerr << "ERROR: parameter " << id
		<< " was not set!"
		<< std::endl;
      error();
    }

  // Return the parameter value if found
  return pos->second;
}

Real & EquationSystems::set_parameter (const std::string& id)
{
#ifdef DEBUG
  /*
  // Make sure the parameter isn't already set
  if (parameters.count(id))
    std::cerr << "WARNING: parameter "
	      << "\""
	      << id
	      << "\""
	      << " is already set!"
	      << std::endl;
  */
#endif

  // Insert the parameter/value pair into the database
  return _parameters[id];
}

void EquationSystems::unset_parameter (const std::string& id)
{
  // Look for the id in the database
  std::map<std::string, Real>::iterator
    pos = _parameters.find(id);

  // Make sure the parameter was found
  if (pos == _parameters.end())
    {
      std::cerr << "ERROR: parameter " << id
		<< " was not set!"
		<< std::endl;
      error();
    }

  // Erase the entry
  _parameters.erase(pos);
}

void EquationSystems::build_variable_names (std::vector<std::string>& var_names)
{
  assert (n_systems());

  var_names.resize (n_vars());

  unsigned int var_num=0;

  for (unsigned int sys=0; sys<n_systems(); sys++)
    for (unsigned int vn=0; vn < (*this)(sys).n_vars(); vn++)
      var_names[var_num++] = (*this)(sys).variable_name(vn);
}

void EquationSystems::build_solution_vector (std::vector<Complex>& soln)
{
  assert (n_systems());

  const unsigned int dim = _mesh.mesh_dimension();
  const unsigned int nn  = _mesh.n_nodes();
  const unsigned int nv  = n_vars();

  if (_mesh.processor_id() == 0)
    soln.resize(nn*nv);

  std::vector<Complex> sys_soln;

  unsigned int var_num=0;

  for (unsigned int sys=0; sys<n_systems(); sys++)
    {
      const GeneralSystem& system  = (*this)(sys);
      const unsigned int nv_sys    = system.n_vars();

      system.update_global_solution (sys_soln);

      if (_mesh.processor_id() == 0)
	{
	  std::vector<Complex>      elem_soln;   // The finite element solution
	  std::vector<Complex>      nodal_soln;  // The finite elemnt solution interpolated to the nodes
	  std::vector<unsigned int> dof_indices; // The DOF indices for the finite element

	  for (unsigned int var=0; var<nv_sys; var++)
	    {
	      const FEType& fe_type    = system.variable_type(var);

	      for (unsigned int e=0; e<_mesh.n_elem(); e++)
		if (_mesh.elem(e)->active())
		  {
		    const Elem* elem = _mesh.elem(e);
		    system.get_dof_map().dof_indices (elem, dof_indices, var);

		    elem_soln.resize(dof_indices.size());

		    for (unsigned int i=0; i<dof_indices.size(); i++)
		      elem_soln[i] = sys_soln[dof_indices[i]];

		    FEInterface::nodal_soln (dim, fe_type, elem,
					     elem_soln, nodal_soln);

		    assert (nodal_soln.size() == elem->n_nodes());

		    for (unsigned int n=0; n<elem->n_nodes(); n++)
		      soln[nv*(elem->node(n)) + (var + var_num)] =
			nodal_soln[n];
		  }
	    }
	}

      var_num += nv_sys;
    }
}

std::string EquationSystems::get_info () const
{
  std::ostringstream out;

  out << " EquationSystems:" << std::endl
      << "  n_systems()=" << n_systems() << std::endl;

  for (std::map<std::string, GeneralSystem*>::const_iterator it=_systems.begin();
       it != _systems.end(); ++it)
    {
      const std::string& sys_name    = it->first;
      const GeneralSystem&  system   = *it->second;

      out << "   System \"" << sys_name << "\"" << std::endl
	  << "    Variables=";
      for (unsigned int vn=0; vn<system.n_vars(); vn++)
	out << "\"" << system.variable_name(vn) << "\" ";

      out << std::endl;

#ifndef ENABLE_INFINITE_ELEMENTS
      out << "    Finite Element Types=";
      for (unsigned int vn=0; vn<system.n_vars(); vn++)
      {
	out << "\"" << system.get_dof_map().variable_type(vn).family << "\" ";
      }
#else
      out << "    Finite Element Types=";
      for (unsigned int vn=0; vn<system.n_vars(); vn++)
      {
	out << "\"" << system.get_dof_map().variable_type(vn).family << "\", ";
	out << "\"" << system.get_dof_map().variable_type(vn).radial_family << "\" ";
      }

      out << std::endl << "    Infinite Element Mapping=";
      for (unsigned int vn=0; vn<system.n_vars(); vn++)
      {
	out << "\"" << system.get_dof_map().variable_type(vn).inf_map << "\" ";
      }
#endif

      out << std::endl;

      out << "    Approximation Orders=";
      for (unsigned int vn=0; vn<system.n_vars(); vn++)
      {
#ifndef ENABLE_INFINITE_ELEMENTS
	out << "\"" << system.get_dof_map().variable_type(vn).order << "\" ";
#else
	out << "\"" << system.get_dof_map().variable_type(vn).order << "\", ";
	out << "\"" << system.get_dof_map().variable_type(vn).radial_order << "\" ";
#endif
      }

      out << std::endl;

      out << "    n_dofs()="             << system.n_dofs()             << std::endl;
      out << "    n_local_dofs()="       << system.n_local_dofs()       << std::endl;
#ifdef ENABLE_AMR
      out << "    n_constrained_dofs()=" << system.n_constrained_dofs() << std::endl;
#endif
    }

  if (!_flags.empty())
    {
      out << "  Flags:" << std::endl;

      for (std::set<std::string>::const_iterator flag = _flags.begin();
	   flag != _flags.end(); ++flag)
	out << "   "
	    << "\""
	    << *flag
	    << "\""
	    << std::endl;
    }

  if (!_parameters.empty())
    {
      out << "  Parameters:" << std::endl;

      for (std::map<std::string, Real>::const_iterator
	     param = _parameters.begin(); param != _parameters.end();
	   ++param)
	out << "   "
	    << "\""
	    << param->first
	    << "\""
	    << "="
	    << param->second
	    << std::endl;
    }

  return out.str();
}
<|endoftext|>


<commit_before>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/ozone/impl/file_surface_factory.h"

#include "base/bind.h"
#include "base/file_util.h"
#include "base/location.h"
#include "base/stl_util.h"
#include "base/threading/worker_pool.h"
#include "third_party/skia/include/core/SkBitmapDevice.h"
#include "third_party/skia/include/core/SkDevice.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/vsync_provider.h"

namespace {

void WriteDataToFile(const base::FilePath& location,
                     const SkBitmap& bitmap) {
  std::vector<unsigned char> png_data;
  gfx::PNGCodec::FastEncodeBGRASkBitmap(bitmap, true, &png_data);
  base::WriteFile(location,
                  reinterpret_cast<const char*>(vector_as_array(&png_data)),
                  png_data.size());
}

}

namespace gfx {

FileSurfaceFactory::FileSurfaceFactory(
    const base::FilePath& dump_location)
    : location_(dump_location) {
  CHECK(!base::DirectoryExists(location_))
      << "Location cannot be a directory (" << location_.value() << ")";
  CHECK(!base::PathExists(location_) || base::PathIsWritable(location_));
}

FileSurfaceFactory::~FileSurfaceFactory() {}

SurfaceFactoryOzone::HardwareState
FileSurfaceFactory::InitializeHardware() {
  return INITIALIZED;
}

void FileSurfaceFactory::ShutdownHardware() {
}

AcceleratedWidget FileSurfaceFactory::GetAcceleratedWidget() {
  return 1;
}

AcceleratedWidget FileSurfaceFactory::RealizeAcceleratedWidget(
    AcceleratedWidget widget) {
  return 1;
}

bool FileSurfaceFactory::LoadEGLGLES2Bindings(
      AddGLLibraryCallback add_gl_library,
      SetGLGetProcAddressProcCallback set_gl_get_proc_address) {
  return false;
}

bool FileSurfaceFactory::AttemptToResizeAcceleratedWidget(
    AcceleratedWidget widget,
    const Rect& bounds) {
  device_ = skia::AdoptRef(new SkBitmapDevice(SkBitmap::kARGB_8888_Config,
                                              bounds.width(),
                                              bounds.height()));
  canvas_ = skia::AdoptRef(new SkCanvas(device_.get()));
  return true;
}

bool FileSurfaceFactory::SchedulePageFlip(AcceleratedWidget widget) {
  SkBitmap bitmap;
  bitmap.setConfig(SkBitmap::kARGB_8888_Config,
                   device_->width(),
                   device_->height());

  if (canvas_->readPixels(&bitmap, 0, 0)) {
    base::WorkerPool::PostTask(FROM_HERE,
        base::Bind(&WriteDataToFile, location_, bitmap),
        true);
  }
  return true;
}

SkCanvas* FileSurfaceFactory::GetCanvasForWidget(AcceleratedWidget w) {
  return canvas_.get();
}

scoped_ptr<VSyncProvider> FileSurfaceFactory::CreateVSyncProvider(
    AcceleratedWidget w) {
  return scoped_ptr<VSyncProvider>();
}

}  // namespace gfx
<commit_msg>[Ozone] Update file backend to new Skia interface<commit_after>// Copyright 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "ui/gfx/ozone/impl/file_surface_factory.h"

#include "base/bind.h"
#include "base/file_util.h"
#include "base/location.h"
#include "base/stl_util.h"
#include "base/threading/worker_pool.h"
#include "third_party/skia/include/core/SkBitmapDevice.h"
#include "third_party/skia/include/core/SkDevice.h"
#include "ui/gfx/codec/png_codec.h"
#include "ui/gfx/vsync_provider.h"

namespace {

void WriteDataToFile(const base::FilePath& location,
                     const SkBitmap& bitmap) {
  std::vector<unsigned char> png_data;
  gfx::PNGCodec::FastEncodeBGRASkBitmap(bitmap, true, &png_data);
  base::WriteFile(location,
                  reinterpret_cast<const char*>(vector_as_array(&png_data)),
                  png_data.size());
}

}

namespace gfx {

FileSurfaceFactory::FileSurfaceFactory(
    const base::FilePath& dump_location)
    : location_(dump_location) {
  CHECK(!base::DirectoryExists(location_))
      << "Location cannot be a directory (" << location_.value() << ")";
  CHECK(!base::PathExists(location_) || base::PathIsWritable(location_));
}

FileSurfaceFactory::~FileSurfaceFactory() {}

SurfaceFactoryOzone::HardwareState
FileSurfaceFactory::InitializeHardware() {
  return INITIALIZED;
}

void FileSurfaceFactory::ShutdownHardware() {
}

AcceleratedWidget FileSurfaceFactory::GetAcceleratedWidget() {
  return 1;
}

AcceleratedWidget FileSurfaceFactory::RealizeAcceleratedWidget(
    AcceleratedWidget widget) {
  return 1;
}

bool FileSurfaceFactory::LoadEGLGLES2Bindings(
      AddGLLibraryCallback add_gl_library,
      SetGLGetProcAddressProcCallback set_gl_get_proc_address) {
  return false;
}

bool FileSurfaceFactory::AttemptToResizeAcceleratedWidget(
    AcceleratedWidget widget,
    const Rect& bounds) {
  SkImageInfo info = SkImageInfo::MakeN32Premul(bounds.width(),
                                                bounds.height());
  device_ = skia::AdoptRef(SkBitmapDevice::Create(info));
  canvas_ = skia::AdoptRef(new SkCanvas(device_.get()));
  return true;
}

bool FileSurfaceFactory::SchedulePageFlip(AcceleratedWidget widget) {
  SkBitmap bitmap;
  bitmap.setConfig(SkBitmap::kARGB_8888_Config,
                   device_->width(),
                   device_->height());

  if (canvas_->readPixels(&bitmap, 0, 0)) {
    base::WorkerPool::PostTask(FROM_HERE,
        base::Bind(&WriteDataToFile, location_, bitmap),
        true);
  }
  return true;
}

SkCanvas* FileSurfaceFactory::GetCanvasForWidget(AcceleratedWidget w) {
  return canvas_.get();
}

scoped_ptr<VSyncProvider> FileSurfaceFactory::CreateVSyncProvider(
    AcceleratedWidget w) {
  return scoped_ptr<VSyncProvider>();
}

}  // namespace gfx
<|endoftext|>


<commit_before>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

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 "LuaStack.h"
#include "LuaEnvironment.h"
#include "World.h"
#include "Device.h"

namespace crown
{

//-----------------------------------------------------------------------------
CE_EXPORT int world_spawn_unit(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);
	const char* name = stack.get_string(2);

	const Vector3& pos = stack.num_args() > 2 ? stack.get_vector3(3) : Vector3::ZERO;
	const Quaternion& rot = stack.num_args() > 3 ? stack.get_quaternion(4) : Quaternion::IDENTITY;

	UnitId unit = world->spawn_unit(name, pos, rot);

	stack.push_unit(world->lookup_unit(unit));
	return 1;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_play_sound(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);
	const char* name = stack.get_string(2);

	const bool loop = stack.num_args() > 2 ? stack.get_bool(3) : false;
	const float volume = stack.num_args() > 3 ? stack.get_float(4) : 1.0f; // test value
	const Vector3& pos = stack.num_args() > 4 ? stack.get_vector3(5) : Vector3::ZERO;
	const float range = stack.num_args() > 5 ? stack.get_float(6) : 1000.0f; // test value

	SoundInstanceId id = world->play_sound(name, loop, volume, pos, range);

	stack.push_int32(id.encode());

	return 1;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_pause_sound(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);

	SoundInstanceId id;
	id.decode(stack.get_int(2));

	world->pause_sound(id);

	return 0;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_link_sound(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);

	SoundInstanceId sound;
	sound.decode(stack.get_int(2));

	UnitId unit;
	unit.decode(stack.get_int(3));

	world->link_sound(sound, unit);

	return 0;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_set_listener(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);

	const Vector3& pos = stack.get_vector3(2);
	const Vector3& vel = stack.get_vector3(3);
	const Vector3& or_up = stack.get_vector3(4);
	const Vector3& or_at = stack.get_vector3(5);

	world->set_listener(pos, vel, or_up, or_at);

	return 0;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_set_sound_position(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);

	SoundInstanceId id;
	id.decode(stack.get_int(2));

	const Vector3& pos = stack.get_vector3(3);

	world->set_sound_position(id, pos);

	return 0;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_set_sound_range(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);

	SoundInstanceId id;
	id.decode(stack.get_int(2));

	float range = stack.get_float(3);

	world->set_sound_range(id, range);

	return 0;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_set_sound_volume(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);

	SoundInstanceId id;
	id.decode(stack.get_int(2));
	float vol = stack.get_float(3);

	world->set_sound_volume(id, vol);

	return 0;
}

//-----------------------------------------------------------------------------
void load_world(LuaEnvironment& env)
{
	env.load_module_function("World", "spawn_unit",			world_spawn_unit);

	env.load_module_function("World", "play_sound",			world_play_sound);
	env.load_module_function("World", "pause_sound", 		world_pause_sound);
	env.load_module_function("World", "link_sound",			world_link_sound);
	env.load_module_function("World", "set_listener", 		world_set_listener);
	env.load_module_function("World", "set_sound_position", world_set_sound_position);
	env.load_module_function("World", "set_sound_range", 	world_set_sound_range);
	env.load_module_function("World", "set_sound_volume", 	world_set_sound_volume);
}

} // namespace crown<commit_msg>Add destory_unit() and fix link_sound()<commit_after>/*
Copyright (c) 2013 Daniele Bartolini, Michele Rossi
Copyright (c) 2012 Daniele Bartolini, Simone Boscaratto

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 "LuaStack.h"
#include "LuaEnvironment.h"
#include "World.h"
#include "Device.h"

namespace crown
{

//-----------------------------------------------------------------------------
CE_EXPORT int world_spawn_unit(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);
	const char* name = stack.get_string(2);

	const Vector3& pos = stack.num_args() > 2 ? stack.get_vector3(3) : Vector3::ZERO;
	const Quaternion& rot = stack.num_args() > 3 ? stack.get_quaternion(4) : Quaternion::IDENTITY;

	UnitId unit = world->spawn_unit(name, pos, rot);

	stack.push_unit(world->lookup_unit(unit));
	return 1;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_destroy_unit(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);
	Unit* unit = stack.get_unit(2);

	world->destroy_unit(unit);
	return 0;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_play_sound(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);
	const char* name = stack.get_string(2);

	const bool loop = stack.num_args() > 2 ? stack.get_bool(3) : false;
	const float volume = stack.num_args() > 3 ? stack.get_float(4) : 1.0f; // test value
	const Vector3& pos = stack.num_args() > 4 ? stack.get_vector3(5) : Vector3::ZERO;
	const float range = stack.num_args() > 5 ? stack.get_float(6) : 1000.0f; // test value

	SoundInstanceId id = world->play_sound(name, loop, volume, pos, range);

	stack.push_int32(id.encode());

	return 1;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_pause_sound(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);

	SoundInstanceId id;
	id.decode(stack.get_int(2));

	world->pause_sound(id);

	return 0;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_link_sound(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);

	SoundInstanceId sound;
	sound.decode(stack.get_int(2));

	Unit* unit = stack.get_unit(3);
	int32_t node = stack.get_int(4);

	world->link_sound(sound, unit, node);

	return 0;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_set_listener(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);

	const Vector3& pos = stack.get_vector3(2);
	const Vector3& vel = stack.get_vector3(3);
	const Vector3& or_up = stack.get_vector3(4);
	const Vector3& or_at = stack.get_vector3(5);

	world->set_listener(pos, vel, or_up, or_at);

	return 0;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_set_sound_position(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);

	SoundInstanceId id;
	id.decode(stack.get_int(2));

	const Vector3& pos = stack.get_vector3(3);

	world->set_sound_position(id, pos);

	return 0;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_set_sound_range(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);

	SoundInstanceId id;
	id.decode(stack.get_int(2));

	float range = stack.get_float(3);

	world->set_sound_range(id, range);

	return 0;
}

//-----------------------------------------------------------------------------
CE_EXPORT int world_set_sound_volume(lua_State* L)
{
	LuaStack stack(L);

	World* world = stack.get_world(1);

	SoundInstanceId id;
	id.decode(stack.get_int(2));
	float vol = stack.get_float(3);

	world->set_sound_volume(id, vol);

	return 0;
}

//-----------------------------------------------------------------------------
void load_world(LuaEnvironment& env)
{
	env.load_module_function("World", "spawn_unit",			world_spawn_unit);
	env.load_module_function("World", "destroy_unit",       world_destroy_unit);

	env.load_module_function("World", "play_sound",			world_play_sound);
	env.load_module_function("World", "pause_sound", 		world_pause_sound);
	env.load_module_function("World", "link_sound",			world_link_sound);
	env.load_module_function("World", "set_listener", 		world_set_listener);
	env.load_module_function("World", "set_sound_position", world_set_sound_position);
	env.load_module_function("World", "set_sound_range", 	world_set_sound_range);
	env.load_module_function("World", "set_sound_volume", 	world_set_sound_volume);
}

} // namespace crown<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: animationbasenode.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-07 20:39:43 $
 *
 *  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 _SLIDESHOW_ANIMATIONBASENODE_HXX
#define _SLIDESHOW_ANIMATIONBASENODE_HXX

#include <basecontainernode.hxx>
#include <activitiesfactory.hxx>
#include <shapeattributelayer.hxx>
#include <shapeattributelayerholder.hxx>
#include <attributableshape.hxx>
#include <shapesubset.hxx>

#ifndef _COM_SUN_STAR_ANIMATIONS_XANIMATE_HPP_
#include <com/sun/star/animations/XAnimate.hpp>
#endif

namespace presentation
{
    namespace internal
    {
        /** Common base class for all leaf animation nodes.

        This class basically holds the target shape
        */
        class AnimationBaseNode : public BaseNode
        {
        public:
            AnimationBaseNode( const ::com::sun::star::uno::Reference<
                                       ::com::sun::star::animations::XAnimationNode >&  xNode,
                               const BaseContainerNodeSharedPtr&                    rParent,
                               const NodeContext&                                   rContext );

            virtual bool init();
            virtual void dispose();
            virtual bool resolve();
            virtual bool activate();
            virtual void deactivate();
            virtual void end();
            virtual void notifyDeactivating( const AnimationNodeSharedPtr& rNotifier );
            virtual bool hasPendingAnimation() const;

#if defined(VERBOSE) && defined(DBG_UTIL)
            virtual void showState() const;
#endif
        protected:

            /** Animation-specific end().

                This is also called from deactivate, for subsetted
                shapes. Actually force-ends the underlying animation
                activity.
            */
            void endAnimation();

            /** Create parameter struct for ActivitiesFactory
             */
            ActivitiesFactory::CommonParameters fillCommonParameters() const;

            /** Create AnimationActivity from common XAnimate parameters
             */
            AnimationActivitySharedPtr createActivity() const;

            /// Returns true, if this node animates a subset of a shape
            bool isSubsettedShape() const;

            /** Returns true, if this is a subset animation, and
                the subset is autogenerated (e.g. from an
                iteration)
            */
            bool isDependentSubsettedShape() const;

            /** This method enables a subset shape
             */
            void enableShapeSubset();

            /** This method removes subset shapes

                Subset shapes may be only temporarily added to a
                slide. When the animation active duration ends,
                and they are generated from iterated effects, they
                are removed again for redraw
                performance. Furthermore, they are revoked from
                the original shape, such that it displays the full
                content again.
            */
            void disableShapeSubset();

            AttributableShapeSharedPtr getShape() const;

            // inline accessors
            // ----------------

            const ::com::sun::star::uno::Reference<
                ::com::sun::star::animations::XAnimate >& getXAnimateNode() const { return mxAnimateNode; }
            const ShapeAttributeLayerHolder&              getAttributeLayerHolder() const { return maAttributeLayerHolder; }
            const AnimationActivitySharedPtr&             getActivity() const { return mpActivity; }
            AnimationActivitySharedPtr&                   getActivity() { return mpActivity; }

        private:
            ::com::sun::star::uno::Reference<
                ::com::sun::star::animations::XAnimate >    mxAnimateNode;
            ShapeAttributeLayerHolder                       maAttributeLayerHolder;
            AnimationActivitySharedPtr                      mpActivity;

            /// When valid, this node has a plain target shape
            AttributableShapeSharedPtr                      mpShape;
            /// When valid, this is a subsetted target shape
            ShapeSubsetSharedPtr                            mpShapeSubset;
            bool                                            mbIsIndependentSubset;
        };
    }
}

#endif /* _SLIDESHOW_ANIMATIONBASENODE_HXX */
<commit_msg>INTEGRATION: CWS presfixes08 (1.2.30); FILE MERGED 2005/07/15 13:11:01 dbo 1.2.30.1: #i45197# skipping animations, cleanup Issue number: Submitted by: Reviewed by:<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: animationbasenode.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2005-10-11 08:42:13 $
 *
 *  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 INCLUDED_SLIDESHOW_ANIMATIONBASENODE_HXX
#define INCLUDED_SLIDESHOW_ANIMATIONBASENODE_HXX

#include "basecontainernode.hxx"
#include "activitiesfactory.hxx"
#include "shapeattributelayer.hxx"
#include "shapeattributelayerholder.hxx"
#include "attributableshape.hxx"
#include "shapesubset.hxx"
#include "com/sun/star/animations/XAnimate.hpp"

namespace presentation {
namespace internal {

/** Common base class for all leaf animation nodes.

    This class basically holds the target shape
*/
class AnimationBaseNode : public BaseNode
{
public:
    AnimationBaseNode(
        ::com::sun::star::uno::Reference<
        ::com::sun::star::animations::XAnimationNode> const & xNode,
        BaseContainerNodeSharedPtr const & rParent,
        NodeContext const & rContext );

    virtual bool init();
    virtual void dispose();
    virtual bool resolve();
    virtual bool activate();
    virtual void deactivate();
    virtual void end();
    virtual void notifyDeactivating( AnimationNodeSharedPtr const & rNotifier );
    virtual bool hasPendingAnimation() const;

#if defined(VERBOSE) && defined(DBG_UTIL)
    virtual void showState() const;
#endif
protected:

    /** Animation-specific end().

        This is also called from deactivate, for subsetted
        shapes. Actually force-ends the underlying animation
        activity.
    */
    void endAnimation();

    /** Create parameter struct for ActivitiesFactory
     */
    ActivitiesFactory::CommonParameters fillCommonParameters() const;

    /** Create AnimationActivity from common XAnimate parameters
     */
    AnimationActivitySharedPtr createActivity() const;

    /// Returns true, if this node animates a subset of a shape
    bool isSubsettedShape() const;

    /** Returns true, if this is a subset animation, and
        the subset is autogenerated (e.g. from an
        iteration)
    */
    bool isDependentSubsettedShape() const;

    /** This method enables a subset shape
     */
    void enableShapeSubset();

    /** This method removes subset shapes

        Subset shapes may be only temporarily added to a
        slide. When the animation active duration ends,
        and they are generated from iterated effects, they
        are removed again for redraw
        performance. Furthermore, they are revoked from
        the original shape, such that it displays the full
        content again.
    */
    void disableShapeSubset();

    AttributableShapeSharedPtr getShape() const;

    // inline accessors
    // ----------------

    ::com::sun::star::uno::Reference<
        ::com::sun::star::animations::XAnimate> const & getXAnimateNode() const
        { return mxAnimateNode; }
    ShapeAttributeLayerHolder const & getAttributeLayerHolder() const
        { return maAttributeLayerHolder; }
    AnimationActivitySharedPtr const & getActivity() const
        { return mpActivity; }
    AnimationActivitySharedPtr & getActivity()
        { return mpActivity; }

private:
    ::com::sun::star::uno::Reference<
        ::com::sun::star::animations::XAnimate>     mxAnimateNode;
    ShapeAttributeLayerHolder                       maAttributeLayerHolder;
    AnimationActivitySharedPtr                      mpActivity;

    /// When valid, this node has a plain target shape
    AttributableShapeSharedPtr                      mpShape;
    /// When valid, this is a subsetted target shape
    ShapeSubsetSharedPtr                            mpShapeSubset;
    bool                                            mbIsIndependentSubset;
};

} // namespace internal
} // namespace presentation

#endif /* INCLUDED_SLIDESHOW_ANIMATIONBASENODE_HXX */
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: basecontainernode.cxx,v $
 *
 *  $Revision: 1.7 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 08:35:24 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"

// must be first
#include "canvas/debug.hxx"
#include "canvas/verbosetrace.hxx"
#include "basecontainernode.hxx"
#include "tools.hxx"
#include "nodetools.hxx"
#include "delayevent.hxx"
#include "boost/mem_fn.hpp"
#include <vector>
#include <algorithm>
#include <iterator>

using namespace com::sun::star;

namespace presentation {
namespace internal {

BaseContainerNode::BaseContainerNode(
    const uno::Reference< animations::XAnimationNode >&     xNode,
    const BaseContainerNodeSharedPtr&                       rParent,
    const NodeContext&                                      rContext )
    : BaseNode( xNode, rParent, rContext ),
      maChildren(),
      mnFinishedChildren(0),
      mbDurationIndefinite( isIndefiniteTiming( xNode->getEnd() ) ||
                            isIndefiniteTiming( xNode->getDuration() ) )
{
}

void BaseContainerNode::dispose()
{
    forEachChildNode( boost::mem_fn(&Disposable::dispose) );
    maChildren.clear();
    BaseNode::dispose();
}

bool BaseContainerNode::init_st()
{
    mnFinishedChildren = 0;
    // initialize all children
    return (std::count_if(
                maChildren.begin(), maChildren.end(),
                boost::mem_fn(&AnimationNode::init) ) ==
            static_cast<VectorOfNodes::difference_type>(maChildren.size()));
}

void BaseContainerNode::deactivate_st( NodeState eDestState )
{
    if (eDestState == FROZEN) {
        // deactivate all children that are not FROZEN or ENDED:
        forEachChildNode( boost::mem_fn(&AnimationNode::deactivate),
                          ~(FROZEN | ENDED) );
    }
    else {
        // end all children that are not ENDED:
        forEachChildNode( boost::mem_fn(&AnimationNode::end), ~ENDED );
    }
}

bool BaseContainerNode::hasPendingAnimation() const
{
    // does any of our children returns "true" on
    // AnimationNode::hasPendingAnimation()?
    // If yes, we, too, return true
    VectorOfNodes::const_iterator const iEnd( maChildren.end() );
    return (std::find_if(
                maChildren.begin(), iEnd,
                boost::mem_fn(&AnimationNode::hasPendingAnimation) ) != iEnd);
}

void BaseContainerNode::appendChildNode( AnimationNodeSharedPtr const& pNode )
{
    if (! checkValidNode())
        return;

    // register derived classes as end listeners at all children.
    // this is necessary to control the children animation
    // sequence, and to determine our own end event
    if (pNode->registerDeactivatingListener( getSelf() )) {
        maChildren.push_back( pNode );
    }
}

bool BaseContainerNode::isChildNode( AnimationNodeSharedPtr const& pNode ) const
{
    // find given notifier in child vector
    VectorOfNodes::const_iterator const iBegin( maChildren.begin() );
    VectorOfNodes::const_iterator const iEnd( maChildren.end() );
    VectorOfNodes::const_iterator const iFind(
        std::find( iBegin, iEnd, pNode ) );
    return (iFind != iEnd);
}

bool BaseContainerNode::notifyDeactivatedChild(
    AnimationNodeSharedPtr const& pChildNode )
{
    OSL_ASSERT( pChildNode->getState() == FROZEN ||
                pChildNode->getState() == ENDED );
    // early exit on invalid nodes
    OSL_ASSERT( getState() != INVALID );
    if( getState() == INVALID )
        return false;

    if (! isChildNode(pChildNode)) {
        OSL_ENSURE( false, "unknown notifier!" );
        return false;
    }

    std::size_t const nSize = maChildren.size();
    OSL_ASSERT( mnFinishedChildren < nSize );
    ++mnFinishedChildren;
    bool const bFinished = (mnFinishedChildren >= nSize);

    // all children finished, and we've got indefinite duration?
    // think of ParallelTimeContainer::notifyDeactivating()
    // if duration given, we will be deactivated by some end event
    // @see fillCommonParameters()
    if (bFinished && isDurationIndefinite()) {
        deactivate();
    }

    return bFinished;
}

#if defined(VERBOSE) && defined(DBG_UTIL)
void BaseContainerNode::showState() const
{
    for( std::size_t i=0; i<maChildren.size(); ++i )
    {
        BaseNodeSharedPtr pNode =
            boost::shared_dynamic_cast<BaseNode>(maChildren[i]);
        VERBOSE_TRACE(
            "Node connection: n0x%X -> n0x%X",
            (const char*)this+debugGetCurrentOffset(),
            (const char*)pNode.get()+debugGetCurrentOffset() );
        pNode->showState();
    }

    BaseNode::showState();
}
#endif

} // namespace internal
} // namespace presentation

<commit_msg>INTEGRATION: CWS presfixes09 (1.5.16); FILE MERGED 2006/10/18 19:55:17 thb 1.5.16.5: RESYNC: (1.6-1.7); FILE MERGED 2006/09/15 22:15:30 thb 1.5.16.4: RESYNC: (1.5-1.6); FILE MERGED 2006/04/24 13:25:29 thb 1.5.16.3: #i53194# Unified include statements (local headers always have double quotes; external headers angle brackets); reverted EventMultiplexer pause events to shared_ptr; removed EventMultiplexer::removeViewHandler(), since the handler is held weakly, anyway. 2006/04/12 20:40:07 thb 1.5.16.2: #i37778# Replaced all shared_ptr.get() != NULL places with the more elegant automatic-conversion-to-bool version (at least where the compiler tolerated that) 2006/03/24 18:23:18 thb 1.5.16.1: #i37778# Moved whole slideshow engine from namespace presentation (which conflicts with one of the UNO subnamespaces) to slideshow<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: basecontainernode.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: kz $ $Date: 2006-12-13 15:32:16 $
 *
 *  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
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_slideshow.hxx"

// must be first
#include "canvas/debug.hxx"
#include "canvas/verbosetrace.hxx"
#include "basecontainernode.hxx"
#include "tools.hxx"
#include "nodetools.hxx"
#include "delayevent.hxx"
#include "boost/mem_fn.hpp"
#include <vector>
#include <algorithm>
#include <iterator>

using namespace com::sun::star;

namespace slideshow {
namespace internal {

BaseContainerNode::BaseContainerNode(
    const uno::Reference< animations::XAnimationNode >&     xNode,
    const BaseContainerNodeSharedPtr&                       rParent,
    const NodeContext&                                      rContext )
    : BaseNode( xNode, rParent, rContext ),
      maChildren(),
      mnFinishedChildren(0),
      mbDurationIndefinite( isIndefiniteTiming( xNode->getEnd() ) ||
                            isIndefiniteTiming( xNode->getDuration() ) )
{
}

void BaseContainerNode::dispose()
{
    forEachChildNode( boost::mem_fn(&Disposable::dispose) );
    maChildren.clear();
    BaseNode::dispose();
}

bool BaseContainerNode::init_st()
{
    mnFinishedChildren = 0;
    // initialize all children
    return (std::count_if(
                maChildren.begin(), maChildren.end(),
                boost::mem_fn(&AnimationNode::init) ) ==
            static_cast<VectorOfNodes::difference_type>(maChildren.size()));
}

void BaseContainerNode::deactivate_st( NodeState eDestState )
{
    if (eDestState == FROZEN) {
        // deactivate all children that are not FROZEN or ENDED:
        forEachChildNode( boost::mem_fn(&AnimationNode::deactivate),
                          ~(FROZEN | ENDED) );
    }
    else {
        // end all children that are not ENDED:
        forEachChildNode( boost::mem_fn(&AnimationNode::end), ~ENDED );
    }
}

bool BaseContainerNode::hasPendingAnimation() const
{
    // does any of our children returns "true" on
    // AnimationNode::hasPendingAnimation()?
    // If yes, we, too, return true
    VectorOfNodes::const_iterator const iEnd( maChildren.end() );
    return (std::find_if(
                maChildren.begin(), iEnd,
                boost::mem_fn(&AnimationNode::hasPendingAnimation) ) != iEnd);
}

void BaseContainerNode::appendChildNode( AnimationNodeSharedPtr const& pNode )
{
    if (! checkValidNode())
        return;

    // register derived classes as end listeners at all children.
    // this is necessary to control the children animation
    // sequence, and to determine our own end event
    if (pNode->registerDeactivatingListener( getSelf() )) {
        maChildren.push_back( pNode );
    }
}

bool BaseContainerNode::isChildNode( AnimationNodeSharedPtr const& pNode ) const
{
    // find given notifier in child vector
    VectorOfNodes::const_iterator const iBegin( maChildren.begin() );
    VectorOfNodes::const_iterator const iEnd( maChildren.end() );
    VectorOfNodes::const_iterator const iFind(
        std::find( iBegin, iEnd, pNode ) );
    return (iFind != iEnd);
}

bool BaseContainerNode::notifyDeactivatedChild(
    AnimationNodeSharedPtr const& pChildNode )
{
    OSL_ASSERT( pChildNode->getState() == FROZEN ||
                pChildNode->getState() == ENDED );
    // early exit on invalid nodes
    OSL_ASSERT( getState() != INVALID );
    if( getState() == INVALID )
        return false;

    if (! isChildNode(pChildNode)) {
        OSL_ENSURE( false, "unknown notifier!" );
        return false;
    }

    std::size_t const nSize = maChildren.size();
    OSL_ASSERT( mnFinishedChildren < nSize );
    ++mnFinishedChildren;
    bool const bFinished = (mnFinishedChildren >= nSize);

    // all children finished, and we've got indefinite duration?
    // think of ParallelTimeContainer::notifyDeactivating()
    // if duration given, we will be deactivated by some end event
    // @see fillCommonParameters()
    if (bFinished && isDurationIndefinite()) {
        deactivate();
    }

    return bFinished;
}

#if defined(VERBOSE) && defined(DBG_UTIL)
void BaseContainerNode::showState() const
{
    for( std::size_t i=0; i<maChildren.size(); ++i )
    {
        BaseNodeSharedPtr pNode =
            boost::shared_dynamic_cast<BaseNode>(maChildren[i]);
        VERBOSE_TRACE(
            "Node connection: n0x%X -> n0x%X",
            (const char*)this+debugGetCurrentOffset(),
            (const char*)pNode.get()+debugGetCurrentOffset() );
        pNode->showState();
    }

    BaseNode::showState();
}
#endif

} // namespace internal
} // namespace slideshow

<|endoftext|>


<commit_before>/*
 *   Copyright (C) 2011 Ivan Cukic <ivan.cukic(at)kde.org>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License version 2,
 *   or (at your option) any later version, as published by the Free
 *   Software Foundation
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details
 *
 *   You should have received a copy of the GNU General Public
 *   License along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "Documents.h"
#include "Documents_p.h"
#include "rankingsclientadaptor.h"

#include <QList>
#include <QDBusConnection>
#include <QDesktopServices>

#include <Nepomuk/Resource>
#include <Nepomuk/Variant>

#include <KDebug>
#include <KUrl>
#include <KFileItem>

#include "nfo.h"
#include "nie.h"
#include "kext.h"

#define KAMD_DBUS_ADDRESS "org.kde.kactivitymanagerd"

using namespace Nepomuk::Vocabulary;

// Private

DocumentsEnginePrivate::DocumentsEnginePrivate(DocumentsEngine * parent)
    : q(parent)
{
    activitymanager = new KActivities::Consumer(this);

    QDBusConnection dbus = QDBusConnection::sessionBus();

    // Making us visible on d-bus
    new RankingsClientAdaptor(this);
    kDebug() << "registering the client" <<
    dbus.registerObject("/RankingsClient", this);

    if (dbus.interface()->isServiceRegistered(KAMD_DBUS_ADDRESS)) {
        serviceOnline();
    }

    QDBusServiceWatcher * watcher = new QDBusServiceWatcher(
            KAMD_DBUS_ADDRESS, dbus,
            QDBusServiceWatcher::WatchForRegistration | QDBusServiceWatcher::WatchForUnregistration,
            this
        );
    connect(watcher, SIGNAL(serviceRegistered(QString)),
            this, SLOT(serviceOnline()));
    connect(watcher, SIGNAL(serviceUnregistered(QString)),
            this, SLOT(serviceOffline()));
}

void DocumentsEnginePrivate::serviceOnline()
{
    kDebug() << KAMD_DBUS_ADDRESS << "went online";

    QDBusInterface rankingsservice(KAMD_DBUS_ADDRESS,
            "/Rankings", "org.kde.ActivityManager.Rankings");

    rankingsservice.asyncCall("registerClient", "org.kde.Contour", QString(), "nao:Document");
}

void DocumentsEnginePrivate::serviceOffline()
{
    kDebug() << KAMD_DBUS_ADDRESS << "went offline";

    q->recommendationsUpdated(QList<Contour::RecommendationItem>());
}

DocumentsEnginePrivate::~DocumentsEnginePrivate()
{
}

void DocumentsEnginePrivate::updated(const QVariantList & data)
{
    kDebug() << "@@@@@@@@@@@@@@@@@@" << data;
    recommendations.clear();

    double score = 1.0;

    foreach (const QVariant & item, data) {
        Nepomuk::Resource resource(KUrl(item.toString()));

        // The problem is when the resource has no particular type set (web page)
        // if (!resource.hasType(Nepomuk::Vocabulary::NFO::FileDataObject())) continue;

        Nepomuk::Resource currentActivityResource(activitymanager->currentActivity(), KEXT::Activity());

        // TODO: See ActivityManager.coo
        // I'd like a resource isRelated activity more than vice-versa
        // but the active models are checking for the other way round.
        // It is defined in the ontologies as a symmetric relation, but
        // Nepomuk doesn't care about that.

        // if (resource.isRelateds().contains(currentActivityResource)) continue;
        if (currentActivityResource.isRelateds().contains(resource)) continue;

        Contour::RecommendationItem recommendation;

        recommendation.score       = score;
        recommendation.id          = item.toString();
        score /= 2;

        recommendation.title       = resource.genericLabel();
        recommendation.description = i18n("Open in the current activity");
        recommendation.icon        = resource.genericIcon();

        if (recommendation.icon.isEmpty()) {
            KFileItem fileItem(KFileItem::Unknown, KFileItem::Unknown,
                    KUrl(resource.property(Nepomuk::Vocabulary::NIE::url()).toString()));
            recommendation.icon = fileItem.iconName();
        }

        kDebug() << recommendation;

        recommendations << recommendation;

        if (recommendations.size() >= 3) break;

    }

    q->recommendationsUpdated(recommendations);

}

void DocumentsEnginePrivate::removeRecommendation(const QString & id)
{
    for (int i = 0; i < recommendations.size(); i++) {
        if (recommendations[i].id == id) {
            recommendations.removeAt(i);
            break;
        }
    }
}

void DocumentsEnginePrivate::inserted(int position, const QVariantList & item)
{
}

void DocumentsEnginePrivate::removed(int position)
{
}

void DocumentsEnginePrivate::changed(int position, const QVariantList & item)
{
}

// DocumentsEngine

DocumentsEngine::DocumentsEngine(QObject * parent, const QVariantList & args)
    : Contour::RecommendationEngine(parent), d(new DocumentsEnginePrivate(this))
{
}

DocumentsEngine::~DocumentsEngine()
{
    delete d;
}

void DocumentsEngine::init()
{
    Contour::RecommendationEngine::init();

    emit recommendationsUpdated(d->recommendations);
}

void DocumentsEngine::activate(const QString & id, const QString & action)
{
    KUrl url(id);

    d->removeRecommendation(id);

    d->activitymanager->linkResourceToActivity(url);

    QDesktopServices::openUrl(url);

}

RECOMMENDATION_EXPORT_PLUGIN(DocumentsEngine, "contour_recommendationengine_documents")

<commit_msg>DBus object<commit_after>/*
 *   Copyright (C) 2011 Ivan Cukic <ivan.cukic(at)kde.org>
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License version 2,
 *   or (at your option) any later version, as published by the Free
 *   Software Foundation
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details
 *
 *   You should have received a copy of the GNU General Public
 *   License along with this program; if not, write to the
 *   Free Software Foundation, Inc.,
 *   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

#include "Documents.h"
#include "Documents_p.h"
#include "rankingsclientadaptor.h"

#include <QList>
#include <QDBusConnection>
#include <QDesktopServices>

#include <Nepomuk/Resource>
#include <Nepomuk/Variant>

#include <KDebug>
#include <KUrl>
#include <KFileItem>

#include "nfo.h"
#include "nie.h"
#include "kext.h"

#define KAMD_DBUS_ADDRESS "org.kde.kactivitymanagerd"

using namespace Nepomuk::Vocabulary;

// Private

DocumentsEnginePrivate::DocumentsEnginePrivate(DocumentsEngine * parent)
    : q(parent)
{
    activitymanager = new KActivities::Consumer(this);

    QDBusConnection dbus = QDBusConnection::sessionBus();

    // Making us visible on d-bus
    new RankingsClientAdaptor(this);
    // kDebug() << "registering the client" <<
    dbus.registerObject("/RankingsClient", this);

    if (dbus.interface()->isServiceRegistered(KAMD_DBUS_ADDRESS)) {
        serviceOnline();
    }

    QDBusServiceWatcher * watcher = new QDBusServiceWatcher(
            KAMD_DBUS_ADDRESS, dbus,
            QDBusServiceWatcher::WatchForRegistration | QDBusServiceWatcher::WatchForUnregistration,
            this
        );
    connect(watcher, SIGNAL(serviceRegistered(QString)),
            this, SLOT(serviceOnline()));
    connect(watcher, SIGNAL(serviceUnregistered(QString)),
            this, SLOT(serviceOffline()));
}

void DocumentsEnginePrivate::serviceOnline()
{
    kDebug() << KAMD_DBUS_ADDRESS << "went online";

    QDBusInterface rankingsservice(KAMD_DBUS_ADDRESS,
            "/Rankings", "org.kde.ActivityManager.Rankings");

    rankingsservice.asyncCall("registerClient", "org.kde.Contour", QString(), "nao:Document");
}

void DocumentsEnginePrivate::serviceOffline()
{
    kDebug() << KAMD_DBUS_ADDRESS << "went offline";

    q->recommendationsUpdated(QList<Contour::RecommendationItem>());
}

DocumentsEnginePrivate::~DocumentsEnginePrivate()
{
}

void DocumentsEnginePrivate::updated(const QVariantList & data)
{
    kDebug() << "@@@@@@@@@@@@@@@@@@" << data;
    recommendations.clear();

    double score = 1.0;

    foreach (const QVariant & item, data) {
        Nepomuk::Resource resource(KUrl(item.toString()));

        // The problem is when the resource has no particular type set (web page)
        // if (!resource.hasType(Nepomuk::Vocabulary::NFO::FileDataObject())) continue;

        Nepomuk::Resource currentActivityResource(activitymanager->currentActivity(), KEXT::Activity());

        // TODO: See ActivityManager.coo
        // I'd like a resource isRelated activity more than vice-versa
        // but the active models are checking for the other way round.
        // It is defined in the ontologies as a symmetric relation, but
        // Nepomuk doesn't care about that.

        // if (resource.isRelateds().contains(currentActivityResource)) continue;
        if (currentActivityResource.isRelateds().contains(resource)) continue;

        Contour::RecommendationItem recommendation;

        recommendation.score       = score;
        recommendation.id          = item.toString();
        score /= 2;

        recommendation.title       = resource.genericLabel();
        recommendation.description = i18n("Open in the current activity");
        recommendation.icon        = resource.genericIcon();

        if (recommendation.icon.isEmpty()) {
            KFileItem fileItem(KFileItem::Unknown, KFileItem::Unknown,
                    KUrl(resource.property(Nepomuk::Vocabulary::NIE::url()).toString()));
            recommendation.icon = fileItem.iconName();
        }

        kDebug() << recommendation;

        recommendations << recommendation;

        if (recommendations.size() >= 3) break;

    }

    q->recommendationsUpdated(recommendations);

}

void DocumentsEnginePrivate::removeRecommendation(const QString & id)
{
    for (int i = 0; i < recommendations.size(); i++) {
        if (recommendations[i].id == id) {
            recommendations.removeAt(i);
            break;
        }
    }
}

void DocumentsEnginePrivate::inserted(int position, const QVariantList & item)
{
}

void DocumentsEnginePrivate::removed(int position)
{
}

void DocumentsEnginePrivate::changed(int position, const QVariantList & item)
{
}

// DocumentsEngine

DocumentsEngine::DocumentsEngine(QObject * parent, const QVariantList & args)
    : Contour::RecommendationEngine(parent), d(new DocumentsEnginePrivate(this))
{
}

DocumentsEngine::~DocumentsEngine()
{
    delete d;
}

void DocumentsEngine::init()
{
    Contour::RecommendationEngine::init();

    emit recommendationsUpdated(d->recommendations);
}

void DocumentsEngine::activate(const QString & id, const QString & action)
{
    KUrl url(id);

    d->removeRecommendation(id);

    d->activitymanager->linkResourceToActivity(url);

    QDesktopServices::openUrl(url);

}

RECOMMENDATION_EXPORT_PLUGIN(DocumentsEngine, "contour_recommendationengine_documents")

<|endoftext|>