<commit_before>/*************************************************************************/
/*  javascript_main.cpp                                                  */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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 "core/io/resource_loader.h"
#include "main/main.h"
#include "platform/javascript/display_server_javascript.h"
#include "platform/javascript/os_javascript.h"

#include <emscripten/emscripten.h>
#include <stdlib.h>

#include "godot_js.h"

static OS_JavaScript *os = nullptr;
static uint64_t target_ticks = 0;

void exit_callback() {
	emscripten_cancel_main_loop(); // After this, we can exit!
	Main::cleanup();
	int exit_code = OS_JavaScript::get_singleton()->get_exit_code();
	memdelete(os);
	os = nullptr;
	emscripten_force_exit(exit_code); // No matter that we call cancel_main_loop, regular "exit" will not work, forcing.
}

void cleanup_after_sync() {
	emscripten_set_main_loop(exit_callback, -1, false);
}

void main_loop_callback() {
	uint64_t current_ticks = os->get_ticks_usec();

	bool force_draw = DisplayServerJavaScript::get_singleton()->check_size_force_redraw();
	if (force_draw) {
		Main::force_redraw();
	} else if (current_ticks < target_ticks) {
		return; // Skip frame.
	}

	int target_fps = Engine::get_singleton()->get_target_fps();
	if (target_fps > 0) {
		if (current_ticks - target_ticks > 1000000) {
			// When the window loses focus, we stop getting updates and accumulate delay.
			// For this reason, if the difference is too big, we reset target ticks to the current ticks.
			target_ticks = current_ticks;
		}
		target_ticks += (uint64_t)(1000000 / target_fps);
	}
	if (os->main_loop_iterate()) {
		emscripten_cancel_main_loop(); // Cancel current loop and wait for cleanup_after_sync.
		godot_js_os_finish_async(cleanup_after_sync);
	}
}

/// When calling main, it is assumed FS is setup and synced.
extern EMSCRIPTEN_KEEPALIVE int godot_js_main(int argc, char *argv[]) {
	os = new OS_JavaScript();

	// We must override main when testing is enabled
	TEST_MAIN_OVERRIDE

	Main::setup(argv[0], argc - 1, &argv[1]);

	// Ease up compatibility.
	ResourceLoader::set_abort_on_missing_resources(false);

	Main::start();
	os->get_main_loop()->initialize();
#ifdef TOOLS_ENABLED
	if (Main::is_project_manager() && FileAccess::exists("/tmp/preload.zip")) {
		PackedStringArray ps;
		ps.push_back("/tmp/preload.zip");
		os->get_main_loop()->emit_signal(SNAME("files_dropped"), ps, -1);
	}
#endif
	emscripten_set_main_loop(main_loop_callback, -1, false);
	// Immediately run the first iteration.
	// We are inside an animation frame, we want to immediately draw on the newly setup canvas.
	main_loop_callback();

	return 0;
}
<commit_msg>HTML5: Fix build after #52742<commit_after>/*************************************************************************/
/*  javascript_main.cpp                                                  */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 Juan Linietsky, Ariel Manzur.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* 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 "core/config/engine.h"
#include "core/io/resource_loader.h"
#include "main/main.h"
#include "platform/javascript/display_server_javascript.h"
#include "platform/javascript/os_javascript.h"

#include <emscripten/emscripten.h>
#include <stdlib.h>

#include "godot_js.h"

static OS_JavaScript *os = nullptr;
static uint64_t target_ticks = 0;

void exit_callback() {
	emscripten_cancel_main_loop(); // After this, we can exit!
	Main::cleanup();
	int exit_code = OS_JavaScript::get_singleton()->get_exit_code();
	memdelete(os);
	os = nullptr;
	emscripten_force_exit(exit_code); // No matter that we call cancel_main_loop, regular "exit" will not work, forcing.
}

void cleanup_after_sync() {
	emscripten_set_main_loop(exit_callback, -1, false);
}

void main_loop_callback() {
	uint64_t current_ticks = os->get_ticks_usec();

	bool force_draw = DisplayServerJavaScript::get_singleton()->check_size_force_redraw();
	if (force_draw) {
		Main::force_redraw();
	} else if (current_ticks < target_ticks) {
		return; // Skip frame.
	}

	int target_fps = Engine::get_singleton()->get_target_fps();
	if (target_fps > 0) {
		if (current_ticks - target_ticks > 1000000) {
			// When the window loses focus, we stop getting updates and accumulate delay.
			// For this reason, if the difference is too big, we reset target ticks to the current ticks.
			target_ticks = current_ticks;
		}
		target_ticks += (uint64_t)(1000000 / target_fps);
	}
	if (os->main_loop_iterate()) {
		emscripten_cancel_main_loop(); // Cancel current loop and wait for cleanup_after_sync.
		godot_js_os_finish_async(cleanup_after_sync);
	}
}

/// When calling main, it is assumed FS is setup and synced.
extern EMSCRIPTEN_KEEPALIVE int godot_js_main(int argc, char *argv[]) {
	os = new OS_JavaScript();

	// We must override main when testing is enabled
	TEST_MAIN_OVERRIDE

	Main::setup(argv[0], argc - 1, &argv[1]);

	// Ease up compatibility.
	ResourceLoader::set_abort_on_missing_resources(false);

	Main::start();
	os->get_main_loop()->initialize();
#ifdef TOOLS_ENABLED
	if (Engine::get_singleton()->is_project_manager_hint() && FileAccess::exists("/tmp/preload.zip")) {
		PackedStringArray ps;
		ps.push_back("/tmp/preload.zip");
		os->get_main_loop()->emit_signal(SNAME("files_dropped"), ps, -1);
	}
#endif
	emscripten_set_main_loop(main_loop_callback, -1, false);
	// Immediately run the first iteration.
	// We are inside an animation frame, we want to immediately draw on the newly setup canvas.
	main_loop_callback();

	return 0;
}
<|endoftext|>


<commit_before>
#pragma once

#include <list>
#include <memory>
#include <vector>

#include "base/disjoint_sets.hpp"
#include "ksp_plugin/celestial.hpp"
#include "ksp_plugin/flight_plan.hpp"
#include "ksp_plugin/part.hpp"
#include "ksp_plugin/pile_up.hpp"
#include "ksp_plugin/vessel_subsets.hpp"
#include "physics/discrete_trajectory.hpp"
#include "physics/ephemeris.hpp"
#include "physics/massless_body.hpp"
#include "quantities/named_quantities.hpp"
#include "serialization/ksp_plugin.pb.h"

namespace principia {
namespace ksp_plugin {
namespace internal_vessel {

using base::not_null;
using base::Subset;
using geometry::Instant;
using geometry::Vector;
using physics::DegreesOfFreedom;
using physics::DiscreteTrajectory;
using physics::Ephemeris;
using physics::MasslessBody;
using quantities::Force;
using quantities::GravitationalParameter;
using quantities::Mass;

// Represents a KSP |Vessel|.
class Vessel {
 public:
  using Manœuvres =
      std::vector<
          not_null<std::unique_ptr<Manœuvre<Barycentric, Navigation> const>>>;

  Vessel(Vessel const&) = delete;
  Vessel(Vessel&&) = delete;
  Vessel& operator=(Vessel const&) = delete;
  Vessel& operator=(Vessel&&) = delete;

  // |CHECK|s that |*this| is not piled up.
  virtual ~Vessel();

  // Constructs a vessel whose parent is initially |*parent|.  No transfer of
  // ownership.
  Vessel(not_null<Celestial const*> parent,
         not_null<Ephemeris<Barycentric>*> ephemeris,
         Ephemeris<Barycentric>::FixedStepParameters const&
             history_fixed_step_parameters,
         Ephemeris<Barycentric>::AdaptiveStepParameters const&
             prolongation_adaptive_step_parameters,
         Ephemeris<Barycentric>::AdaptiveStepParameters const&
             prediction_adaptive_step_parameters);

  // Returns the body for this vessel.
  virtual not_null<MasslessBody const*> body() const;

  // True if, and only if, |prolongation_| is not null, i.e., if either
  // |CreateProlongation| or |CreateHistoryAndForkProlongation| was called at
  // some point.
  virtual bool is_initialized() const;

  virtual not_null<Celestial const*> parent() const;
  virtual void set_parent(not_null<Celestial const*> parent);

  // These three functions require |is_initialized()|.
  virtual DiscreteTrajectory<Barycentric> const& history() const;
  virtual DiscreteTrajectory<Barycentric> const& prolongation() const;
  virtual DiscreteTrajectory<Barycentric> const& prediction() const;

  // Requires |has_flight_plan()|.
  virtual FlightPlan& flight_plan() const;
  virtual bool has_flight_plan() const;

  // A vessel that was in the physics since the last time its history advanced
  // (which with the time when its prolongation was reset).  For such a vessel,
  // the prolongation, not the history, is authoritative.
  virtual void set_dirty();
  virtual bool is_dirty() const;

  virtual void set_prediction_adaptive_step_parameters(
      Ephemeris<Barycentric>::AdaptiveStepParameters const&
          prediction_adaptive_step_parameters);
  virtual Ephemeris<Barycentric>::AdaptiveStepParameters const&
      prediction_adaptive_step_parameters() const;

  // Creates a |history_| for this vessel and appends a point with the
  // given |time| and |degrees_of_freedom|, then forks a |prolongation_| at
  // |time|.  Nulls |owned_prolongation_|.  The vessel must not satisfy
  // |is_initialized()|.  The vessel |is_initialized()| after the call.
  virtual void CreateHistoryAndForkProlongation(
      Instant const& time,
      DegreesOfFreedom<Barycentric> const& degrees_of_freedom);

  // Advances time for a vessel not in the physics bubble.  This may clean the
  // vessel.
  virtual void AdvanceTimeNotInBubble(Instant const& time);

  // Advances time for a vessel in the physics bubble.  This dirties the vessel.
  virtual void AdvanceTimeInBubble(
      Instant const& time,
      DegreesOfFreedom<Barycentric> const& degrees_of_freedom);

  // Forgets the trajectories and flight plan before |time|.  This may delete
  // the flight plan.
  virtual void ForgetBefore(Instant const& time);

  // Creates a |flight_plan_| at the end of history using the given parameters.
  // Deletes any pre-existing predictions.
  virtual void CreateFlightPlan(
      Instant const& final_time,
      Mass const& initial_mass,
      Ephemeris<Barycentric>::AdaptiveStepParameters const&
          flight_plan_adaptive_step_parameters);

  // Deletes the |flight_plan_|.  Performs no action unless |has_flight_plan()|.
  virtual void DeleteFlightPlan();

  virtual void UpdatePrediction(Instant const& last_time);

  virtual void AppendToPsychohistory(
      Instant const& time,
      DegreesOfFreedom<Barycentric> const& degrees_of_freedom,
      bool authoritative);

  virtual DiscreteTrajectory<Barycentric> const& psychohistory() const;
  virtual bool psychohistory_is_authoritative() const;

  // The vessel must satisfy |is_initialized()|.
  virtual void WriteToMessage(not_null<serialization::Vessel*> message) const;
  static not_null<std::unique_ptr<Vessel>> ReadFromMessage(
      serialization::Vessel const& message,
      not_null<Ephemeris<Barycentric>*> ephemeris,
      not_null<Celestial const*> parent);

 protected:
  // For mocking.
  Vessel();

 private:
  void AdvanceHistoryIfNeeded(Instant const& time);
  void FlowHistory(Instant const& time);
  void FlowProlongation(Instant const& time);
  void FlowPrediction(Instant const& time);

  MasslessBody const body_;
  Ephemeris<Barycentric>::FixedStepParameters const
      history_fixed_step_parameters_;
  Ephemeris<Barycentric>::AdaptiveStepParameters const
      prolongation_adaptive_step_parameters_;
  Ephemeris<Barycentric>::AdaptiveStepParameters
      prediction_adaptive_step_parameters_;
  // The parent body for the 2-body approximation. Not owning.
  not_null<Celestial const*> parent_;
  not_null<Ephemeris<Barycentric>*> const ephemeris_;

  // The past and present trajectory of the body. It ends at |HistoryTime()|
  // unless |*this| was created after |HistoryTime()|, in which case it ends
  // at |current_time_|.  It is advanced with a constant time step.
  std::unique_ptr<DiscreteTrajectory<Barycentric>> history_;

  // The new implementation of history, also encompasses the prolongation.
  DiscreteTrajectory<Barycentric> psychohistory_;
  bool psychohistory_is_authoritative_;

  // A child trajectory of |*history_|. It is forked at |history_->last_time()|
  // and continues until |current_time_|. It is computed with a non-constant
  // timestep, which breaks symplecticity.
  DiscreteTrajectory<Barycentric>* prolongation_ = nullptr;

  // Child trajectory of |*history_|.
  DiscreteTrajectory<Barycentric>* prediction_ = nullptr;

  std::unique_ptr<FlightPlan> flight_plan_;
  bool is_dirty_ = false;

  // We will use union-find algorithms on |Vessel|s.
  not_null<std::unique_ptr<Subset<Vessel>::Node>> const subset_node_;
  friend class Subset<Vessel>::Node;
};

// Factories for use by the clients and the compatibility code.
Ephemeris<Barycentric>::FixedStepParameters DefaultHistoryParameters();
Ephemeris<Barycentric>::AdaptiveStepParameters DefaultProlongationParameters();
Ephemeris<Barycentric>::AdaptiveStepParameters DefaultPredictionParameters();

}  // namespace internal_vessel

using internal_vessel::DefaultHistoryParameters;
using internal_vessel::DefaultPredictionParameters;
using internal_vessel::DefaultProlongationParameters;
using internal_vessel::Vessel;

}  // namespace ksp_plugin

namespace base {

template<>
inline not_null<Subset<ksp_plugin::Vessel>::Node*>
Subset<ksp_plugin::Vessel>::Node::Get(ksp_plugin::Vessel& element) {
  return element.subset_node_.get();
}

}  // namespace base
}  // namespace principia
<commit_msg>cleanup Vessel<commit_after>
#pragma once

#include <list>
#include <memory>
#include <vector>

#include "base/disjoint_sets.hpp"
#include "ksp_plugin/celestial.hpp"
#include "ksp_plugin/flight_plan.hpp"
#include "ksp_plugin/part.hpp"
#include "ksp_plugin/pile_up.hpp"
#include "ksp_plugin/vessel_subsets.hpp"
#include "physics/discrete_trajectory.hpp"
#include "physics/ephemeris.hpp"
#include "physics/massless_body.hpp"
#include "quantities/named_quantities.hpp"
#include "serialization/ksp_plugin.pb.h"

namespace principia {
namespace ksp_plugin {
namespace internal_vessel {

using base::not_null;
using base::Subset;
using geometry::Instant;
using geometry::Vector;
using physics::DegreesOfFreedom;
using physics::DiscreteTrajectory;
using physics::Ephemeris;
using physics::MasslessBody;
using quantities::Force;
using quantities::GravitationalParameter;
using quantities::Mass;

// Represents a KSP |Vessel|.
class Vessel {
 public:
  using Manœuvres =
      std::vector<
          not_null<std::unique_ptr<Manœuvre<Barycentric, Navigation> const>>>;

  Vessel(Vessel const&) = delete;
  Vessel(Vessel&&) = delete;
  Vessel& operator=(Vessel const&) = delete;
  Vessel& operator=(Vessel&&) = delete;

  // |CHECK|s that |*this| is not piled up.
  virtual ~Vessel();

  // Constructs a vessel whose parent is initially |*parent|.  No transfer of
  // ownership.
  Vessel(not_null<Celestial const*> parent,
         not_null<Ephemeris<Barycentric>*> ephemeris,
         Ephemeris<Barycentric>::FixedStepParameters const&
             history_fixed_step_parameters,
         Ephemeris<Barycentric>::AdaptiveStepParameters const&
             prolongation_adaptive_step_parameters,
         Ephemeris<Barycentric>::AdaptiveStepParameters const&
             prediction_adaptive_step_parameters);

  // Returns the body for this vessel.
  virtual not_null<MasslessBody const*> body() const;

  virtual not_null<Celestial const*> parent() const;
  virtual void set_parent(not_null<Celestial const*> parent);

  virtual void clear_parts();
  virtual void add_part(not_null<Part const*> part);

  virtual DiscreteTrajectory<Barycentric> const& prediction() const;

  // Requires |has_flight_plan()|.
  virtual FlightPlan& flight_plan() const;
  virtual bool has_flight_plan() const;

  virtual void AdvanceTime(Instant const& time);

  // Forgets the trajectories and flight plan before |time|.  This may delete
  // the flight plan.
  virtual void ForgetBefore(Instant const& time);

  // Creates a |flight_plan_| at the end of history using the given parameters.
  // Deletes any pre-existing predictions.
  virtual void CreateFlightPlan(
      Instant const& final_time,
      Mass const& initial_mass,
      Ephemeris<Barycentric>::AdaptiveStepParameters const&
          flight_plan_adaptive_step_parameters);

  // Deletes the |flight_plan_|.  Performs no action unless |has_flight_plan()|.
  virtual void DeleteFlightPlan();

  virtual void UpdatePrediction(Instant const& last_time);

  virtual void AppendToPsychohistory(
      Instant const& time,
      DegreesOfFreedom<Barycentric> const& degrees_of_freedom,
      bool authoritative);

  virtual DiscreteTrajectory<Barycentric> const& psychohistory() const;
  virtual bool psychohistory_is_authoritative() const;

  // The vessel must satisfy |is_initialized()|.
  virtual void WriteToMessage(not_null<serialization::Vessel*> message) const;
  static not_null<std::unique_ptr<Vessel>> ReadFromMessage(
      serialization::Vessel const& message,
      not_null<Ephemeris<Barycentric>*> ephemeris,
      not_null<Celestial const*> parent);

 protected:
  // For mocking.
  Vessel();

 private:
  void AdvanceHistoryIfNeeded(Instant const& time);
  void FlowHistory(Instant const& time);
  void FlowProlongation(Instant const& time);
  void FlowPrediction(Instant const& time);

  MasslessBody const body_;
  Ephemeris<Barycentric>::FixedStepParameters const
      history_fixed_step_parameters_;
  Ephemeris<Barycentric>::AdaptiveStepParameters const
      prolongation_adaptive_step_parameters_;
  Ephemeris<Barycentric>::AdaptiveStepParameters
      prediction_adaptive_step_parameters_;
  // The parent body for the 2-body approximation. Not owning.
  not_null<Celestial const*> parent_;
  not_null<Ephemeris<Barycentric>*> const ephemeris_;

  std::vector<not_null<Part const*>> parts_;

  // The new implementation of history, also encompasses the prolongation.
  DiscreteTrajectory<Barycentric> psychohistory_;
  bool psychohistory_is_authoritative_;

  // Child trajectory of |*history_|.
  DiscreteTrajectory<Barycentric>* prediction_ = nullptr;

  std::unique_ptr<FlightPlan> flight_plan_;

  // We will use union-find algorithms on |Vessel|s.
  not_null<std::unique_ptr<Subset<Vessel>::Node>> const subset_node_;
  friend class Subset<Vessel>::Node;
};

// Factories for use by the clients and the compatibility code.
Ephemeris<Barycentric>::FixedStepParameters DefaultHistoryParameters();
Ephemeris<Barycentric>::AdaptiveStepParameters DefaultProlongationParameters();
Ephemeris<Barycentric>::AdaptiveStepParameters DefaultPredictionParameters();

}  // namespace internal_vessel

using internal_vessel::DefaultHistoryParameters;
using internal_vessel::DefaultPredictionParameters;
using internal_vessel::DefaultProlongationParameters;
using internal_vessel::Vessel;

}  // namespace ksp_plugin

namespace base {

template<>
inline not_null<Subset<ksp_plugin::Vessel>::Node*>
Subset<ksp_plugin::Vessel>::Node::Get(ksp_plugin::Vessel& element) {
  return element.subset_node_.get();
}

}  // namespace base
}  // namespace principia
<|endoftext|>


<commit_before><commit_msg>Solved #378<commit_after><|endoftext|>


<commit_before><commit_msg>Companions work in combat<commit_after><|endoftext|>


<commit_before>/*
* This file is part of buteo-sync-plugins package
*
* Copyright (C) 2013 Jolla Ltd. and/or its subsidiary(-ies).
*
* Author: Sateesh Kavuri <sateesh.kavuri@gmail.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "PluginServiceObj.h"
#include <SyncResults.h>
#include <ProfileManager.h>
#include <LogMacros.h>
#include <SyncCommonDefs.h>

using namespace Buteo;

PluginServiceObj::PluginServiceObj( QString aProfileName, QString aPluginName, QObject *parent) :
    QObject(parent), iPlugin(0), iProfileName(aProfileName), iPluginName(aPluginName)
{
}

PluginServiceObj::~PluginServiceObj()
{
    if( iPlugin ) {
        delete iPlugin;
        iPlugin = 0;
    }
}

bool PluginServiceObj::init()
{
    FUNCTION_CALL_TRACE;

    ProfileManager pm;
#ifdef CLIENT_PLUGIN
    SyncProfile *syncProfile = pm.syncProfile( iProfileName );
    if( !syncProfile ) {
        LOG_WARNING( "Profile " << iProfileName << " does not exist" );
        return false;
    }

    // Create the plugin (client or server)
    iPlugin = new CLASSNAME( iPluginName, *syncProfile, &iPluginCb );
#else
    Profile *profile = pm.profile( iProfileName, Profile::TYPE_SERVER );
    if( !profile ) {
        LOG_WARNING( "Profile " << iProfileName << " does not exist" );
        return false;
    }

    // Create the plugin (client or server)
    iPlugin = new CLASSNAME( iPluginName, *profile, &iPluginCb );

    // Server signals
    QObject::connect(iPlugin, SIGNAL(newSession(const QString&)),
                     this, SIGNAL(newSession(const QString&)));
#endif
    // Chain the signals
    QObject::connect(iPlugin, SIGNAL(transferProgress(const QString&, int, int, const QString, int)),
                     this, SIGNAL(transferProgress(const QString&, int, int, const QString&, int)));
    QObject::connect(iPlugin, SIGNAL(error(const QString&, const QStrnig&, int)),
                     this, SIGNAL(error(const QString&, const QString&, int)));
    QObject::connect(iPlugin, SIGNAL(success(const QString&, const QString&)),
                     this, SIGNAL(success(const QString&, const QString&)));
    QObject::connect(iPlugin, SIGNAL(accquiredStorage(const QString&)),
                     this, SIGNAL(accquiredStorage(const QString&)));
    QObject::connect(iPlugin, SIGNAL(syncProgressDetail(const QString&, int)),
                     this, SIGNAL(syncProgressDetail(const QString&, int)));

    return iPlugin->init();
}

bool PluginServiceObj::uninit()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->uninit();
}

void PluginServiceObj::abortSync(uchar aStatus)
{
    FUNCTION_CALL_TRACE;

    iPlugin->abortSync( static_cast<Sync::SyncStatus>(aStatus) );
}

bool PluginServiceObj::cleanUp()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->cleanUp();
}

void PluginServiceObj::connectivityStateChanged(int aType, bool aState)
{
    FUNCTION_CALL_TRACE;

    iPlugin->connectivityStateChanged( static_cast<Sync::ConnectivityType>(aType), aState );
}

QString PluginServiceObj::getSyncResults()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->getSyncResults().toString();
}

#ifdef CLIENT_PLUGIN
bool PluginServiceObj::startSync()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->startSync();
}

#else
void PluginServiceObj::resume()
{
    FUNCTION_CALL_TRACE;

    iPlugin->resume();
}

bool PluginServiceObj::startListen()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->startListen();
}

void PluginServiceObj::stopListen()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->stopListen();
}

void PluginServiceObj::suspend()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->suspend();
}
#endif
<commit_msg>Fixed typo in connect of signals between plugin and dbus adaptor<commit_after>/*
* This file is part of buteo-sync-plugins package
*
* Copyright (C) 2013 Jolla Ltd. and/or its subsidiary(-ies).
*
* Author: Sateesh Kavuri <sateesh.kavuri@gmail.com>
*
* 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., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA
*/
#include "PluginServiceObj.h"
#include <SyncResults.h>
#include <ProfileManager.h>
#include <LogMacros.h>
#include <SyncCommonDefs.h>

using namespace Buteo;

PluginServiceObj::PluginServiceObj( QString aProfileName, QString aPluginName, QObject *parent) :
    QObject(parent), iPlugin(0), iProfileName(aProfileName), iPluginName(aPluginName)
{
}

PluginServiceObj::~PluginServiceObj()
{
    if( iPlugin ) {
        delete iPlugin;
        iPlugin = 0;
    }
}

bool PluginServiceObj::init()
{
    FUNCTION_CALL_TRACE;

    ProfileManager pm;
#ifdef CLIENT_PLUGIN
    SyncProfile *syncProfile = pm.syncProfile( iProfileName );
    if( !syncProfile ) {
        LOG_WARNING( "Profile " << iProfileName << " does not exist" );
        return false;
    }

    // Create the plugin (client or server)
    iPlugin = new CLASSNAME( iPluginName, *syncProfile, &iPluginCb );
#else
    Profile *profile = pm.profile( iProfileName, Profile::TYPE_SERVER );
    if( !profile ) {
        LOG_WARNING( "Profile " << iProfileName << " does not exist" );
        return false;
    }

    // Create the plugin (client or server)
    iPlugin = new CLASSNAME( iPluginName, *profile, &iPluginCb );

    // Server signals
    QObject::connect(iPlugin, SIGNAL(newSession(const QString&)),
                     this, SIGNAL(newSession(const QString&)));
#endif
    // Chain the signals
    QObject::connect(iPlugin, SIGNAL(transferProgress(const QString&, int, int, const QString&, int)),
                     this, SIGNAL(transferProgress(const QString&, int, int, const QString&, int)));
    QObject::connect(iPlugin, SIGNAL(error(const QString&, const QString&, int)),
                     this, SIGNAL(error(const QString&, const QString&, int)));
    QObject::connect(iPlugin, SIGNAL(success(const QString&, const QString&)),
                     this, SIGNAL(success(const QString&, const QString&)));
    QObject::connect(iPlugin, SIGNAL(accquiredStorage(const QString&)),
                     this, SIGNAL(accquiredStorage(const QString&)));
    QObject::connect(iPlugin, SIGNAL(syncProgressDetail(const QString&, int)),
                     this, SIGNAL(syncProgressDetail(const QString&, int)));

    return iPlugin->init();
}

bool PluginServiceObj::uninit()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->uninit();
}

void PluginServiceObj::abortSync(uchar aStatus)
{
    FUNCTION_CALL_TRACE;

    iPlugin->abortSync( static_cast<Sync::SyncStatus>(aStatus) );
}

bool PluginServiceObj::cleanUp()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->cleanUp();
}

void PluginServiceObj::connectivityStateChanged(int aType, bool aState)
{
    FUNCTION_CALL_TRACE;

    iPlugin->connectivityStateChanged( static_cast<Sync::ConnectivityType>(aType), aState );
}

QString PluginServiceObj::getSyncResults()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->getSyncResults().toString();
}

#ifdef CLIENT_PLUGIN
bool PluginServiceObj::startSync()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->startSync();
}

#else
void PluginServiceObj::resume()
{
    FUNCTION_CALL_TRACE;

    iPlugin->resume();
}

bool PluginServiceObj::startListen()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->startListen();
}

void PluginServiceObj::stopListen()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->stopListen();
}

void PluginServiceObj::suspend()
{
    FUNCTION_CALL_TRACE;

    return iPlugin->suspend();
}
#endif
<|endoftext|>


<commit_before>// SAMPLE_PLUGIN.cpp : Defines the entry point for the DLL application.
//

#include "bzfsAPI.h"
#include "plugin_utils.h"

class SAMPLE_PLUGIN : public bz_Plugin
{
	virtual const char* Name (){return "SAMPLE PLUGIN";}
	virtual void Init ( const char* config);

	virtual void Event ( bz_EventData *eventData ){return;}

};

BZ_PLUGIN(SAMPLE_PLUGIN)

void SAMPLE_PLUGIN::Init ( const char* /*commandLine*/ )
{
  bz_debugMessage(4,"SAMPLE_PLUGIN plugin loaded");

  // init events here with Register();
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<commit_msg>Unused parameter breaks the --enable-debug build on linux<commit_after>// SAMPLE_PLUGIN.cpp : Defines the entry point for the DLL application.
//

#include "bzfsAPI.h"
#include "plugin_utils.h"

class SAMPLE_PLUGIN : public bz_Plugin
{
  virtual const char* Name (){return "SAMPLE PLUGIN";}
  virtual void Init ( const char* config);

  virtual void Event ( bz_EventData * /* eventData */ ){return;}
};

BZ_PLUGIN(SAMPLE_PLUGIN)

void SAMPLE_PLUGIN::Init ( const char* /*commandLine*/ )
{
  bz_debugMessage(4,"SAMPLE_PLUGIN plugin loaded");

  // init events here with Register();
}
// Local Variables: ***
// mode:C++ ***
// tab-width: 8 ***
// c-basic-offset: 2 ***
// indent-tabs-mode: t ***
// End: ***
// ex: shiftwidth=2 tabstop=8

<|endoftext|>


<commit_before>/**
 * @file edge.cpp
 * @brief Simple test for OpenCV
 * @author Denis Deryugin <deryugin.denis@gmail.com>
 * @version
 * @date 03.06.2019
 */

#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>

#include <drivers/video/fb.h>

using namespace cv;
using namespace std;

static void help(void) {
	printf("\nThis sample demonstrates Canny edge detection\n"
			"Call:\n"
			"	./edge [image [threshold]] \n\n");
}

static const char* keys = {
	"{help h||}"
	"{@image        | \"fruits.png\" | source image   }"
	"{@repeat |1     | number}"
};

int main(int argc, const char** argv) {
	int edgeThresh = 2;
	Mat image, gray, edge, cedge;

	struct fb_info *fbi = fb_lookup(0);

	CommandLineParser parser(argc, argv, keys);
	if (parser.has("help"))  {
		help();
		return 0;
	}

	edgeThresh = parser.get<int>(1);
	string filename = parser.get<String>("@image");
	image = imread(filename, 1);
	if(image.empty()) {
		printf("Cannot read image file: %s\n", filename.c_str());
		help();
		return -1;
	}

	cedge.create(image.size(), image.type());
	cvtColor(image, gray, COLOR_BGR2GRAY);

	blur(gray, edge, Size(3,3));
	Canny(edge, edge, edgeThresh, edgeThresh*3, 3);
	cedge = Scalar::all(0);

	image.copyTo(cedge, edge);

	printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel);
	printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh);

	for (int i = 0; i < cedge.cols; i++) {
		for (int j = 0; j < cedge.rows; j++) {
			Vec3b intensity = cedge.at<Vec3b>(j, i);
			unsigned rgb888	=
				0xFF000000 |
				intensity.val[0] |
				((intensity.val[1]) << 8) |
				((intensity.val[2]) << 16);

			((uint32_t *) fbi->screen_base)[fbi->var.xres * j + i] = rgb888;
		}
	}

	return 0;
}
<commit_msg>more obvious loop variable names<commit_after>/**
 * @file edge.cpp
 * @brief Simple test for OpenCV
 * @author Denis Deryugin <deryugin.denis@gmail.com>
 * @version
 * @date 03.06.2019
 */

#include "opencv2/core/utility.hpp"
#include "opencv2/imgproc.hpp"
#include "opencv2/imgcodecs.hpp"
#include "opencv2/highgui.hpp"
#include <stdio.h>

#include <drivers/video/fb.h>

using namespace cv;
using namespace std;

static void help(void) {
	printf("\nThis sample demonstrates Canny edge detection\n"
			"Call:\n"
			"	./edge [image [threshold]] \n\n");
}

static const char* keys = {
	"{help h||}"
	"{@image        | \"fruits.png\" | source image   }"
	"{@repeat |1     | number}"
};

int main(int argc, const char** argv) {
	int edgeThresh = 2;
	Mat image, gray, edge, cedge;

	struct fb_info *fbi = fb_lookup(0);

	CommandLineParser parser(argc, argv, keys);
	if (parser.has("help"))  {
		help();
		return 0;
	}

	edgeThresh = parser.get<int>(1);
	string filename = parser.get<String>("@image");
	image = imread(filename, 1);
	if(image.empty()) {
		printf("Cannot read image file: %s\n", filename.c_str());
		help();
		return -1;
	}

	cedge.create(image.size(), image.type());
	cvtColor(image, gray, COLOR_BGR2GRAY);

	blur(gray, edge, Size(3,3));
	Canny(edge, edge, edgeThresh, edgeThresh*3, 3);
	cedge = Scalar::all(0);

	image.copyTo(cedge, edge);

	printf("Framebuffer: %dx%d %dbpp\n", fbi->var.xres, fbi->var.yres, fbi->var.bits_per_pixel);
	printf("Image: %dx%d; Threshold=%d\n", cedge.cols, cedge.rows, edgeThresh);

	for (int x = 0; x < cedge.cols; x++) {
		for (int y = 0; y < cedge.rows; y++) {
			Vec3b intensity = cedge.at<Vec3b>(y, x);
			unsigned rgb888	=
				0xFF000000 |
				intensity.val[0] |
				((intensity.val[1]) << 8) |
				((intensity.val[2]) << 16);

			((uint32_t *) fbi->screen_base)[fbi->var.xres * y + x] = rgb888;
		}
	}

	return 0;
}
<|endoftext|>


<commit_before>// Copyright 2019 Google LLC
//
// 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
//
//      https://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 "iree/base/target_platform.h"

#if defined(IREE_PLATFORM_ANDROID) || defined(IREE_PLATFORM_APPLE) || \
    defined(IREE_PLATFORM_LINUX)

#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <cstdio>
#include <cstdlib>

#include "absl/strings/str_cat.h"
#include "iree/base/file_io.h"
#include "iree/base/file_path.h"
#include "iree/base/status.h"
#include "iree/base/tracing.h"

namespace iree {
namespace file_io {

Status FileExists(const std::string& path) {
  IREE_TRACE_SCOPE0("file_io::FileExists");
  struct stat stat_buf;
  return stat(path.c_str(), &stat_buf) == 0
             ? OkStatus()
             : NotFoundErrorBuilder(IREE_LOC) << "'" << path << "'";
}

StatusOr<std::string> GetFileContents(const std::string& path) {
  IREE_TRACE_SCOPE0("file_io::GetFileContents");
  std::unique_ptr<FILE, void (*)(FILE*)> file = {std::fopen(path.c_str(), "r"),
                                                 +[](FILE* file) {
                                                   if (file) fclose(file);
                                                 }};
  if (file == nullptr) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to open file '" << path << "'";
  }
  if (std::fseek(file.get(), 0, SEEK_END) == -1) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to seek file '" << path << "'";
  }
  size_t file_size = std::ftell(file.get());
  if (file_size == -1L) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to read file length for '" << path << "'";
  }
  if (std::fseek(file.get(), 0, SEEK_SET) == -1) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to seek back in file '" << path << "'";
  }
  std::string contents;
  contents.resize(file_size);
  if (std::fread(const_cast<char*>(contents.data()), file_size, 1,
                 file.get()) != 1) {
    return UnavailableErrorBuilder(IREE_LOC)
           << "Unable to read entire file contents of '" << path << "'";
  }
  return contents;
}

Status SetFileContents(const std::string& path, absl::string_view content) {
  IREE_TRACE_SCOPE0("file_io::SetFileContents");
  std::unique_ptr<FILE, void (*)(FILE*)> file = {std::fopen(path.c_str(), "wb"),
                                                 +[](FILE* file) {
                                                   if (file) fclose(file);
                                                 }};
  if (file == nullptr) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to open file '" << path << "'";
  }
  if (std::fwrite(const_cast<char*>(content.data()), content.size(), 1,
                  file.get()) != 1) {
    return UnavailableErrorBuilder(IREE_LOC)
           << "Unable to write entire file contents of '" << path << "'";
  }
  return OkStatus();
}

Status DeleteFile(const std::string& path) {
  IREE_TRACE_SCOPE0("file_io::DeleteFile");
  if (::remove(path.c_str()) == -1) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to delete file '" << path << "'";
  }
  return OkStatus();
}

Status MoveFile(const std::string& source_path,
                const std::string& destination_path) {
  IREE_TRACE_SCOPE0("file_io::MoveFile");
  if (::rename(source_path.c_str(), destination_path.c_str()) == -1) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to rename file '" << source_path << "' to '"
           << destination_path << "'";
  }
  return OkStatus();
}

std::string GetTempPath() {
  IREE_TRACE_SCOPE0("file_io::GetTempPath");

  // TEST_TMPDIR will point to a writeable temp path when running bazel tests.
  char* test_tmpdir = getenv("TEST_TMPDIR");
  if (test_tmpdir) {
    return test_tmpdir;
  }

  char* tmpdir = getenv("TMPDIR");
  if (tmpdir) {
    return tmpdir;
  }

  return "/tmp";
}

StatusOr<std::string> GetTempFile(absl::string_view base_name) {
  IREE_TRACE_SCOPE0("file_io::GetTempFile");

  std::string temp_path = GetTempPath();
  std::string template_path =
      file_path::JoinPaths(temp_path, base_name) + "XXXXXX";

  if (::mkstemp(&template_path[0]) != -1) {
    return template_path;  // Should have been modified by mkstemp.
  } else {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to create temp file with template '" << template_path
           << "'";
  }
}

}  // namespace file_io
}  // namespace iree

#endif  // IREE_PLATFORM_*
<commit_msg>support running as root on android. (#4013)<commit_after>// Copyright 2019 Google LLC
//
// 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
//
//      https://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 "iree/base/target_platform.h"

#if defined(IREE_PLATFORM_ANDROID) || defined(IREE_PLATFORM_APPLE) || \
    defined(IREE_PLATFORM_LINUX)

#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

#include <cstdio>
#include <cstdlib>

#include "absl/strings/str_cat.h"
#include "iree/base/file_io.h"
#include "iree/base/file_path.h"
#include "iree/base/status.h"
#include "iree/base/tracing.h"

namespace iree {
namespace file_io {

Status FileExists(const std::string& path) {
  IREE_TRACE_SCOPE0("file_io::FileExists");
  struct stat stat_buf;
  return stat(path.c_str(), &stat_buf) == 0
             ? OkStatus()
             : NotFoundErrorBuilder(IREE_LOC) << "'" << path << "'";
}

StatusOr<std::string> GetFileContents(const std::string& path) {
  IREE_TRACE_SCOPE0("file_io::GetFileContents");
  std::unique_ptr<FILE, void (*)(FILE*)> file = {std::fopen(path.c_str(), "r"),
                                                 +[](FILE* file) {
                                                   if (file) fclose(file);
                                                 }};
  if (file == nullptr) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to open file '" << path << "'";
  }
  if (std::fseek(file.get(), 0, SEEK_END) == -1) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to seek file '" << path << "'";
  }
  size_t file_size = std::ftell(file.get());
  if (file_size == -1L) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to read file length for '" << path << "'";
  }
  if (std::fseek(file.get(), 0, SEEK_SET) == -1) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to seek back in file '" << path << "'";
  }
  std::string contents;
  contents.resize(file_size);
  if (std::fread(const_cast<char*>(contents.data()), file_size, 1,
                 file.get()) != 1) {
    return UnavailableErrorBuilder(IREE_LOC)
           << "Unable to read entire file contents of '" << path << "'";
  }
  return contents;
}

Status SetFileContents(const std::string& path, absl::string_view content) {
  IREE_TRACE_SCOPE0("file_io::SetFileContents");
  std::unique_ptr<FILE, void (*)(FILE*)> file = {std::fopen(path.c_str(), "wb"),
                                                 +[](FILE* file) {
                                                   if (file) fclose(file);
                                                 }};
  if (file == nullptr) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to open file '" << path << "'";
  }
  if (std::fwrite(const_cast<char*>(content.data()), content.size(), 1,
                  file.get()) != 1) {
    return UnavailableErrorBuilder(IREE_LOC)
           << "Unable to write entire file contents of '" << path << "'";
  }
  return OkStatus();
}

Status DeleteFile(const std::string& path) {
  IREE_TRACE_SCOPE0("file_io::DeleteFile");
  if (::remove(path.c_str()) == -1) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to delete file '" << path << "'";
  }
  return OkStatus();
}

Status MoveFile(const std::string& source_path,
                const std::string& destination_path) {
  IREE_TRACE_SCOPE0("file_io::MoveFile");
  if (::rename(source_path.c_str(), destination_path.c_str()) == -1) {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to rename file '" << source_path << "' to '"
           << destination_path << "'";
  }
  return OkStatus();
}

std::string GetTempPath() {
  IREE_TRACE_SCOPE0("file_io::GetTempPath");

  // TEST_TMPDIR will point to a writeable temp path when running bazel tests.
  char* test_tmpdir = getenv("TEST_TMPDIR");
  if (test_tmpdir) {
    return test_tmpdir;
  }

  char* tmpdir = getenv("TMPDIR");
  if (tmpdir) {
    return tmpdir;
  }

#ifdef __ANDROID__
  // Support running Android command-line programs both as regular shell user
  // and as root. For the latter, TMPDIR is not defined by default.
  return "/data/local/tmp";
#else
  return "/tmp";
#endif
}

StatusOr<std::string> GetTempFile(absl::string_view base_name) {
  IREE_TRACE_SCOPE0("file_io::GetTempFile");

  std::string temp_path = GetTempPath();
  std::string template_path =
      file_path::JoinPaths(temp_path, base_name) + "XXXXXX";

  if (::mkstemp(&template_path[0]) != -1) {
    return template_path;  // Should have been modified by mkstemp.
  } else {
    return ErrnoToCanonicalStatusBuilder(errno, IREE_LOC)
           << "Failed to create temp file with template '" << template_path
           << "'";
  }
}

}  // namespace file_io
}  // namespace iree

#endif  // IREE_PLATFORM_*
<|endoftext|>


<commit_before>/*$Id$
 *
 * This source file is a part of the Fresco Project.
 * Copyright (C) 2000 Stefan Seefeld <stefan@fresco.org>
 * http://www.fresco.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */
#include <Prague/Sys/Tracer.hh>
#include <Prague/Sys/Thread.hh>
#include <Fresco/config.hh>
#include <Fresco/Selection.hh>
#include <Berlin/ImplVar.hh>
#include <Berlin/SubjectImpl.hh>
#include <Berlin/RefCountVar.hh>
#include "Choice.hh"

using namespace Prague;
using namespace Fresco;

using namespace Berlin::WidgetKit::Motif;

Choice::Choice(Selection_ptr s, LayoutKit_ptr l, ToolKit_ptr t)
  : ControllerImpl(false),
    my_selection(RefCount_var<Selection>::increment(s)),
    my_layout(RefCount_var<LayoutKit>::increment(l)),
    my_tools(RefCount_var<ToolKit>::increment(t))
{ Trace trace("Choice::Choice");}

Choice::~Choice() { Trace trace("Choice::~Choice");}

Selection_ptr Choice::state()
{
  Trace trace("Choice::state");
  return RefCount_var<Selection>::increment(my_selection);
}

Graphic_ptr Choice::create_focus_frame(Controller_ptr g)
{
  Fresco::ToolKit::FrameSpec none;
  Graphic_var empty = my_tools->frame(g, 20., none, false);
  Fresco::ToolKit::FrameSpec colored;
  Color c = {0., 0., 0., 1.};
  colored.foreground(c);
  Graphic_var black = my_tools->frame(g, 20., colored, false);

  return my_tools->create_switch(black, empty, Fresco::Controller::active, g);
}

ToggleChoice::ToggleChoice(Selection_ptr s,
			   Graphic_ptr inbox,
			   Graphic_ptr outbox,
			   LayoutKit_ptr l,
			   ToolKit_ptr t)
  : Choice(s, l, t),
    my_in_box(Fresco::Graphic::_duplicate(inbox)),
    my_out_box(Fresco::Graphic::_duplicate(outbox))
{}

RefCount_var<Fresco::Graphic> ToggleChoice::create_item(Graphic_ptr g, Tag& t)
{
  Trace trace("ToggleChoice::create_item");

  // Define initial hbox, which is nested inside a toggle-box (no bevel!)
  RefCount_var<Fresco::Graphic> box = my_layout->hbox();
  RefCount_var<Fresco::Controller> toggle_box = my_tools->toggle(box);
  t = my_selection->add(toggle_box);
  append_controller(toggle_box);

  // 'toggle': simply a graphic with bevel dependent upon toggle_box
  Graphic_var toggle = my_tools->create_switch(my_in_box, my_out_box,
					      Fresco::Controller::toggled,
					      toggle_box);

  // now add the toggle button into the button box, along with g
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->valign(RefCount_var<Fresco::Graphic>(my_layout->margin(toggle, 50.)), 0.5)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->hspace(100.)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->valign(g, 0.5)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->hspace(50.)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->hfill()));

  // Add the 'active item' border
  return create_focus_frame(toggle_box);
}

Tag ToggleChoice::append_item(Graphic_ptr g)
{
  Trace trace("ToggleChoice::append_item");
  Tag tag;
  body()->append_graphic(create_item(g, tag));
  return tag;
}

Tag ToggleChoice::prepend_item(Graphic_ptr g)
{
  Trace trace("ToggleChoice::prepend_item");
  Tag tag;
  body()->prepend_graphic(create_item(g, tag));
  return tag;
}

void ToggleChoice::remove_item(Tag t)
{
  Trace trace("ToggleChoice::remove_item");
  my_selection->remove(t);
  Graphic_var box = body();
  box->remove_graphic(t);
}

CheckboxChoice::CheckboxChoice(Selection_ptr s,
			       Graphic_ptr inbox,
			       Graphic_ptr outbox,
			       LayoutKit_ptr l,
			       ToolKit_ptr t)
  : Choice(s, l, t),
    my_in_box(Fresco::Graphic::_duplicate(inbox)),
    my_out_box(Fresco::Graphic::_duplicate(outbox))
{}

RefCount_var<Fresco::Graphic> CheckboxChoice::create_item(Graphic_ptr g, Tag& t)
{
  Trace trace("CheckboxChoice::create_item");

  // Define initial hbox, which is nested inside a toggle-box (no bevel!)
  RefCount_var<Fresco::Graphic> box = my_layout->hbox();
  RefCount_var<Fresco::Controller> toggle_box = my_tools->toggle(box);
  t = my_selection->add(toggle_box);
  append_controller(toggle_box);

  // 'toggle': simply a graphic with bevel dependent upon toggle_box state

  Graphic_var toggle = my_tools->create_switch(my_in_box, my_out_box,
					       Fresco::Controller::toggled,
					       toggle_box);

  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->valign(RefCount_var<Fresco::Graphic>(my_layout->margin(toggle, 50.)), 0.5)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->hspace(100.)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->valign(g, 0.5)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->hspace(50.)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->hfill()));

  // Add the 'active item' border
//   return RefCount_var<Fresco::Graphic>(create_focus_frame(toggle_box));
  return create_focus_frame(toggle_box);
}

Tag CheckboxChoice::append_item(Graphic_ptr g)
{
  Trace trace("CheckboxChoice::append_item");
  Tag tag;
  body()->append_graphic(create_item(g, tag));
  return tag;
}

Tag CheckboxChoice::prepend_item(Graphic_ptr g)
{
  Trace trace("CheckboxChoice::prepend_item");
  Tag tag;
  body()->prepend_graphic(create_item(g, tag));
  return tag;
}

void CheckboxChoice::remove_item(Tag t)
{
  Trace trace("CheckboxChoice::remove_item");
  my_selection->remove(t);
  Graphic_var box = body();
  box->remove_graphic(t);
}

ToolChoice::ToolChoice(Selection_ptr s, LayoutKit_ptr l, ToolKit_ptr t)
  : Choice(s, l, t)
{}

Tag ToolChoice::append_item(Graphic_ptr g)
{
  Trace trace("ToolChoice::append_item");
  RefCount_var<Fresco::Controller> toggle = my_tools->toggle(Fresco::Graphic::_nil());
  Tag tag = my_selection->add(toggle);
  append_controller(toggle);

  Fresco::ToolKit::FrameSpec in, out;
  in.brightness(0.5); in._d(ToolKit::inset);
  Graphic_var inset = my_tools->frame(g, 20., in, true);
  out.brightness(0.5); out._d(ToolKit::outset);
  Graphic_var outset = my_tools->frame(g, 20., out, true);
  Graphic_var frame = my_tools->create_switch(inset, outset,
					      Fresco::Controller::toggled,
					      toggle);
  toggle->body(frame);
  Graphic_var box = body();
  box->append_graphic(toggle);
  return tag;
}

Tag ToolChoice::prepend_item(Graphic_ptr g)
{
  Trace trace("ToolChoice::prepend_item");
  RefCount_var<Fresco::Controller> toggle = my_tools->toggle(Fresco::Graphic::_nil());
  Tag tag = my_selection->add(toggle);
  prepend_controller(toggle);

  Fresco::ToolKit::FrameSpec in, out;
  in.brightness(0.5); in._d(ToolKit::inset);
  Graphic_var inset = my_tools->frame(g, 20., in, true);
  out.brightness(0.5); out._d(ToolKit::outset);
  Graphic_var outset = my_tools->frame(g, 20., out, true);
  Graphic_var frame = my_tools->create_switch(inset, outset,
					      Fresco::Controller::toggled,
					      toggle);
  toggle->body(frame);
  Graphic_var box = body();
  box->prepend_graphic(toggle);
  return tag;
}

void ToolChoice::remove_item(Tag t)
{
  Trace trace("ToolChoice::remove_item");
  my_selection->remove(t);
  Graphic_var box = body();
  box->remove_graphic(t);
}
<commit_msg>Tidy-up to sync layout of Choice widgets - code should now be identical apart from class names - please comment in task80<commit_after>/*$Id$
 *
 * This source file is a part of the Fresco Project.
 * Copyright (C) 2000 Stefan Seefeld <stefan@fresco.org>
 * http://www.fresco.org
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Library General Public
 * License as published by the Free Software Foundation; either
 * version 2 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
 * Library General Public License for more details.
 *
 * You should have received a copy of the GNU Library General Public
 * License along with this library; if not, write to the
 * Free Software Foundation, Inc., 675 Mass Ave, Cambridge,
 * MA 02139, USA.
 */
#include <Prague/Sys/Tracer.hh>
#include <Prague/Sys/Thread.hh>
#include <Fresco/config.hh>
#include <Fresco/Selection.hh>
#include <Berlin/ImplVar.hh>
#include <Berlin/SubjectImpl.hh>
#include <Berlin/RefCountVar.hh>
#include "Choice.hh"

using namespace Prague;
using namespace Fresco;

using namespace Berlin::WidgetKit::Motif;

Choice::Choice(Selection_ptr s, LayoutKit_ptr l, ToolKit_ptr t)
  : ControllerImpl(false),
    my_selection(RefCount_var<Selection>::increment(s)),
    my_layout(RefCount_var<LayoutKit>::increment(l)),
    my_tools(RefCount_var<ToolKit>::increment(t))
{ Trace trace("Choice::Choice");}

Choice::~Choice() { Trace trace("Choice::~Choice");}

Selection_ptr Choice::state()
{
  Trace trace("Choice::state");
  return RefCount_var<Selection>::increment(my_selection);
}

Graphic_ptr Choice::create_focus_frame(Controller_ptr g)
{
  Fresco::ToolKit::FrameSpec none;
  Graphic_var empty = my_tools->frame(g, 20., none, false);
  Fresco::ToolKit::FrameSpec colored;
  Color c = {0., 0., 0., 1.};
  colored.foreground(c);
  Graphic_var black = my_tools->frame(g, 20., colored, false);

  return my_tools->create_switch(black, empty, Fresco::Controller::active, g);
}

ToggleChoice::ToggleChoice(Selection_ptr s,
			   Graphic_ptr inbox,
			   Graphic_ptr outbox,
			   LayoutKit_ptr l,
			   ToolKit_ptr t)
  : Choice(s, l, t),
    my_in_box(Fresco::Graphic::_duplicate(inbox)),
    my_out_box(Fresco::Graphic::_duplicate(outbox))
{}

RefCount_var<Fresco::Graphic> ToggleChoice::create_item(Graphic_ptr g, Tag& t)
{
  Trace trace("ToggleChoice::create_item");

  // Define initial hbox, which is nested inside a toggle-box (no bevel!)
  RefCount_var<Fresco::Graphic> box = my_layout->hbox();
  RefCount_var<Fresco::Controller> toggle_box = my_tools->toggle(box);
  t = my_selection->add(toggle_box);
  append_controller(toggle_box);

  // 'toggle': simply a graphic with bevel dependent upon toggle_box
  Graphic_var toggle = my_tools->create_switch(my_in_box, my_out_box,
					      Fresco::Controller::toggled,
					      toggle_box);

  // now add the toggle button into the button box, along with g
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->valign(RefCount_var<Fresco::Graphic>(my_layout->margin(toggle, 50.)), 0.5)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->hspace(100.)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->valign(g, 0.5)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->hspace(50.)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->hfill()));

  // Add the 'active item' border
  return create_focus_frame(toggle_box);
}

Tag ToggleChoice::append_item(Graphic_ptr g)
{
  Trace trace("ToggleChoice::append_item");
  Tag tag;
  body()->append_graphic(create_item(g, tag));
  return tag;
}

Tag ToggleChoice::prepend_item(Graphic_ptr g)
{
  Trace trace("ToggleChoice::prepend_item");
  Tag tag;
  body()->prepend_graphic(create_item(g, tag));
  return tag;
}

void ToggleChoice::remove_item(Tag t)
{
  Trace trace("ToggleChoice::remove_item");
  my_selection->remove(t);
  Graphic_var box = body();
  box->remove_graphic(t);
}

CheckboxChoice::CheckboxChoice(Selection_ptr s,
			       Graphic_ptr inbox,
			       Graphic_ptr outbox,
			       LayoutKit_ptr l,
			       ToolKit_ptr t)
  : Choice(s, l, t),
    my_in_box(Fresco::Graphic::_duplicate(inbox)),
    my_out_box(Fresco::Graphic::_duplicate(outbox))
{}

RefCount_var<Fresco::Graphic> CheckboxChoice::create_item(Graphic_ptr g, Tag& t)
{
  Trace trace("CheckboxChoice::create_item");

  // Define initial hbox, which is nested inside a toggle-box (no bevel!)
  RefCount_var<Fresco::Graphic> box = my_layout->hbox();
  RefCount_var<Fresco::Controller> toggle_box = my_tools->toggle(box);
  t = my_selection->add(toggle_box);
  append_controller(toggle_box);

  // 'toggle': simply a graphic with bevel dependent upon toggle_box state
  Graphic_var toggle = my_tools->create_switch(my_in_box, my_out_box,
					       Fresco::Controller::toggled,
					       toggle_box);

  // now add the toggle button into the button box, along with g
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->valign(RefCount_var<Fresco::Graphic>(my_layout->margin(toggle, 50.)), 0.5)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->hspace(100.)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->valign(g, 0.5)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->hspace(50.)));
  box->append_graphic(RefCount_var<Fresco::Graphic>(my_layout->hfill()));

  // Add the 'active item' border
//   return RefCount_var<Fresco::Graphic>(create_focus_frame(toggle_box));
  return create_focus_frame(toggle_box);
}

Tag CheckboxChoice::append_item(Graphic_ptr g)
{
  Trace trace("CheckboxChoice::append_item");
  Tag tag;
  body()->append_graphic(create_item(g, tag));
  return tag;
}

Tag CheckboxChoice::prepend_item(Graphic_ptr g)
{
  Trace trace("CheckboxChoice::prepend_item");
  Tag tag;
  body()->prepend_graphic(create_item(g, tag));
  return tag;
}

void CheckboxChoice::remove_item(Tag t)
{
  Trace trace("CheckboxChoice::remove_item");
  my_selection->remove(t);
  Graphic_var box = body();
  box->remove_graphic(t);
}

ToolChoice::ToolChoice(Selection_ptr s, LayoutKit_ptr l, ToolKit_ptr t)
  : Choice(s, l, t)
{}

Tag ToolChoice::append_item(Graphic_ptr g)
{
  Trace trace("ToolChoice::append_item");
  RefCount_var<Fresco::Controller> toggle = my_tools->toggle(Fresco::Graphic::_nil());
  Tag tag = my_selection->add(toggle);
  append_controller(toggle);

  Fresco::ToolKit::FrameSpec in, out;
  in.brightness(0.5); in._d(ToolKit::inset);
  Graphic_var inset = my_tools->frame(g, 20., in, true);
  out.brightness(0.5); out._d(ToolKit::outset);
  Graphic_var outset = my_tools->frame(g, 20., out, true);
  Graphic_var frame = my_tools->create_switch(inset, outset,
					      Fresco::Controller::toggled,
					      toggle);
  toggle->body(frame);
  Graphic_var box = body();
  box->append_graphic(toggle);
  return tag;
}

Tag ToolChoice::prepend_item(Graphic_ptr g)
{
  Trace trace("ToolChoice::prepend_item");
  RefCount_var<Fresco::Controller> toggle = my_tools->toggle(Fresco::Graphic::_nil());
  Tag tag = my_selection->add(toggle);
  prepend_controller(toggle);

  Fresco::ToolKit::FrameSpec in, out;
  in.brightness(0.5); in._d(ToolKit::inset);
  Graphic_var inset = my_tools->frame(g, 20., in, true);
  out.brightness(0.5); out._d(ToolKit::outset);
  Graphic_var outset = my_tools->frame(g, 20., out, true);
  Graphic_var frame = my_tools->create_switch(inset, outset,
					      Fresco::Controller::toggled,
					      toggle);
  toggle->body(frame);
  Graphic_var box = body();
  box->prepend_graphic(toggle);
  return tag;
}

void ToolChoice::remove_item(Tag t)
{
  Trace trace("ToolChoice::remove_item");
  my_selection->remove(t);
  Graphic_var box = body();
  box->remove_graphic(t);
}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2002 by Ryan Surkamp

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csgeom/math2d.h"
#include "csgeom/math3d.h"
#include "csgeom/polyclip.h"
#include "csgeom/poly2d.h"
#include "csgeom/vector3.h"
#include "csutil/garray.h"
#include "iengine/camera.h"
#include "iengine/engine.h"
#include "ivideo/graph3d.h"
#include "ivideo/material.h"
#include "ivideo/vbufmgr.h"
#include "iengine/material.h"
#include "iengine/rview.h"
#include "ivideo/txtmgr.h"
#include "igraphic/image.h"
#include "iutil/objreg.h"
#include "iutil/vfs.h"
#include "imap/ldrctxt.h"
#include "csgfx/rgbpixel.h"
#include "bcterr.h"
#include "quadtree.h"
#include "qint.h"
#include "qsqrt.h"
#include "ivaria/reporter.h"
#include "quadtree.h"

bool Inside (csBox3 bbox, csVector3 *point)
{
  if ( ( point->x <= bbox.MaxX () ) && ( point->x >= bbox.MinX () )
    && ( point->z <= bbox.MaxZ () ) && ( point->z >= bbox.MinZ () )
    && ( point->y <= bbox.MaxY () ) )
    return true;
  else
    return false;
}

void csColQuad::HeightTest (csVector3  *point,
		int &hits)
{
  if ( Inside (bbox, point) )
  {
    int i;
    for (i = 0; i < num_blocks; i++)
    {
      if ( Inside (blocks[i]->bbox, point) )
      {
        if ( point->y < (blocks[i]->bbox.MaxY () + 0.2f) )
        {
          point->y = blocks[i]->bbox.MaxY () + 0.2f;
          hits += 1;
        }
      }
    }
    if (children[0])
    {
      for (i = 0; i < 4; i++)
        children[i]->HeightTest (point, hits);
    }
  }
}

void csColQuad::HeightTestExt (csVector3  *point,
    int &hits)
{
  return; // don't use yet
}

void csColQuad::HeightTestExact (csVector3  *point,
    int &hits)
{
  if ( Inside (bbox, point) )
  {
    int i;
    for (i = 0; i < num_blocks; i++)
    {
      if ( Inside (blocks[i]->bbox, point) )
      {
        if (point->y <= blocks[i]->bbox.MaxY ())
        {
          csVector3 newpoint;
          float u, v;
          csVector3 temp[4];
  u = ( point->x - blocks[i]->bbox.MinX () )
    / (blocks[i]->bbox.MaxX () - blocks[i]->bbox.MinX ());
  v = (blocks[i]->bbox.MaxZ () - point->z)
    / (blocks[i]->bbox.MaxZ () - blocks[i]->bbox.MinZ ());
          if (u < 0.0f) u = -u;
          if (v < 0.0f) v = -v;
          if (u > 1.0f) u = 1.0f;
          if (v > 1.0f) v = 1.0f;
          temp[0] = BezierControlCompute (v, blocks[i]->verts, 4);
          temp[1] = BezierControlCompute (v, &blocks[i]->verts[1], 4);
          temp[2] = BezierControlCompute (v, &blocks[i]->verts[2], 4);
          temp[3] = BezierControlCompute (v, &blocks[i]->verts[3], 4);
          newpoint =  BezierCompute (u, temp);
          if ( (newpoint.y > point->y) ||
               (point->y < (newpoint.y + 1.0f)))
          {
            point->y = newpoint.y + 1.0f;
            hits += 1;
          }
          //point->y = newpoint.y + 10.0f;
        }
      }
    }
    if (children[0])
    {
      for (i = 0; i < 4; i++)
        children[i]->HeightTestExact (point, hits);
    }
  }
}

void csColQuad::SetupChildren (float shortest, iObjectRegistry* object_reg)
{
  csBox3 nbbox;
  csVector3 pt;
  float half_z, half_x;
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCColQuad", "SetupChildren");
  half_z = (bbox.MaxZ () - bbox.MinZ ()) / 2.0f;
  half_x = (bbox.MaxX () - bbox.MinX ()) / 2.0f;
  // left
  nbbox.StartBoundingBox ();
  pt.x = bbox.MinX ();
  pt.y = bbox.MaxY ();
  pt.z = bbox.MaxZ ();
  nbbox.AddBoundingVertex (pt);
  pt.x = bbox.MinX () + half_x;
  pt.y = bbox.MinY ();
  pt.z = bbox.MinZ () + half_z;
  nbbox.AddBoundingVertex (pt);
  children[0] = new csColQuad (shortest, nbbox, object_reg);
  // right
  nbbox.StartBoundingBox ();
  nbbox.AddBoundingVertex ( bbox.Max ());
  pt.x = bbox.MinX () + half_x;
  pt.y = bbox.MinY ();
  pt.z = bbox.MinZ () + half_z;
  nbbox.AddBoundingVertex (pt);
  children[1] = new csColQuad (shortest, nbbox, object_reg);
  // down left
  nbbox.StartBoundingBox ();
  pt.x = bbox.MinX ();
  pt.y = bbox.MaxY ();
  pt.z = bbox.MinZ ();
  nbbox.AddBoundingVertex (pt);
  pt.x = bbox.MinX () + half_x;
  pt.y = bbox.MinY ();
  pt.z = bbox.MinZ () + half_z;
  nbbox.AddBoundingVertex (pt);
  children[2] = new csColQuad (shortest, nbbox, object_reg);
  // down right
  nbbox.StartBoundingBox ();
  pt.x = bbox.MaxX ();
  pt.y = bbox.MaxY ();
  pt.z = bbox.MinZ ();
  nbbox.AddBoundingVertex (pt);
  pt.x = bbox.MinX () + half_x;
  pt.y = bbox.MinY ();
  pt.z = bbox.MinZ () + half_z;
  nbbox.AddBoundingVertex (pt);
  children[3] = new csColQuad (shortest, nbbox, object_reg);
}

csColQuad::csColQuad (csVector3 *cntrl_pt, int x_blocks, int z_blocks,
					  float shortest, iObjectRegistry* object_reg)
{
  int x, z, size, i;
  float half_x, half_z;
  num_blocks = 0;
  blocks = NULL;
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCColQuad", "Big Create");
  x = (x_blocks * 3) + 1;
  z = (z_blocks * 3) + 1;
  size = x * z;
  bbox.StartBoundingBox ();
  for (i = 0; i < size; i++)
  {
    bbox.AddBoundingVertex (cntrl_pt[i]);
  }
  half_z = (bbox.MaxZ () - bbox.MinZ ()) / 2.0f;
  half_x = (bbox.MaxX () - bbox.MinX ()) / 2.0f;
  for (i = 0; i < 4; i++)
  {
    children[i] = NULL;
  }
  if ( (half_z < shortest) && (half_x < shortest) )
    return;
  if ( shortest < 0.5f) return;
  SetupChildren (shortest, object_reg);
}

csColQuad::csColQuad (float shortest, csBox3 nbbox, iObjectRegistry* object_reg)
{
  float half_x, half_z;
  int i;
  num_blocks = 0;
  blocks = NULL;
  bbox = nbbox;
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCColQuad", "Small Create");
  half_z = (bbox.MaxZ () - bbox.MinZ ()) / 2.0f;
  half_x = (bbox.MaxX () - bbox.MinX ()) / 2.0f;
  for (i = 0; i < 4; i++)
  {
    children[i] = NULL;
  }
  if ( (half_z < shortest) && (half_x < shortest) )
    return;
  SetupChildren (shortest, object_reg);
}

void csColQuad::AddBlock (csBCTerrBlock *block)
{
  bool left, right, bleft, bright, multi, done;
  if (children[0])
  {
    multi = false;
    done = false;
    left = CheckBox (children[0]->bbox, block);
    right = CheckBox (children[1]->bbox, block);
    if (right && left)
      multi = true;

    bleft = CheckBox (children[2]->bbox, block);
    if ( (bleft && right) || (bleft && left) )
      multi = true;

    bright = CheckBox (children[3]->bbox, block);
    if ( (bright && bleft) || (bright && right) ||
       (bright && left) )
       multi = true;

    if (multi)
    {
      AddBlockToList (block);
      done = true;
    }
    else
    {
      if (left)
      {
        children[0]->AddBlock (block);
        done = true;
      }
      if (right)
      {
        children[1]->AddBlock (block);
        done = true;
      }
      if (bleft)
      {
        children[2]->AddBlock (block);
        done = true;
      }
      if (bright)
      {
        children[3]->AddBlock (block);
        done = true;
      }
      if (done == false)
        AddBlockToList (block);
    }
  } else
    AddBlockToList (block);
}

void csColQuad::AddBlockToList (csBCTerrBlock *block)
{
  int i;
  if (num_blocks > 0)
  {
    csBCTerrBlock **new_blocks = new csBCTerrBlock*[num_blocks + 1];
    for (i = 0; i < num_blocks; i++)
    {
      new_blocks[i] = blocks[i];
      blocks[i] = NULL;
    }
    delete [] blocks;
    new_blocks[num_blocks] = block;
    blocks = new_blocks;
    num_blocks++;
  } else
  {
    num_blocks++;
    blocks = new csBCTerrBlock*[num_blocks];
    blocks[0] = block;
  }
}

void csColQuad::RebuildBoundingBoxes ()
{
  int i;
  bbox.StartBoundingBox ();
  if (children[0])
  {
    for (i = 0; i < 4; i++)
    {
      children[i]->RebuildBoundingBoxes ();
      bbox += children[i]->bbox;
    }
  }
  if (num_blocks > 0)
  {
    for (i = 0; i < num_blocks; i++)
    {
      bbox += blocks[i]->bbox;
    }
  }
}

bool csColQuad::CheckBox (csBox3 check, csBCTerrBlock *block)
{
  if ( check.In  (block->bbox.GetCenter ()))
  {
    return true;
  } else
  {
    if ( check.In (block->bbox.Max ()) ) return true;
    if ( check.In (block->bbox.Min ()) ) return true;
  }
  return false;
}

csColQuad::~csColQuad ()
{
  int i;
  if (children[0])
  {
    for (i = 0; i < 4; i++)
    {
      delete children[i];
    }
  }
  if ((num_blocks > 0) && (blocks))
  {
    for (i = 0; i < num_blocks; i++)
    {
      blocks[i] = NULL;
    }
    delete [] blocks;
  }
}

csBCCollisionQuad::csBCCollisionQuad ()
{
  root_quad = NULL;
  object_reg = NULL;
}

csBCCollisionQuad::~csBCCollisionQuad ()
{
  if (root_quad) delete root_quad;
}

csBCCollisionQuad::csBCCollisionQuad (csVector3 *cntrl_pt,
									  int x_blocks, int z_blocks,
									  float shortest, iObjectRegistry* nobject_reg)
{
  root_quad = NULL;
  object_reg = nobject_reg;
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Building Quads");
  root_quad = new csColQuad (cntrl_pt, x_blocks, z_blocks, shortest, object_reg);
}

void csBCCollisionQuad::AddBlock (csBCTerrBlock *block)
{
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Adding blocks");
  root_quad->AddBlock (block);
}

void csBCCollisionQuad::RebuildBoundingBoxes ()
{
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Rebuilding blocks");
  root_quad->RebuildBoundingBoxes ();
}

int csBCCollisionQuad::HeightTest (csVector3 *point)
{
  int hits;
  hits = 0;
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Height Test Called");
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Point %f %f %f", point->x, point->y, point->z);
  //point->y = root_quad->bbox.MaxY ();
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","new point %f %f %f", point->x, point->y, point->z);
  //csVector3 max = root_quad->bbox.Max ();
  //csVector3 min = root_quad->bbox.Min ();
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Max Point %f %f %f", max.x, max.y, max.z);
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Max Point %f %f %f", min.x, min.y, min.z);
  root_quad->HeightTest (point, hits);
  return hits;
}

int csBCCollisionQuad::HeightTestExt (csVector3 *point)
{
  int hits;
  hits = 0;
  root_quad->HeightTestExt (point, hits);
  return hits;
}

int csBCCollisionQuad::HeightTestExact (csVector3 *point)
{
  int hits;
  hits = 0;
  root_quad->HeightTestExact (point, hits);
  return hits;
}
<commit_msg>no message<commit_after>/*
    Copyright (C) 2002 by Ryan Surkamp

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
#include "cssysdef.h"
#include "csgeom/math2d.h"
#include "csgeom/math3d.h"
#include "csgeom/polyclip.h"
#include "csgeom/poly2d.h"
#include "csgeom/vector3.h"
#include "csutil/garray.h"
#include "iengine/camera.h"
#include "iengine/engine.h"
#include "ivideo/graph3d.h"
#include "ivideo/material.h"
#include "ivideo/vbufmgr.h"
#include "iengine/material.h"
#include "iengine/rview.h"
#include "ivideo/txtmgr.h"
#include "igraphic/image.h"
#include "iutil/objreg.h"
#include "iutil/vfs.h"
#include "imap/ldrctxt.h"
#include "csgfx/rgbpixel.h"
#include "bcterr.h"
#include "quadtree.h"
#include "qint.h"
#include "qsqrt.h"
#include "ivaria/reporter.h"
#include "quadtree.h"

bool Inside (csBox3 bbox, csVector3 *point)
{
  if ( ( point->x <= bbox.MaxX () ) && ( point->x >= bbox.MinX () )
    && ( point->z <= bbox.MaxZ () ) && ( point->z >= bbox.MinZ () )
    && ( point->y <= bbox.MaxY () ) )
    return true;
  else
    return false;
}

void csColQuad::HeightTest (csVector3  *point,
		int &hits)
{
  if ( Inside (bbox, point) )
  {
    int i;
    for (i = 0; i < num_blocks; i++)
    {
      if ( Inside (blocks[i]->bbox, point) )
      {
        if ( point->y < (blocks[i]->bbox.MaxY () + 0.2f) )
        {
          point->y = blocks[i]->bbox.MaxY () + 0.2f;
          hits += 1;
        }
      }
    }
    if (children[0])
    {
      for (i = 0; i < 4; i++)
        children[i]->HeightTest (point, hits);
    }
  }
}

void csColQuad::HeightTestExt (csVector3  *point,
    int &hits)
{
  return; // don't use yet
}

void csColQuad::HeightTestExact (csVector3  *point,
    int &hits)
{
  if ( Inside (bbox, point) )
  {
    int i;
    for (i = 0; i < num_blocks; i++)
    {
      if ( Inside (blocks[i]->bbox, point) )
      {
        if (point->y <= blocks[i]->bbox.MaxY ())
        {
          csVector3 newpoint;
          float u, v;
          csVector3 temp[4];
  u = ( point->x - blocks[i]->bbox.MinX () )
    / (blocks[i]->bbox.MaxX () - blocks[i]->bbox.MinX ());
  v = (blocks[i]->bbox.MaxZ () - point->z)
    / (blocks[i]->bbox.MaxZ () - blocks[i]->bbox.MinZ ());
          if (u < 0.0f) u = -u;
          if (v < 0.0f) v = -v;
          if (u > 1.0f) u = 1.0f;
          if (v > 1.0f) v = 1.0f;
          temp[0] = BezierControlCompute (v, blocks[i]->verts, 4);
          temp[1] = BezierControlCompute (v, &blocks[i]->verts[1], 4);
          temp[2] = BezierControlCompute (v, &blocks[i]->verts[2], 4);
          temp[3] = BezierControlCompute (v, &blocks[i]->verts[3], 4);
          newpoint =  BezierCompute (u, temp);
          if ( (newpoint.y > point->y) ||
               (point->y < (newpoint.y + 2.0f)))
          {
            point->y = newpoint.y + 2.0f;
            hits += 1;
          }
          //point->y = newpoint.y + 10.0f;
        }
      }
    }
    if (children[0])
    {
      for (i = 0; i < 4; i++)
        children[i]->HeightTestExact (point, hits);
    }
  }
}

void csColQuad::SetupChildren (float shortest, iObjectRegistry* object_reg)
{
  csBox3 nbbox;
  csVector3 pt;
  float half_z, half_x;
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCColQuad", "SetupChildren");
  half_z = (bbox.MaxZ () - bbox.MinZ ()) / 2.0f;
  half_x = (bbox.MaxX () - bbox.MinX ()) / 2.0f;
  // left
  nbbox.StartBoundingBox ();
  pt.x = bbox.MinX ();
  pt.y = bbox.MaxY ();
  pt.z = bbox.MaxZ ();
  nbbox.AddBoundingVertex (pt);
  pt.x = bbox.MinX () + half_x;
  pt.y = bbox.MinY ();
  pt.z = bbox.MinZ () + half_z;
  nbbox.AddBoundingVertex (pt);
  children[0] = new csColQuad (shortest, nbbox, object_reg);
  // right
  nbbox.StartBoundingBox ();
  nbbox.AddBoundingVertex ( bbox.Max ());
  pt.x = bbox.MinX () + half_x;
  pt.y = bbox.MinY ();
  pt.z = bbox.MinZ () + half_z;
  nbbox.AddBoundingVertex (pt);
  children[1] = new csColQuad (shortest, nbbox, object_reg);
  // down left
  nbbox.StartBoundingBox ();
  pt.x = bbox.MinX ();
  pt.y = bbox.MaxY ();
  pt.z = bbox.MinZ ();
  nbbox.AddBoundingVertex (pt);
  pt.x = bbox.MinX () + half_x;
  pt.y = bbox.MinY ();
  pt.z = bbox.MinZ () + half_z;
  nbbox.AddBoundingVertex (pt);
  children[2] = new csColQuad (shortest, nbbox, object_reg);
  // down right
  nbbox.StartBoundingBox ();
  pt.x = bbox.MaxX ();
  pt.y = bbox.MaxY ();
  pt.z = bbox.MinZ ();
  nbbox.AddBoundingVertex (pt);
  pt.x = bbox.MinX () + half_x;
  pt.y = bbox.MinY ();
  pt.z = bbox.MinZ () + half_z;
  nbbox.AddBoundingVertex (pt);
  children[3] = new csColQuad (shortest, nbbox, object_reg);
}

csColQuad::csColQuad (csVector3 *cntrl_pt, int x_blocks, int z_blocks,
					  float shortest, iObjectRegistry* object_reg)
{
  int x, z, size, i;
  float half_x, half_z;
  num_blocks = 0;
  blocks = NULL;
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCColQuad", "Big Create");
  x = (x_blocks * 3) + 1;
  z = (z_blocks * 3) + 1;
  size = x * z;
  bbox.StartBoundingBox ();
  for (i = 0; i < size; i++)
  {
    bbox.AddBoundingVertex (cntrl_pt[i]);
  }
  half_z = (bbox.MaxZ () - bbox.MinZ ()) / 2.0f;
  half_x = (bbox.MaxX () - bbox.MinX ()) / 2.0f;
  for (i = 0; i < 4; i++)
  {
    children[i] = NULL;
  }
  if ( (half_z < shortest) && (half_x < shortest) )
    return;
  if ( shortest < 0.5f) return;
  SetupChildren (shortest, object_reg);
}

csColQuad::csColQuad (float shortest, csBox3 nbbox, iObjectRegistry* object_reg)
{
  float half_x, half_z;
  int i;
  num_blocks = 0;
  blocks = NULL;
  bbox = nbbox;
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCColQuad", "Small Create");
  half_z = (bbox.MaxZ () - bbox.MinZ ()) / 2.0f;
  half_x = (bbox.MaxX () - bbox.MinX ()) / 2.0f;
  for (i = 0; i < 4; i++)
  {
    children[i] = NULL;
  }
  if ( (half_z < shortest) && (half_x < shortest) )
    return;
  SetupChildren (shortest, object_reg);
}

void csColQuad::AddBlock (csBCTerrBlock *block)
{
  bool left, right, bleft, bright, multi, done;
  if (children[0])
  {
    multi = false;
    done = false;
    left = CheckBox (children[0]->bbox, block);
    right = CheckBox (children[1]->bbox, block);
    if (right && left)
      multi = true;

    bleft = CheckBox (children[2]->bbox, block);
    if ( (bleft && right) || (bleft && left) )
      multi = true;

    bright = CheckBox (children[3]->bbox, block);
    if ( (bright && bleft) || (bright && right) ||
       (bright && left) )
       multi = true;

    if (multi)
    {
      AddBlockToList (block);
      done = true;
    }
    else
    {
      if (left)
      {
        children[0]->AddBlock (block);
        done = true;
      }
      if (right)
      {
        children[1]->AddBlock (block);
        done = true;
      }
      if (bleft)
      {
        children[2]->AddBlock (block);
        done = true;
      }
      if (bright)
      {
        children[3]->AddBlock (block);
        done = true;
      }
      if (done == false)
        AddBlockToList (block);
    }
  } else
    AddBlockToList (block);
}

void csColQuad::AddBlockToList (csBCTerrBlock *block)
{
  int i;
  if (num_blocks > 0)
  {
    csBCTerrBlock **new_blocks = new csBCTerrBlock*[num_blocks + 1];
    for (i = 0; i < num_blocks; i++)
    {
      new_blocks[i] = blocks[i];
      blocks[i] = NULL;
    }
    delete [] blocks;
    new_blocks[num_blocks] = block;
    blocks = new_blocks;
    num_blocks++;
  } else
  {
    num_blocks++;
    blocks = new csBCTerrBlock*[num_blocks];
    blocks[0] = block;
  }
}

void csColQuad::RebuildBoundingBoxes ()
{
  int i;
  bbox.StartBoundingBox ();
  if (children[0])
  {
    for (i = 0; i < 4; i++)
    {
      children[i]->RebuildBoundingBoxes ();
      bbox += children[i]->bbox;
    }
  }
  if (num_blocks > 0)
  {
    for (i = 0; i < num_blocks; i++)
    {
      bbox += blocks[i]->bbox;
    }
  }
}

bool csColQuad::CheckBox (csBox3 check, csBCTerrBlock *block)
{
  if ( check.In  (block->bbox.GetCenter ()))
  {
    return true;
  } else
  {
    if ( check.In (block->bbox.Max ()) ) return true;
    if ( check.In (block->bbox.Min ()) ) return true;
  }
  return false;
}

csColQuad::~csColQuad ()
{
  int i;
  if (children[0])
  {
    for (i = 0; i < 4; i++)
    {
      delete children[i];
    }
  }
  if ((num_blocks > 0) && (blocks))
  {
    for (i = 0; i < num_blocks; i++)
    {
      blocks[i] = NULL;
    }
    delete [] blocks;
  }
}

csBCCollisionQuad::csBCCollisionQuad ()
{
  root_quad = NULL;
  object_reg = NULL;
}

csBCCollisionQuad::~csBCCollisionQuad ()
{
  if (root_quad) delete root_quad;
}

csBCCollisionQuad::csBCCollisionQuad (csVector3 *cntrl_pt,
									  int x_blocks, int z_blocks,
									  float shortest, iObjectRegistry* nobject_reg)
{
  root_quad = NULL;
  object_reg = nobject_reg;
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Building Quads");
  root_quad = new csColQuad (cntrl_pt, x_blocks, z_blocks, shortest, object_reg);
}

void csBCCollisionQuad::AddBlock (csBCTerrBlock *block)
{
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Adding blocks");
  root_quad->AddBlock (block);
}

void csBCCollisionQuad::RebuildBoundingBoxes ()
{
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Rebuilding blocks");
  root_quad->RebuildBoundingBoxes ();
}

int csBCCollisionQuad::HeightTest (csVector3 *point)
{
  int hits;
  hits = 0;
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Height Test Called");
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Point %f %f %f", point->x, point->y, point->z);
  //point->y = root_quad->bbox.MaxY ();
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","new point %f %f %f", point->x, point->y, point->z);
  //csVector3 max = root_quad->bbox.Max ();
  //csVector3 min = root_quad->bbox.Min ();
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Max Point %f %f %f", max.x, max.y, max.z);
  //csReport (object_reg, CS_REPORTER_SEVERITY_NOTIFY,"csBCCollisionQuad","Max Point %f %f %f", min.x, min.y, min.z);
  root_quad->HeightTest (point, hits);
  return hits;
}

int csBCCollisionQuad::HeightTestExt (csVector3 *point)
{
  int hits;
  hits = 0;
  root_quad->HeightTestExt (point, hits);
  return hits;
}

int csBCCollisionQuad::HeightTestExact (csVector3 *point)
{
  int hits;
  hits = 0;
  root_quad->HeightTestExact (point, hits);
  return hits;
}
<|endoftext|>


<commit_before>#include <iostream>
#include <fstream>
#include <vector>
#include <regex>

#define CHECK_STREAM(S) do { \
    if (!(S)) throw std::ios_base::failure("error while parsing file"); \
} while (0)

#define CHECK_END_STREAM(S) do { \
    (S).ignore(1); \
    if (!(S).eof()) throw std::ios_base::failure("error while parsing file"); \
} while (0)

class AlienData {
private:
    size_t _L;
    size_t _D;
    size_t _N;
    std::vector<std::string> _alien_words;
    std::vector<std::string> _alien_signals;

public:

public:
    auto parse_file(const std::string & filename)
    {

        std::ifstream file;
        file.open(filename);

        CHECK_STREAM(file >> _L);
        CHECK_STREAM(file >> _D);
        CHECK_STREAM(file >> _N);

        _alien_words = std::vector<std::string>(D());
        _alien_signals = std::vector<std::string>(N());

        file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        for (size_t i = 0; i < D(); ++i) {
            CHECK_STREAM(std::getline(file, _alien_words[i], '\n'));
        }
        for (size_t i = 0; i < N(); ++i) {
            CHECK_STREAM(std::getline(file, _alien_signals[i], '\n'));
            bool mod = false;
            for (size_t j = 0; j < alien_signal(i).size(); ++j) {
                if (alien_signal(i)[j] == '(') {
                    mod = true; continue;
                }
                else if (alien_signal(i)[j] == ')') {
                    mod = false; continue;
                }
                else if (mod && alien_signal(i)[j+1] != ')') {
                    alien_signal(i).insert(++j, "|"); continue;
                }
            }
        }
        CHECK_END_STREAM(file);
        file.close();

        return *this;
    }

    inline auto L(void) const -> size_t
    {
        return _L;
    }

    inline auto D(void) const -> size_t
    {
        return _D;
    }

    inline auto N(void) const -> size_t
    {
        return _N;
    }

    inline auto alien_word(size_t i) -> std::string &
    {
        return _alien_words[i];
    }

    inline auto alien_signal(size_t i) -> std::string &
    {
        return _alien_signals[i];
    }

};

int main(int argc, char** argv)
{
    if (argc < 3) {
        std::cerr << "expected \'./programe filename\' n_threads ";
        return -1;
    }
try {
        AlienData data;
        data.parse_file(argv[1]);

        std::vector<size_t> acc(data.N());
#pragma omp parallel for num_threads(atoi(argv[2]))
        for (size_t i = 0; i < data.N(); ++i) {
            std::regex alien_signal_regex(data.alien_signal(i),
                std::regex::optimize | std::regex_constants::nosubs);
            for (size_t j = 0; j < data.D(); ++j) {
                acc[i] += std::regex_match(data.alien_word(j), alien_signal_regex);
            }
        }
        for (size_t i = 0; i < data.N(); ++i) {
            std::cout << "Case #" + std::to_string(i + 1) + ": "
                      << acc[i] << std::endl;
        }
    } catch (std::exception& exc) {
        std::cerr << exc.what() << std::endl;
        return -2;
    }
    return 0;
}
<commit_msg>Update main_lang.cpp<commit_after>#include <iostream>
#include <fstream>
#include <vector>
#include <ios>
#include <exception>
#include <regex>

#define CHECK_STREAM(S) do { \
    if (!(S)) throw std::ios_base::failure("error while parsing file"); \
} while (0)

#define CHECK_END_STREAM(S) do { \
    (S).ignore(1); \
    if (!(S).eof()) throw std::ios_base::failure("error while parsing file"); \
} while (0)

class AlienData {
private:
    size_t _L;
    size_t _D;
    size_t _N;
    std::vector<std::string> _alien_words;
    std::vector<std::string> _alien_signals;

public:

public:
    auto parse_file(const std::string & filename)
    {

        std::ifstream file;
        file.open(filename);

        CHECK_STREAM(file >> _L);
        CHECK_STREAM(file >> _D);
        CHECK_STREAM(file >> _N);

        _alien_words = std::vector<std::string>(D());
        _alien_signals = std::vector<std::string>(N());

        file.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
        for (size_t i = 0; i < D(); ++i) {
            CHECK_STREAM(std::getline(file, _alien_words[i], '\n'));
        }
        for (size_t i = 0; i < N(); ++i) {
            CHECK_STREAM(std::getline(file, _alien_signals[i], '\n'));
            bool mod = false;
            for (size_t j = 0; j < alien_signal(i).size(); ++j) {
                if (alien_signal(i)[j] == '(') {
                    mod = true; continue;
                }
                else if (alien_signal(i)[j] == ')') {
                    mod = false; continue;
                }
                else if (mod && alien_signal(i)[j+1] != ')') {
                    alien_signal(i).insert(++j, "|"); continue;
                }
            }
        }
        CHECK_END_STREAM(file);
        file.close();

        return *this;
    }

    inline auto L(void) const -> size_t
    {
        return _L;
    }

    inline auto D(void) const -> size_t
    {
        return _D;
    }

    inline auto N(void) const -> size_t
    {
        return _N;
    }

    inline auto alien_word(size_t i) -> std::string &
    {
        return _alien_words[i];
    }

    inline auto alien_signal(size_t i) -> std::string &
    {
        return _alien_signals[i];
    }

};

int main(int argc, char** argv)
{
    if (argc < 3) {
        std::cerr << "expected \'./programe filename\' n_threads ";
        return -1;
    }
try {
        AlienData data;
        data.parse_file(argv[1]);

        std::vector<size_t> acc(data.N());
#pragma omp parallel for num_threads(atoi(argv[2]))
        for (size_t i = 0; i < data.N(); ++i) {
            std::regex alien_signal_regex(data.alien_signal(i),
                std::regex::optimize | std::regex_constants::nosubs);
            for (size_t j = 0; j < data.D(); ++j) {
                acc[i] += std::regex_match(data.alien_word(j), alien_signal_regex);
            }
        }
        for (size_t i = 0; i < data.N(); ++i) {
            std::cout << "Case #" + std::to_string(i + 1) + ": "
                      << acc[i] << std::endl;
        }
    } catch (std::exception& exc) {
        std::cerr << exc.what() << std::endl;
        return -2;
    }
    return 0;
}
<|endoftext|>