<commit_before>/*
 * Copyright (c) 2010 Nathaniel McCallum <nathaniel@natemccallum.com>
 *
 * 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.
 *
 */

#ifndef VALUE_HPP_
#define VALUE_HPP_
#include "types.hpp"
#include <string>

#ifndef _HAVE_NT_VALUE
#define _HAVE_NT_VALUE
typedef struct _ntValue ntValue;
#endif

namespace natus {
/* Type: NativeFunction
 * Function type for calls made back into native space from javascript.
 *
 * Parameters:
 *     fnc - The object representing the function itself.
 *     ths - The 'this' variable for the current execution.
 *           ths has a value of 'Undefined' when being run as a constructor.
 *     arg - The argument vector.
 *
 * Returns:
 *     The return value, which may be an exception.
 */
typedef Value (*NativeFunction)(Value& fnc, Value& ths, Value& arg);

typedef std::basic_string<char> UTF8;
typedef std::basic_string<Char> UTF16;

class Class {
public:
	typedef enum {
		FlagNone      = 0,
		FlagDelete    = 1 << 1,
		FlagGet       = 1 << 2,
		FlagSet       = 1 << 3,
		FlagEnumerate = 1 << 4,
		FlagCall      = 1 << 5,
		FlagObject    = FlagDelete | FlagGet | FlagSet | FlagEnumerate,
		FlagFunction  = FlagObject | FlagCall,
	} Flags;

	virtual Class::Flags getFlags ();

	/*
	 * * Undefined Exception: don't intercept
	 * * Other Exception: throw exception
	 * * Otherwise: success
	 */
	virtual Value        del      (Value& obj, Value& name);

	/*
	 * * Undefined Exception: don't intercept
	 * * Other Exception: throw exception
	 * * Otherwise: returns value
	 */
	virtual Value        get      (Value& obj, Value& name);

	/*
	 * * Undefined Exception: don't intercept
	 * * Other Exception: throw exception
	 * * Otherwise: success
	 */
	virtual Value        set      (Value& obj, Value& name, Value& value);
	virtual Value        enumerate(Value& obj);
	virtual Value        call     (Value& obj, Value& ths,  Value& args);
	virtual ~Class();
};

class Value {
public:
	typedef enum {
		_TypeUnknown  = 0, // Internal use only
		TypeArray     = 1 << 0,
		TypeBool      = 1 << 1,
		TypeFunction  = 1 << 2,
		TypeNull      = 1 << 3,
		TypeNumber    = 1 << 4,
		TypeObject    = 1 << 5,
		TypeString    = 1 << 6,
		TypeUndefined = 1 << 7,
	} Type;

	typedef enum {
		PropAttrNone       = 0,
		PropAttrReadOnly   = 1 << 0,
		PropAttrDontEnum   = 1 << 1,
		PropAttrDontDelete = 1 << 2,
		PropAttrConstant   = PropAttrReadOnly | PropAttrDontDelete,
		PropAttrProtected  = PropAttrConstant | PropAttrDontEnum
	} PropAttr;

	Value();
	Value(ntValue *value, bool steal=true);
	Value(const Value& value);
	~Value();
	Value&                operator=(const Value& value);
	Value                 operator[](long index);
	Value                 operator[](Value& index);
	Value                 operator[](UTF8 string);
	Value                 operator[](UTF16 string);

	Value                 newBoolean(bool b) const;
	Value                 newNumber(double n) const;
	Value                 newString(UTF8 string) const;
	Value                 newString(UTF16 string) const;
	Value                 newArray(const Value* const* array=NULL) const;
	Value                 newFunction(NativeFunction func) const;
	Value                 newObject(Class* cls=NULL) const;
	Value                 newNull() const;
	Value                 newUndefined() const;
	Value                 getGlobal() const;
	Engine                getEngine() const;
	Value::Type           getType() const;
	const char*           getTypeName() const;
	bool                  borrowContext(void **context, void **value) const;
	ntValue*              borrowCValue() const;

	bool                  isGlobal() const;
	bool                  isException() const;
	bool                  isType(Value::Type types) const;
	bool                  isArray() const;
	bool                  isBool() const;
	bool                  isFunction() const;
	bool                  isNull() const;
	bool                  isNumber() const;
	bool                  isObject() const;
	bool                  isString() const;
	bool                  isUndefined() const;

	Value                 toException();
	template <class T> T  to() const { return (T) to<double>(); }

	Value                 del(Value  idx);
	Value                 del(UTF8   idx);
	Value                 del(UTF16  idx);
	Value                 del(size_t idx);
	Value                 delRecursive(UTF8 path);
	Value                 get(Value  idx) const;
	Value                 get(UTF8   idx) const;
	Value                 get(UTF16  idx) const;
	Value                 get(size_t idx) const;
	Value                 getRecursive(UTF8 path);
	Value                 set(Value  idx, Value          value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, bool           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, int            value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, long           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, double         value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, const char*    value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, const Char*    value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, UTF8           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, UTF16          value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, NativeFunction value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, Value          value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, bool           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, int            value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, long           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, double         value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, const char*    value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, const Char*    value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, UTF8           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, UTF16          value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, NativeFunction value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, Value          value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, bool           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, int            value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, long           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, double         value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, const char*    value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, const Char*    value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, UTF8           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, UTF16          value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, NativeFunction value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(size_t idx, Value          value);
	Value                 set(size_t idx, bool           value);
	Value                 set(size_t idx, int            value);
	Value                 set(size_t idx, long           value);
	Value                 set(size_t idx, double         value);
	Value                 set(size_t idx, const char*    value);
	Value                 set(size_t idx, const Char*    value);
	Value                 set(size_t idx, UTF8           value);
	Value                 set(size_t idx, UTF16          value);
	Value                 set(size_t idx, NativeFunction value);
	Value                 setRecursive(UTF8 path, Value          val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, bool           val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, int            val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, long           val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, double         val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, const char*    val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, const Char*    val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, UTF8           val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, UTF16          val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, NativeFunction val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 enumerate() const;

	bool                  setPrivate(const char* key, void *priv, FreeFunction free=NULL);
	bool                  setPrivate(const char* key, Value value);
	template <class T> T  getPrivate(const char* key) const { return (T) getPrivate<void*>(key); }

	Value                 evaluate(Value javascript, Value filename,    unsigned int lineno=0);
	Value                 evaluate(UTF8  javascript, UTF8  filename="", unsigned int lineno=0);
	Value                 evaluate(UTF16 javascript, UTF16 filename,    unsigned int lineno=0);

	Value                 call(Value  ths, Value args=NULL);
	Value                 call(UTF8  name, Value args=NULL);
	Value                 call(UTF16 name, Value args=NULL);
	Value                 callNew(Value args=NULL);
	Value                 callNew(UTF8  name, Value args=NULL);
	Value                 callNew(UTF16 name, Value args=NULL);
private:
	ntValue *internal;
};
template <> bool   Value::to<bool>()   const;
template <> double Value::to<double>() const;
template <> int    Value::to<int>()    const;
template <> long   Value::to<long>()   const;
template <> UTF8   Value::to<UTF8>()   const;
template <> UTF16  Value::to<UTF16>()  const;
template <> void* Value::getPrivate<void*>(const char* key) const;
template <> Value Value::getPrivate<Value>(const char* key) const;

}  // namespace natus
#endif /* VALUE_HPP_ */

<commit_msg>rename _TypeUnknown to TypeUnknown<commit_after>/*
 * Copyright (c) 2010 Nathaniel McCallum <nathaniel@natemccallum.com>
 *
 * 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.
 *
 */

#ifndef VALUE_HPP_
#define VALUE_HPP_
#include "types.hpp"
#include <string>

#ifndef _HAVE_NT_VALUE
#define _HAVE_NT_VALUE
typedef struct _ntValue ntValue;
#endif

namespace natus {
/* Type: NativeFunction
 * Function type for calls made back into native space from javascript.
 *
 * Parameters:
 *     fnc - The object representing the function itself.
 *     ths - The 'this' variable for the current execution.
 *           ths has a value of 'Undefined' when being run as a constructor.
 *     arg - The argument vector.
 *
 * Returns:
 *     The return value, which may be an exception.
 */
typedef Value (*NativeFunction)(Value& fnc, Value& ths, Value& arg);

typedef std::basic_string<char> UTF8;
typedef std::basic_string<Char> UTF16;

class Class {
public:
	typedef enum {
		FlagNone      = 0,
		FlagDelete    = 1 << 1,
		FlagGet       = 1 << 2,
		FlagSet       = 1 << 3,
		FlagEnumerate = 1 << 4,
		FlagCall      = 1 << 5,
		FlagObject    = FlagDelete | FlagGet | FlagSet | FlagEnumerate,
		FlagFunction  = FlagObject | FlagCall,
	} Flags;

	virtual Class::Flags getFlags ();

	/*
	 * * Undefined Exception: don't intercept
	 * * Other Exception: throw exception
	 * * Otherwise: success
	 */
	virtual Value        del      (Value& obj, Value& name);

	/*
	 * * Undefined Exception: don't intercept
	 * * Other Exception: throw exception
	 * * Otherwise: returns value
	 */
	virtual Value        get      (Value& obj, Value& name);

	/*
	 * * Undefined Exception: don't intercept
	 * * Other Exception: throw exception
	 * * Otherwise: success
	 */
	virtual Value        set      (Value& obj, Value& name, Value& value);
	virtual Value        enumerate(Value& obj);
	virtual Value        call     (Value& obj, Value& ths,  Value& args);
	virtual ~Class();
};

class Value {
public:
	typedef enum {
		TypeUnknown   = 0, // Internal use only
		TypeArray     = 1 << 0,
		TypeBool      = 1 << 1,
		TypeFunction  = 1 << 2,
		TypeNull      = 1 << 3,
		TypeNumber    = 1 << 4,
		TypeObject    = 1 << 5,
		TypeString    = 1 << 6,
		TypeUndefined = 1 << 7,
	} Type;

	typedef enum {
		PropAttrNone       = 0,
		PropAttrReadOnly   = 1 << 0,
		PropAttrDontEnum   = 1 << 1,
		PropAttrDontDelete = 1 << 2,
		PropAttrConstant   = PropAttrReadOnly | PropAttrDontDelete,
		PropAttrProtected  = PropAttrConstant | PropAttrDontEnum
	} PropAttr;

	Value();
	Value(ntValue *value, bool steal=true);
	Value(const Value& value);
	~Value();
	Value&                operator=(const Value& value);
	Value                 operator[](long index);
	Value                 operator[](Value& index);
	Value                 operator[](UTF8 string);
	Value                 operator[](UTF16 string);

	Value                 newBoolean(bool b) const;
	Value                 newNumber(double n) const;
	Value                 newString(UTF8 string) const;
	Value                 newString(UTF16 string) const;
	Value                 newArray(const Value* const* array=NULL) const;
	Value                 newFunction(NativeFunction func) const;
	Value                 newObject(Class* cls=NULL) const;
	Value                 newNull() const;
	Value                 newUndefined() const;
	Value                 getGlobal() const;
	Engine                getEngine() const;
	Value::Type           getType() const;
	const char*           getTypeName() const;
	bool                  borrowContext(void **context, void **value) const;
	ntValue*              borrowCValue() const;

	bool                  isGlobal() const;
	bool                  isException() const;
	bool                  isType(Value::Type types) const;
	bool                  isArray() const;
	bool                  isBool() const;
	bool                  isFunction() const;
	bool                  isNull() const;
	bool                  isNumber() const;
	bool                  isObject() const;
	bool                  isString() const;
	bool                  isUndefined() const;

	Value                 toException();
	template <class T> T  to() const { return (T) to<double>(); }

	Value                 del(Value  idx);
	Value                 del(UTF8   idx);
	Value                 del(UTF16  idx);
	Value                 del(size_t idx);
	Value                 delRecursive(UTF8 path);
	Value                 get(Value  idx) const;
	Value                 get(UTF8   idx) const;
	Value                 get(UTF16  idx) const;
	Value                 get(size_t idx) const;
	Value                 getRecursive(UTF8 path);
	Value                 set(Value  idx, Value          value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, bool           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, int            value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, long           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, double         value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, const char*    value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, const Char*    value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, UTF8           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, UTF16          value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(Value  idx, NativeFunction value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, Value          value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, bool           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, int            value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, long           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, double         value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, const char*    value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, const Char*    value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, UTF8           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, UTF16          value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF8   idx, NativeFunction value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, Value          value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, bool           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, int            value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, long           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, double         value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, const char*    value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, const Char*    value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, UTF8           value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, UTF16          value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(UTF16  idx, NativeFunction value, Value::PropAttr attrs=PropAttrNone);
	Value                 set(size_t idx, Value          value);
	Value                 set(size_t idx, bool           value);
	Value                 set(size_t idx, int            value);
	Value                 set(size_t idx, long           value);
	Value                 set(size_t idx, double         value);
	Value                 set(size_t idx, const char*    value);
	Value                 set(size_t idx, const Char*    value);
	Value                 set(size_t idx, UTF8           value);
	Value                 set(size_t idx, UTF16          value);
	Value                 set(size_t idx, NativeFunction value);
	Value                 setRecursive(UTF8 path, Value          val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, bool           val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, int            val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, long           val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, double         val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, const char*    val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, const Char*    val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, UTF8           val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, UTF16          val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 setRecursive(UTF8 path, NativeFunction val, Value::PropAttr attrs=PropAttrNone, bool mkpath=false);
	Value                 enumerate() const;

	bool                  setPrivate(const char* key, void *priv, FreeFunction free=NULL);
	bool                  setPrivate(const char* key, Value value);
	template <class T> T  getPrivate(const char* key) const { return (T) getPrivate<void*>(key); }

	Value                 evaluate(Value javascript, Value filename,    unsigned int lineno=0);
	Value                 evaluate(UTF8  javascript, UTF8  filename="", unsigned int lineno=0);
	Value                 evaluate(UTF16 javascript, UTF16 filename,    unsigned int lineno=0);

	Value                 call(Value  ths, Value args=NULL);
	Value                 call(UTF8  name, Value args=NULL);
	Value                 call(UTF16 name, Value args=NULL);
	Value                 callNew(Value args=NULL);
	Value                 callNew(UTF8  name, Value args=NULL);
	Value                 callNew(UTF16 name, Value args=NULL);
private:
	ntValue *internal;
};
template <> bool   Value::to<bool>()   const;
template <> double Value::to<double>() const;
template <> int    Value::to<int>()    const;
template <> long   Value::to<long>()   const;
template <> UTF8   Value::to<UTF8>()   const;
template <> UTF16  Value::to<UTF16>()  const;
template <> void* Value::getPrivate<void*>(const char* key) const;
template <> Value Value::getPrivate<Value>(const char* key) const;

}  // namespace natus
#endif /* VALUE_HPP_ */

<|endoftext|>


<commit_before>#include <iostream>

using namespace std;

int main() {
    int x, y, z;
    cin >> x >> y;
    z=(x + y - 1) / y;
    cout << z;
    return 0;
}<commit_msg>белки<commit_after>#include <iostream>

using namespace std;

int main() {
    int x, y, z;
    cin >> x >> y;
    z = y / x;
    cout << z;
    return 0;
}<|endoftext|>


<commit_before>// coding: utf-8
#ifndef TASK_HEADPHONE_HPP
#define TASK_HEADPHONE_HPP

#include <xpcc/processing.hpp>
#include <xpcc/driver/inertial/hmc6343.hpp>
#include "../hardware.hpp"
#include "task_leds.hpp"
#include <xpcc/debug/logger.hpp>

#undef	XPCC_LOG_LEVEL
#define	XPCC_LOG_LEVEL xpcc::log::DEBUG

namespace task
{

class Headphone : private xpcc::pt::Protothread, private xpcc::co::Coroutine
{
public:
	Headphone(Leds &leds);

	void
	update();

	/// @return `true` if device response to pings
	bool ALWAYS_INLINE
	isAvailable()
	{ return devicePingable; }

	/// @return device id or `-1` if device id is not valid (no device, or still reading)
	uint16_t ALWAYS_INLINE
	getDeviceId()
	{ return deviceId; }

	xpcc::co::Result<bool>
	enterCalibrationMode()
	{
		CO_BEGIN(this);

		CO_CALL(device.readRegister(this, device.Register16::X_Offset, xOffset));
		CO_CALL(device.readRegister(this, device.Register16::Y_Offset, yOffset));
		CO_CALL(device.readRegister(this, device.Register16::Z_Offset, zOffset));

		XPCC_LOG_DEBUG << "Offsets before: x=" << xOffset << " y=" << yOffset << " z=" << zOffset << xpcc::endl;

		if ( CO_CALL(device.enterUserCalibrationMode(this)) )
			CO_RETURN(true);

		leds.setHeadphoneError();
		CO_END();
	}

	xpcc::co::Result<bool>
	exitCalibrationMode()
	{
		CO_BEGIN(this);

		if ( CO_CALL(device.exitUserCalibrationMode(this)) )
		{
			CO_CALL(device.readRegister(this, device.Register16::X_Offset, xOffset));
			CO_CALL(device.readRegister(this, device.Register16::Y_Offset, yOffset));
			CO_CALL(device.readRegister(this, device.Register16::Z_Offset, zOffset));

			XPCC_LOG_DEBUG << "Offsets after: x=" << xOffset << " y=" << yOffset << " z=" << zOffset << xpcc::endl;

			CO_RETURN(true);
		}

		leds.setHeadphoneError();
		CO_END();
	}

private:
	bool
	run();

	Leds &leds;

	uint8_t compassData[21];
	xpcc::Hmc6343<Twi> compass;
	xpcc::PeriodicTimer<> pingTimer;
	bool devicePingable;

	uint16_t deviceId;
	uint16_t xOffset;
	uint16_t yOffset;
	uint16_t zOffset;

	xpcc::Hmc6343<Twi> device;
	uint8_t deviceData[21];
};

} // namespace task

#include "task_headphone_impl.hpp"

#endif // TASK_HEADPHONE_HPP
<commit_msg>Set IIR Filter to 5.<commit_after>// coding: utf-8
#ifndef TASK_HEADPHONE_HPP
#define TASK_HEADPHONE_HPP

#include <xpcc/processing.hpp>
#include <xpcc/driver/inertial/hmc6343.hpp>
#include "../hardware.hpp"
#include "task_leds.hpp"
#include <xpcc/debug/logger.hpp>

#undef	XPCC_LOG_LEVEL
#define	XPCC_LOG_LEVEL xpcc::log::DEBUG

namespace task
{

class Headphone : private xpcc::pt::Protothread, private xpcc::co::Coroutine
{
public:
	Headphone(Leds &leds);

	void
	update();

	/// @return `true` if device response to pings
	bool ALWAYS_INLINE
	isAvailable()
	{ return devicePingable; }

	/// @return device id or `-1` if device id is not valid (no device, or still reading)
	uint16_t ALWAYS_INLINE
	getDeviceId()
	{ return deviceId; }

	xpcc::co::Result<bool>
	enterCalibrationMode()
	{
		CO_BEGIN(this);

		CO_CALL(device.readRegister(this, device.Register::FilterLsb, filter));
		XPCC_LOG_DEBUG << "IIR Filter= " << filter << xpcc::endl;
		CO_CALL(device.setIIR_Filter(this, 5));

		CO_CALL(device.readRegister(this, device.Register16::X_Offset, xOffset));
		CO_CALL(device.readRegister(this, device.Register16::Y_Offset, yOffset));
		CO_CALL(device.readRegister(this, device.Register16::Z_Offset, zOffset));

		XPCC_LOG_DEBUG << "Offsets before: x=" << xOffset << " y=" << yOffset << " z=" << zOffset << xpcc::endl;

		if ( CO_CALL(device.enterUserCalibrationMode(this)) )
			CO_RETURN(true);

		leds.setHeadphoneError();
		CO_END();
	}

	xpcc::co::Result<bool>
	exitCalibrationMode()
	{
		CO_BEGIN(this);

		if ( CO_CALL(device.exitUserCalibrationMode(this)) )
		{
			CO_CALL(device.readRegister(this, device.Register16::X_Offset, xOffset));
			CO_CALL(device.readRegister(this, device.Register16::Y_Offset, yOffset));
			CO_CALL(device.readRegister(this, device.Register16::Z_Offset, zOffset));

			XPCC_LOG_DEBUG << "Offsets after: x=" << xOffset << " y=" << yOffset << " z=" << zOffset << xpcc::endl;

			CO_RETURN(true);
		}

		leds.setHeadphoneError();
		CO_END();
	}

private:
	bool
	run();

	Leds &leds;

	uint8_t compassData[21];
	xpcc::Hmc6343<Twi> compass;
	xpcc::PeriodicTimer<> pingTimer;
	bool devicePingable;

	uint16_t deviceId;
	uint16_t xOffset;
	uint16_t yOffset;
	uint16_t zOffset;
	uint8_t filter;

	xpcc::Hmc6343<Twi> device;
	uint8_t deviceData[21];
};

} // namespace task

#include "task_headphone_impl.hpp"

#endif // TASK_HEADPHONE_HPP
<|endoftext|>


<commit_before>//-*-c++-*-

/**************************************************************************/
/**
 **  @file tLithologyManager.cpp
 **
 **  @brief Implementation of the tLithologyManager class.
 **
 **  For information regarding this program, please contact Greg Tucker at:
 **
 **     Cooperative Institute for Research in Environmental Sciences (CIRES)
 **     and Department of Geological Sciences
 **     University of Colorado
 **     2200 Colorado Avenue, Campus Box 399
 **     Boulder, CO 80309-0399
 */
/**************************************************************************/

#include <vector>
#include <sstream>
#include "tLithologyManager.h"

using namespace std;

/**************************************************************************/
/**
 **  Basic constructor
 **
 **  (does nothing at the moment)
 */
/**************************************************************************/
tLithologyManager::
tLithologyManager() :
  meshPtr_(0)
{
  if(1) cout << "tLithologyManager default constructor" << endl;
}

/**************************************************************************/
/**
 **  Destructor
 **
 **  Closes and deletes any remaining ofstream objects.
 */
/**************************************************************************/
tLithologyManager::
~tLithologyManager()
{
  if(1) cout << "tLithologyManager destructor" << endl;
}

/**************************************************************************/
/**
 **  InitializeFromInputFile
 **
 */
/**************************************************************************/
void tLithologyManager::
InitializeFromInputFile( tInputFile &inputFile, tMesh<tLNode> *meshPtr )
{
  if(1) cout << "tLithologyManager::InitializeFromInputFile" << endl;

  meshPtr_ = meshPtr;

  // Read from the input file and do what the user requests

  /* Notes:

  Things we ought to handle include:
  - read from a restart run
  - read from another CHILD-format lith file with given name
  - set lithology according to a strat sequence of uniform thicknesses
    - with or without a uniform or varying regolith layer on top
  - set lithology according to a map pattern (uniform in depth)
    - with or without a uniform or varying regolith layer on top
  - set regolith thickness according to a map pattern
  - set to simple "bedrock and regolith" (current default)
  - ?? set according to a set of "contact surfaces" that represent the lower
    boundary of a unit

  */

	// See if the user wants to start with an existing .lay file. If so, read it
	// and set layers accordingly.
	bool user_wants_to_read_from_layfile = inputFile.ReadBool( "OPT_READ_LAYFILE", false );
	if( user_wants_to_read_from_layfile )
	{
		SetLithologyFromChildLayFile( inputFile );
	}

	// See if the user wants to modify layers according to an Etch File.
  // An Etch File specifies one or more layers, with given properties, to be
  // "etched in" to the current topography and lithology.
	bool user_wants_to_read_from_etchfile = inputFile.ReadBool( "OPT_READ_ETCHFILE", false );
	if( user_wants_to_read_from_etchfile )
	{
		SetLithologyFromEtchFile( inputFile );
	}
}

/**************************************************************************/
/**
 **  SetLithologyFromChildLayFile
 **
 **  This function sets the layers and properties based on data in a
 **  specified CHILD-format .lay file. The previous layers are removed.
 */
/**************************************************************************/
void tLithologyManager::
SetLithologyFromChildLayFile( const tInputFile &infile )
{
  int i, item, numl;
  int numlayernodes;
  double time;
  double ditem;
  char thestring[80], inname[80];
  std::ifstream layerinfile;
  infile.ReadItem( thestring, sizeof(thestring), "INPUT_LAY_FILE" );

  if (1) //DEBUG
    std::cout<<"in SetLithologyFromChildLayFile..."<<std::endl;

  strcpy( inname, thestring );
  layerinfile.open(inname); /* Layer input file pointer */
  assert( layerinfile.good() );

  // Read first line, which should contain the time corresponding to the run
  layerinfile >> time;

  if(1) //DEBUG
    std::cout<<"Time="<<time<<std::endl;

  // Read second line, which specified number of interior nodes in file.
  layerinfile >> numlayernodes;
  if(1) //DEBUG
    std::cout<<"nnodes in file="<<numlayernodes<<std::endl;
  if( numlayernodes != meshPtr_->getNodeList()->getActiveSize() )
    ReportFatalError( "Number of nodes in layer file doesn't match number in mesh" );

  // Create and initialize a tLayer object that will serve as the basic template
  // for all layers. Set its # of grain size classes.
  tLayer layer_template;
  int numg;
  numg = infile.ReadInt( "NUMGRNSIZE" );
  layer_template.setDgradesize(numg);

  // Get an iterator for the node list
  tLNode * cn;
  tMesh<tLNode>::nodeListIter_t ni( meshPtr_->getNodeList() );
    // Hack: make layers input backwards compatible for simulations
    // without bulk density; :
  bool optNewLayersInput = infile.ReadBool( "OPT_NEW_LAYERSINPUT", false );

  for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )
  {
    // Remove pre-existing layers
    for(i=cn->getNumLayer()-1; i>=0; i-- )
      cn->removeLayer(i);

    // Read the number of layers at the current node
    layerinfile >> numl;
    if( numl<1 )
    {
      std::cout << "In SetLithologyFromChildLayFile: node "
      << cn->getPermID() << " has " << numl << " layers."
      << std::endl;
      ReportFatalError( "Each interior point must have at least one layer." );
    }

    // For each layer, read its properties, assign them to our template layer,
    // and insert a copy of that layer to the bottom of the layer list for this
    // node.
    for(i = 1; i<=numl; i++)
    {
      // Read layer properties
      layerinfile >> ditem;     // layer creation time
      layer_template.setCtime(ditem);
      layerinfile >> ditem;     // layer "recent activity" time
      layer_template.setRtime(ditem);
      layerinfile >> ditem;     // layer surface exposure duration
      layer_template.setEtime(ditem);
      layerinfile >> ditem;     // layer thickness (m)
      if( ditem <= 0. )
      {
        std::cout << "MakeLayersFromInputData: Layer " << i
        << " at node " << cn->getID()
        << " has thickness " << ditem << std::endl;
        ReportFatalError("Layers must have positive thickness.");
      }
      layer_template.setDepth(ditem);
      layerinfile >> ditem;     // layer erodibility
      layer_template.setErody(ditem);
        // Hack: to make this backwards compatible,
        // read bulk density if optNewLayersInput == true:
      if( optNewLayersInput )
      {
        layerinfile >> ditem;   // layer bulk density
        layer_template.setBulkDensity(ditem);
      }
      layerinfile >> item;      // layer alluvial-bedrock flag
      if( item<0 || item>1 )
      {
        std::cout << "MakeLayersFromInputData: Layer " << i
        << " at node " << cn->getID()
        << " has flag value " << item << std::endl;
        ReportFatalError("Flag value must be either zero or one.");
      }
      {
        tLayer::tSed_t item_ = static_cast<tLayer::tSed_t>(item);
        layer_template.setSed(item_);
      }
      for(int g=0; g<numg; g++){
        layerinfile >> ditem;   // equivalent thickness of grain size g
        layer_template.setDgrade(g, ditem);
      }

      // Insert a copy of the layer on the bottom of the layer stack
      cn->InsertLayerBack( layer_template );
    }

  }

}

/**************************************************************************/
/**
 **  SetLithologyFromEtchFile
 **
 **  This function sets the layers and properties based on data in a
 **  specified Etchfile.
 */
/**************************************************************************/
void tLithologyManager::
SetLithologyFromEtchFile( const tInputFile &infile )
{

}

/**************************************************************************/
/**
 **  SetRockErodibilityValuesAtAllDepths
 **
 **  This function sets the value of bedrock erodibility at each node
 **  according to the values in the parameter "erody". This parameter is
 **  assumed to be a vector of size equal to the number of nodes, and
 **  ordered according to node (permanent) ID. All rock layers at a node
 **  are given the same erodibility values. Sediment layers are not
 **  affected.
 */
/**************************************************************************/
void tLithologyManager::
SetRockErodibilityValuesAtAllDepths( vector<double> erody )
{
  tLNode * cn;
  tMesh<tLNode>::nodeListIter_t ni( meshPtr_->getNodeList() );

  for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )
  {
    int node_id = cn->getPermID();
    double local_erody = erody[node_id];
    std::cout << "There are " << cn->getNumLayer() << " layers at node " << node_id << std::endl;
    for( int i=0; i<cn->getNumLayer(); i++ )
    {
      std::cout << "  Working on layer " << i << std:: endl;
      if( cn->getLayerSed(i)==tLayer::kBedRock )
        cn->setLayerErody(i, local_erody);
    }
  }

}

/**************************************************************************/
/**
 */
/**************************************************************************/
void tLithologyManager::
EtchLayerAboveHeightAtNode( double layer_base_height, tLNode * node,
                           tLayer &layer_properties, bool keep_regolith )
{
}

/**************************************************************************/
/**
 **  PointInPolygon
 **
 **  Determines whether the point (point_x, point_y) lies inside the
 **  polygon described by vertx, verty. Ray casting algorithm,
 **  re-written in C++ from web-published C code by W. Randolph Franklin.
 */
/**************************************************************************/
bool tLithologyManager::
PointInPolygon( std::vector<double> vertx,
               std::vector<double> verty,
               double point_x, double point_y )
{
  unsigned i, j;
  unsigned n_vertices = vertx.size();
  assert( n_vertices==verty.size() );
  bool point_is_in = false;
  for( i=0, j = n_vertices-1; i<n_vertices; j = i++ )
  {
    if ( ((verty[i]>point_y) != (verty[j]>point_y)) &&
        (point_x < (vertx[j]-vertx[i]) * (point_y-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
      point_is_in = !point_is_in;
  }
  return point_is_in;
}

/**************************************************************************/
/**
 **  EtchLayerAbove2DSurface
 **
 **  This function inserts a new layer with a given set of properties
 **  above a 2D surface described by a polynomial, and within the map
 **  area described by a second (optional) polynomial.
 */
/**************************************************************************/
void tLithologyManager::
EtchLayerAbove2DSurface(  vector<double> &poly_coefs_x,
                          vector<double> &poly_coefs_y,
                          tLayer &layer_properties,
                          bool keep_regolith,
                          bool use_bounding_polygon,
                          vector<double> bounding_poly_x,
                          vector<double> bounding_poly_y )
{
  tLNode * cn;
  tMesh<tLNode>::nodeListIter_t ni( meshPtr_->getNodeList() );

  for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )
  {
    bool layer_is_present_here = true;
    if( use_bounding_polygon )
      if( !PointInPolygon( bounding_poly_x, bounding_poly_y, cn->getX(), cn->getY() ) )
         layer_is_present_here = false;
    if( layer_is_present_here )
    {
      double x = cn->getX();
      double y = cn->getY();
      double new_layer_base_height = poly_coefs_x[0]*x*x*x +
                              poly_coefs_x[1]*x*x +
                              poly_coefs_x[2]*x +
                              poly_coefs_x[3] +
                              poly_coefs_y[0]*y*y*y +
                              poly_coefs_y[1]*y*y +
                              poly_coefs_y[2]*y +
                              poly_coefs_y[3];
      if( new_layer_base_height < cn->getZ() )
        EtchLayerAboveHeightAtNode( new_layer_base_height, cn, layer_properties, keep_regolith );
    }
  }

}

/**************************************************************************/
/**
 */
/**************************************************************************/

<commit_msg>Fixed problem in assigning bulk density when reading layers.<commit_after>//-*-c++-*-

/**************************************************************************/
/**
 **  @file tLithologyManager.cpp
 **
 **  @brief Implementation of the tLithologyManager class.
 **
 **  For information regarding this program, please contact Greg Tucker at:
 **
 **     Cooperative Institute for Research in Environmental Sciences (CIRES)
 **     and Department of Geological Sciences
 **     University of Colorado
 **     2200 Colorado Avenue, Campus Box 399
 **     Boulder, CO 80309-0399
 */
/**************************************************************************/

#include <vector>
#include <sstream>
#include "tLithologyManager.h"

using namespace std;

/**************************************************************************/
/**
 **  Basic constructor
 **
 **  (does nothing at the moment)
 */
/**************************************************************************/
tLithologyManager::
tLithologyManager() :
  meshPtr_(0)
{
  if(1) cout << "tLithologyManager default constructor" << endl;
}

/**************************************************************************/
/**
 **  Destructor
 **
 **  Closes and deletes any remaining ofstream objects.
 */
/**************************************************************************/
tLithologyManager::
~tLithologyManager()
{
  if(1) cout << "tLithologyManager destructor" << endl;
}

/**************************************************************************/
/**
 **  InitializeFromInputFile
 **
 */
/**************************************************************************/
void tLithologyManager::
InitializeFromInputFile( tInputFile &inputFile, tMesh<tLNode> *meshPtr )
{
  if(1) cout << "tLithologyManager::InitializeFromInputFile" << endl;

  meshPtr_ = meshPtr;

  // Read from the input file and do what the user requests

  /* Notes:

  Things we ought to handle include:
  - read from a restart run
  - read from another CHILD-format lith file with given name
  - set lithology according to a strat sequence of uniform thicknesses
    - with or without a uniform or varying regolith layer on top
  - set lithology according to a map pattern (uniform in depth)
    - with or without a uniform or varying regolith layer on top
  - set regolith thickness according to a map pattern
  - set to simple "bedrock and regolith" (current default)
  - ?? set according to a set of "contact surfaces" that represent the lower
    boundary of a unit

  */

	// See if the user wants to start with an existing .lay file. If so, read it
	// and set layers accordingly.
	bool user_wants_to_read_from_layfile = inputFile.ReadBool( "OPT_READ_LAYFILE", false );
	if( user_wants_to_read_from_layfile )
	{
		SetLithologyFromChildLayFile( inputFile );
	}

	// See if the user wants to modify layers according to an Etch File.
  // An Etch File specifies one or more layers, with given properties, to be
  // "etched in" to the current topography and lithology.
	bool user_wants_to_read_from_etchfile = inputFile.ReadBool( "OPT_READ_ETCHFILE", false );
	if( user_wants_to_read_from_etchfile )
	{
		SetLithologyFromEtchFile( inputFile );
	}
}

/**************************************************************************/
/**
 **  SetLithologyFromChildLayFile
 **
 **  This function sets the layers and properties based on data in a
 **  specified CHILD-format .lay file. The previous layers are removed.
 */
/**************************************************************************/
void tLithologyManager::
SetLithologyFromChildLayFile( const tInputFile &infile )
{
  int i, item, numl;
  int numlayernodes;
  double time;
  double ditem;
  char thestring[80], inname[80];
  std::ifstream layerinfile;
  infile.ReadItem( thestring, sizeof(thestring), "INPUT_LAY_FILE" );

  if (1) //DEBUG
    std::cout<<"in SetLithologyFromChildLayFile..."<<std::endl;

  strcpy( inname, thestring );
  layerinfile.open(inname); /* Layer input file pointer */
  assert( layerinfile.good() );

  // Read first line, which should contain the time corresponding to the run
  layerinfile >> time;

  if(1) //DEBUG
    std::cout<<"Time="<<time<<std::endl;

  // Read second line, which specified number of interior nodes in file.
  layerinfile >> numlayernodes;
  if(1) //DEBUG
    std::cout<<"nnodes in file="<<numlayernodes<<std::endl;
  if( numlayernodes != meshPtr_->getNodeList()->getActiveSize() )
    ReportFatalError( "Number of nodes in layer file doesn't match number in mesh" );

  // Create and initialize a tLayer object that will serve as the basic template
  // for all layers. Set its # of grain size classes.
  tLayer layer_template;
  int numg;
  numg = infile.ReadInt( "NUMGRNSIZE" );
  layer_template.setDgradesize(numg);

  // Get an iterator for the node list
  tLNode * cn;
  tMesh<tLNode>::nodeListIter_t ni( meshPtr_->getNodeList() );
    // Hack: make layers input backwards compatible for simulations
    // without bulk density; :
  bool optNewLayersInput = infile.ReadBool( "OPT_NEW_LAYERSINPUT", false );
	double rock_density, sed_density;
	if( !optNewLayersInput )
	{
		rock_density = infile.ReadDouble( "ROCKDENSITYINIT", false );
		if( rock_density==0.0 ) rock_density = kDefaultRockBulkDensity;
		sed_density = infile.ReadDouble( "SOILBULKDENSITY", false );
		if( sed_density==0.0 ) sed_density = kDefaultSoilBulkDensity;
	}

  for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )
  {
    // Remove pre-existing layers
    for(i=cn->getNumLayer()-1; i>=0; i-- )
      cn->removeLayer(i);

    // Read the number of layers at the current node
    layerinfile >> numl;
    if( numl<1 )
    {
      std::cout << "In SetLithologyFromChildLayFile: node "
      << cn->getPermID() << " has " << numl << " layers."
      << std::endl;
      ReportFatalError( "Each interior point must have at least one layer." );
    }

    // For each layer, read its properties, assign them to our template layer,
    // and insert a copy of that layer to the bottom of the layer list for this
    // node.
    for(i = 1; i<=numl; i++)
    {
      // Read layer properties
      layerinfile >> ditem;     // layer creation time
      layer_template.setCtime(ditem);
      layerinfile >> ditem;     // layer "recent activity" time
      layer_template.setRtime(ditem);
      layerinfile >> ditem;     // layer surface exposure duration
      layer_template.setEtime(ditem);
      layerinfile >> ditem;     // layer thickness (m)
      if( ditem <= 0. )
      {
        std::cout << "MakeLayersFromInputData: Layer " << i
        << " at node " << cn->getID()
        << " has thickness " << ditem << std::endl;
        ReportFatalError("Layers must have positive thickness.");
      }
      layer_template.setDepth(ditem);
      layerinfile >> ditem;     // layer erodibility
      layer_template.setErody(ditem);

			// layer alluvial-bedrock flag
			tLayer::tSed_t bedrock_alluvial_flag;
			int item;
      layerinfile >> item;
			if( item==0 )
				bedrock_alluvial_flag = tLayer::kBedRock;
			else
			{
				if( item==1 )
					bedrock_alluvial_flag = tLayer::kSed;
				else
				{
					std::cout << "MakeLayersFromInputData: Layer " << i
					<< " at node " << cn->getID()
					<< " has flag value " << bedrock_alluvial_flag << std::endl;
					ReportFatalError("Flag value must be either zero or one.");
				}
			}
		  layer_template.setSed(bedrock_alluvial_flag);

			// Hack: to make this backwards compatible,
			// read bulk density if optNewLayersInput == true; otherwise, use values
			// specified in input file or defaults, as above.
      if( optNewLayersInput )
      {
        layerinfile >> ditem;   // layer bulk density
        layer_template.setBulkDensity(ditem);
      }
			else
			{
				if( bedrock_alluvial_flag==tLayer::kSed ) layer_template.setBulkDensity( sed_density );
				else layer_template.setBulkDensity( rock_density );
			}

			for(int g=0; g<numg; g++){
        layerinfile >> ditem;   // equivalent thickness of grain size g
        layer_template.setDgrade(g, ditem);
      }

      // Insert a copy of the layer on the bottom of the layer stack
      cn->InsertLayerBack( layer_template );
    }

  }

}

/**************************************************************************/
/**
 **  SetLithologyFromEtchFile
 **
 **  This function sets the layers and properties based on data in a
 **  specified Etchfile.
 */
/**************************************************************************/
void tLithologyManager::
SetLithologyFromEtchFile( const tInputFile &infile )
{

}

/**************************************************************************/
/**
 **  SetRockErodibilityValuesAtAllDepths
 **
 **  This function sets the value of bedrock erodibility at each node
 **  according to the values in the parameter "erody". This parameter is
 **  assumed to be a vector of size equal to the number of nodes, and
 **  ordered according to node (permanent) ID. All rock layers at a node
 **  are given the same erodibility values. Sediment layers are not
 **  affected.
 */
/**************************************************************************/
void tLithologyManager::
SetRockErodibilityValuesAtAllDepths( vector<double> erody )
{
  tLNode * cn;
  tMesh<tLNode>::nodeListIter_t ni( meshPtr_->getNodeList() );

  for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )
  {
    int node_id = cn->getPermID();
    double local_erody = erody[node_id];
    std::cout << "There are " << cn->getNumLayer() << " layers at node " << node_id << std::endl;
    for( int i=0; i<cn->getNumLayer(); i++ )
    {
      std::cout << "  Working on layer " << i << std:: endl;
      if( cn->getLayerSed(i)==tLayer::kBedRock )
        cn->setLayerErody(i, local_erody);
    }
  }

}

/**************************************************************************/
/**
 */
/**************************************************************************/
void tLithologyManager::
EtchLayerAboveHeightAtNode( double layer_base_height, tLNode * node,
                           tLayer &layer_properties, bool keep_regolith )
{
}

/**************************************************************************/
/**
 **  PointInPolygon
 **
 **  Determines whether the point (point_x, point_y) lies inside the
 **  polygon described by vertx, verty. Ray casting algorithm,
 **  re-written in C++ from web-published C code by W. Randolph Franklin.
 */
/**************************************************************************/
bool tLithologyManager::
PointInPolygon( std::vector<double> vertx,
               std::vector<double> verty,
               double point_x, double point_y )
{
  unsigned i, j;
  unsigned n_vertices = vertx.size();
  assert( n_vertices==verty.size() );
  bool point_is_in = false;
  for( i=0, j = n_vertices-1; i<n_vertices; j = i++ )
  {
    if ( ((verty[i]>point_y) != (verty[j]>point_y)) &&
        (point_x < (vertx[j]-vertx[i]) * (point_y-verty[i]) / (verty[j]-verty[i]) + vertx[i]) )
      point_is_in = !point_is_in;
  }
  return point_is_in;
}

/**************************************************************************/
/**
 **  EtchLayerAbove2DSurface
 **
 **  This function inserts a new layer with a given set of properties
 **  above a 2D surface described by a polynomial, and within the map
 **  area described by a second (optional) polynomial.
 */
/**************************************************************************/
void tLithologyManager::
EtchLayerAbove2DSurface(  vector<double> &poly_coefs_x,
                          vector<double> &poly_coefs_y,
                          tLayer &layer_properties,
                          bool keep_regolith,
                          bool use_bounding_polygon,
                          vector<double> bounding_poly_x,
                          vector<double> bounding_poly_y )
{
  tLNode * cn;
  tMesh<tLNode>::nodeListIter_t ni( meshPtr_->getNodeList() );

  for( cn = ni.FirstP(); ni.IsActive(); cn = ni.NextP() )
  {
    bool layer_is_present_here = true;
    if( use_bounding_polygon )
      if( !PointInPolygon( bounding_poly_x, bounding_poly_y, cn->getX(), cn->getY() ) )
         layer_is_present_here = false;
    if( layer_is_present_here )
    {
      double x = cn->getX();
      double y = cn->getY();
      double new_layer_base_height = poly_coefs_x[0]*x*x*x +
                              poly_coefs_x[1]*x*x +
                              poly_coefs_x[2]*x +
                              poly_coefs_x[3] +
                              poly_coefs_y[0]*y*y*y +
                              poly_coefs_y[1]*y*y +
                              poly_coefs_y[2]*y +
                              poly_coefs_y[3];
      if( new_layer_base_height < cn->getZ() )
        EtchLayerAboveHeightAtNode( new_layer_base_height, cn, layer_properties, keep_regolith );
    }
  }

}

/**************************************************************************/
/**
 */
/**************************************************************************/

<|endoftext|>


<commit_before>/**********************************************************************
 * $Id$
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.refractions.net
 *
 * Copyright (C) 2006 Refractions Research Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 *
 * Last port: geom/util/GeometryTransformer.java rev. 1.6 (JTS-1.7.1+)
 *
 **********************************************************************/

#include <geos/geom/util/GeometryTransformer.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/CoordinateSequenceFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/MultiPoint.h>
#include <geos/geom/MultiPolygon.h>
#include <geos/geom/MultiLineString.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/Point.h>
#include <geos/geom/LineString.h>
#include <geos/geom/LinearRing.h>
#include <geos/geom/GeometryCollection.h>
#include <geos/util/IllegalArgumentException.h>
#include <geos/util.h>

#include <typeinfo>
#include <cassert>

#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif

#ifdef GEOS_DEBUG
#include <iostream>
#endif

using namespace std;

namespace geos {
namespace geom { // geos.geom
namespace util { // geos.geom.util

/*public*/
GeometryTransformer::GeometryTransformer()
	:
	factory(NULL),
	inputGeom(NULL),
	pruneEmptyGeometry(true),
	preserveGeometryCollectionType(true),
	preserveCollections(false),
	preserveType(false)
{}

GeometryTransformer::~GeometryTransformer()
{
}

/*public*/
auto_ptr<Geometry>
GeometryTransformer::transform(const Geometry* nInputGeom)
{
	using geos::util::IllegalArgumentException;

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transform(Geometry " << nInputGeom << ");" << std::endl;
#endif

	inputGeom = nInputGeom;
	factory = inputGeom->getFactory();

	if ( const Point* p=dynamic_cast<const Point*>(inputGeom) )
		return transformPoint(p, NULL);
	if ( const MultiPoint* mp=dynamic_cast<const MultiPoint*>(inputGeom) )
		return transformMultiPoint(mp, NULL);
	if ( const LinearRing* lr=dynamic_cast<const LinearRing*>(inputGeom) )
		return transformLinearRing(lr, NULL);
	if ( const LineString* ls=dynamic_cast<const LineString*>(inputGeom) )
		return transformLineString(ls, NULL);
	if ( const MultiLineString* mls=dynamic_cast<const MultiLineString*>(inputGeom) )
		return transformMultiLineString(mls, NULL);
	if ( const Polygon* p=dynamic_cast<const Polygon*>(inputGeom) )
		return transformPolygon(p, NULL);
	if ( const MultiPolygon* mp=dynamic_cast<const MultiPolygon*>(inputGeom) )
		return transformMultiPolygon(mp, NULL);
	if ( const GeometryCollection* gc=dynamic_cast<const GeometryCollection*>(inputGeom) )
		return transformGeometryCollection(gc, NULL);

	throw IllegalArgumentException("Unknown Geometry subtype.");
}

std::auto_ptr<CoordinateSequence>
GeometryTransformer::createCoordinateSequence(
		std::auto_ptr< std::vector<Coordinate> > coords)
{
	return std::auto_ptr<CoordinateSequence>(
		factory->getCoordinateSequenceFactory()->create(
				coords.release())
	);
}

std::auto_ptr<CoordinateSequence>
GeometryTransformer::transformCoordinates(
		const CoordinateSequence* coords,
		const Geometry* parent)
{

    UNREFERENCED_PARAMETER(parent);
#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformCoordinates(CoordinateSequence " << coords <<", Geometry " << parent << ");" << std::endl;
#endif

	return std::auto_ptr<CoordinateSequence>(coords->clone());
}

Geometry::AutoPtr
GeometryTransformer::transformPoint(
		const Point* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformPoint(Point " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	CoordinateSequence::AutoPtr cs(transformCoordinates(
		geom->getCoordinatesRO(), geom));

	return Geometry::AutoPtr(factory->createPoint(cs.release()));
}

Geometry::AutoPtr
GeometryTransformer::transformMultiPoint(
		const MultiPoint* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformMultiPoint(MultiPoint " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	vector<Geometry*>* transGeomList = new vector<Geometry*>();

	for (unsigned int i=0, n=geom->getNumGeometries(); i<n; i++)
	{
		assert(dynamic_cast<const Point*>(geom->getGeometryN(i)));
		const Point* p = static_cast<const Point*>(
				geom->getGeometryN(i));

		Geometry::AutoPtr transformGeom = transformPoint(p, geom);
		if ( transformGeom.get() == NULL ) continue;
		if ( transformGeom->isEmpty() ) continue;

		// If an exception is thrown we'll leak
		transGeomList->push_back(transformGeom.release());
	}

	return Geometry::AutoPtr(factory->buildGeometry(transGeomList));

}

Geometry::AutoPtr
GeometryTransformer::transformLinearRing(
		const LinearRing* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformLinearRing(LinearRing " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	CoordinateSequence::AutoPtr seq(transformCoordinates(
		geom->getCoordinatesRO(), geom));

	unsigned int seqSize = seq->size();

	// ensure a valid LinearRing
	if ( seqSize > 0 && seqSize < 4 && ! preserveType )
	{
		return factory->createLineString(seq);
	}

	return factory->createLinearRing(seq);

}

Geometry::AutoPtr
GeometryTransformer::transformLineString(
		const LineString* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformLineString(LineString " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	// should check for 1-point sequences and downgrade them to points
	return factory->createLineString(
		transformCoordinates(geom->getCoordinatesRO(), geom));
}

Geometry::AutoPtr
GeometryTransformer::transformMultiLineString(
		const MultiLineString* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformMultiLineString(MultiLineString " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	vector<Geometry*>* transGeomList = new vector<Geometry*>();

	for (unsigned int i=0, n=geom->getNumGeometries(); i<n; i++)
	{
		assert(dynamic_cast<const LineString*>(geom->getGeometryN(i)));
		const LineString* l = static_cast<const LineString*>(
				geom->getGeometryN(i));

		Geometry::AutoPtr transformGeom = transformLineString(l, geom);
		if ( transformGeom.get() == NULL ) continue;
		if ( transformGeom->isEmpty() ) continue;

		// If an exception is thrown we'll leak
		transGeomList->push_back(transformGeom.release());
	}

	return Geometry::AutoPtr(factory->buildGeometry(transGeomList));

}

Geometry::AutoPtr
GeometryTransformer::transformPolygon(
		const Polygon* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformPolygon(Polygon " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	bool isAllValidLinearRings = true;

	assert(dynamic_cast<const LinearRing*>(geom->getExteriorRing()));
	const LinearRing* lr = static_cast<const LinearRing*>(
			geom->getExteriorRing());

	Geometry::AutoPtr shell = transformLinearRing(lr, geom);
	if ( shell.get() == NULL
		|| ! dynamic_cast<LinearRing*>(shell.get())
		|| shell->isEmpty() )
	{
		isAllValidLinearRings = false;
	}

	vector<Geometry*>* holes = new vector<Geometry*>();
	for (unsigned int i=0, n=geom->getNumInteriorRing(); i<n; i++)
	{
		assert(dynamic_cast<const LinearRing*>(
			geom->getInteriorRingN(i)));
		const LinearRing* lr = static_cast<const LinearRing*>(
			geom->getInteriorRingN(i));

		Geometry::AutoPtr hole(transformLinearRing(lr, geom));

		if ( hole.get() == NULL || hole->isEmpty() ) {
			continue;
		}

		if ( ! dynamic_cast<LinearRing*>(hole.get()) )
		{
			isAllValidLinearRings = false;
		}

		holes->push_back(hole.release());
	}

	if ( isAllValidLinearRings)
	{
		Geometry* sh = shell.release();
		assert(dynamic_cast<LinearRing*>(sh));
		return Geometry::AutoPtr(factory->createPolygon(
			static_cast<LinearRing*>(sh),
			holes));
	}
	else
	{
		// would like to use a manager constructor here
		vector<Geometry*>* components = new vector<Geometry*>();
		if ( shell.get() != NULL ) {
			components->push_back(shell.release());
		}

		components->insert(components->end(),
			holes->begin(), holes->end());

		delete holes; // :(

		return Geometry::AutoPtr(factory->buildGeometry(components));
	}

}

Geometry::AutoPtr
GeometryTransformer::transformMultiPolygon(
		const MultiPolygon* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformMultiPolygon(MultiPolygon " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	vector<Geometry*>* transGeomList = new vector<Geometry*>();

	for (unsigned int i=0, n=geom->getNumGeometries(); i<n; i++)
	{
		assert(dynamic_cast<const Polygon*>(geom->getGeometryN(i)));
		const Polygon* p = static_cast<const Polygon*>(
				geom->getGeometryN(i));

		Geometry::AutoPtr transformGeom = transformPolygon(p, geom);
		if ( transformGeom.get() == NULL ) continue;
		if ( transformGeom->isEmpty() ) continue;

		// If an exception is thrown we'll leak
		transGeomList->push_back(transformGeom.release());
	}

	return Geometry::AutoPtr(factory->buildGeometry(transGeomList));

}

Geometry::AutoPtr
GeometryTransformer::transformGeometryCollection(
		const GeometryCollection* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformGeometryCollection(GeometryCollection " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	vector<Geometry*>* transGeomList = new vector<Geometry*>();

	for (unsigned int i=0, n=geom->getNumGeometries(); i<n; i++)
	{
		Geometry::AutoPtr transformGeom = transform(
			geom->getGeometryN(i)); // no parent ?
		if ( transformGeom.get() == NULL ) continue;
		if ( pruneEmptyGeometry && transformGeom->isEmpty() ) continue;

		// If an exception is thrown we'll leak
		transGeomList->push_back(transformGeom.release());
	}

	if ( preserveGeometryCollectionType )
	{
		return Geometry::AutoPtr(factory->createGeometryCollection(
			transGeomList));
	}
	else
	{
		return Geometry::AutoPtr(factory->buildGeometry(transGeomList));
	}

}

} // namespace geos.geom.util
} // namespace geos.geom
} // namespace geos

/**********************************************************************
 * $Log$
 * Revision 1.3  2006/06/19 21:20:22  strk
 * updated port info
 *
 * Revision 1.2  2006/04/11 16:04:34  strk
 * geos::simplify::DouglasPeukerSimplifier class + unit test
 *
 * Revision 1.1  2006/04/11 12:21:48  strk
 * GeometryTransformer class ported
 *
 **********************************************************************/

<commit_msg>Fix memory leak on exception<commit_after>/**********************************************************************
 * $Id$
 *
 * GEOS - Geometry Engine Open Source
 * http://geos.refractions.net
 *
 * Copyright (C) 2006 Refractions Research Inc.
 *
 * This is free software; you can redistribute and/or modify it under
 * the terms of the GNU Lesser General Public Licence as published
 * by the Free Software Foundation.
 * See the COPYING file for more information.
 *
 **********************************************************************
 *
 * Last port: geom/util/GeometryTransformer.java rev. 1.6 (JTS-1.7.1+)
 *
 **********************************************************************/

#include <geos/geom/util/GeometryTransformer.h>
#include <geos/geom/GeometryFactory.h>
#include <geos/geom/CoordinateSequenceFactory.h>
#include <geos/geom/Geometry.h>
#include <geos/geom/MultiPoint.h>
#include <geos/geom/MultiPolygon.h>
#include <geos/geom/MultiLineString.h>
#include <geos/geom/CoordinateSequence.h>
#include <geos/geom/Polygon.h>
#include <geos/geom/Point.h>
#include <geos/geom/LineString.h>
#include <geos/geom/LinearRing.h>
#include <geos/geom/GeometryCollection.h>
#include <geos/util/IllegalArgumentException.h>
#include <geos/util.h>

#include <typeinfo>
#include <cassert>

#ifndef GEOS_DEBUG
#define GEOS_DEBUG 0
#endif

#ifdef GEOS_DEBUG
#include <iostream>
#endif

using namespace std;

namespace geos {
namespace geom { // geos.geom
namespace util { // geos.geom.util

/*public*/
GeometryTransformer::GeometryTransformer()
	:
	factory(NULL),
	inputGeom(NULL),
	pruneEmptyGeometry(true),
	preserveGeometryCollectionType(true),
	preserveCollections(false),
	preserveType(false)
{}

GeometryTransformer::~GeometryTransformer()
{
}

/*public*/
auto_ptr<Geometry>
GeometryTransformer::transform(const Geometry* nInputGeom)
{
	using geos::util::IllegalArgumentException;

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transform(Geometry " << nInputGeom << ");" << std::endl;
#endif

	inputGeom = nInputGeom;
	factory = inputGeom->getFactory();

	if ( const Point* p=dynamic_cast<const Point*>(inputGeom) )
		return transformPoint(p, NULL);
	if ( const MultiPoint* mp=dynamic_cast<const MultiPoint*>(inputGeom) )
		return transformMultiPoint(mp, NULL);
	if ( const LinearRing* lr=dynamic_cast<const LinearRing*>(inputGeom) )
		return transformLinearRing(lr, NULL);
	if ( const LineString* ls=dynamic_cast<const LineString*>(inputGeom) )
		return transformLineString(ls, NULL);
	if ( const MultiLineString* mls=dynamic_cast<const MultiLineString*>(inputGeom) )
		return transformMultiLineString(mls, NULL);
	if ( const Polygon* p=dynamic_cast<const Polygon*>(inputGeom) )
		return transformPolygon(p, NULL);
	if ( const MultiPolygon* mp=dynamic_cast<const MultiPolygon*>(inputGeom) )
		return transformMultiPolygon(mp, NULL);
	if ( const GeometryCollection* gc=dynamic_cast<const GeometryCollection*>(inputGeom) )
		return transformGeometryCollection(gc, NULL);

	throw IllegalArgumentException("Unknown Geometry subtype.");
}

std::auto_ptr<CoordinateSequence>
GeometryTransformer::createCoordinateSequence(
		std::auto_ptr< std::vector<Coordinate> > coords)
{
	return std::auto_ptr<CoordinateSequence>(
		factory->getCoordinateSequenceFactory()->create(
				coords.release())
	);
}

std::auto_ptr<CoordinateSequence>
GeometryTransformer::transformCoordinates(
		const CoordinateSequence* coords,
		const Geometry* parent)
{

    UNREFERENCED_PARAMETER(parent);
#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformCoordinates(CoordinateSequence " << coords <<", Geometry " << parent << ");" << std::endl;
#endif

	return std::auto_ptr<CoordinateSequence>(coords->clone());
}

Geometry::AutoPtr
GeometryTransformer::transformPoint(
		const Point* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformPoint(Point " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	CoordinateSequence::AutoPtr cs(transformCoordinates(
		geom->getCoordinatesRO(), geom));

	return Geometry::AutoPtr(factory->createPoint(cs.release()));
}

Geometry::AutoPtr
GeometryTransformer::transformMultiPoint(
		const MultiPoint* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformMultiPoint(MultiPoint " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	vector<Geometry*>* transGeomList = new vector<Geometry*>();

	for (unsigned int i=0, n=geom->getNumGeometries(); i<n; i++)
	{
		assert(dynamic_cast<const Point*>(geom->getGeometryN(i)));
		const Point* p = static_cast<const Point*>(
				geom->getGeometryN(i));

		Geometry::AutoPtr transformGeom = transformPoint(p, geom);
		if ( transformGeom.get() == NULL ) continue;
		if ( transformGeom->isEmpty() ) continue;

		// If an exception is thrown we'll leak
		transGeomList->push_back(transformGeom.release());
	}

	return Geometry::AutoPtr(factory->buildGeometry(transGeomList));

}

Geometry::AutoPtr
GeometryTransformer::transformLinearRing(
		const LinearRing* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformLinearRing(LinearRing " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	CoordinateSequence::AutoPtr seq(transformCoordinates(
		geom->getCoordinatesRO(), geom));

	unsigned int seqSize = seq->size();

	// ensure a valid LinearRing
	if ( seqSize > 0 && seqSize < 4 && ! preserveType )
	{
		return factory->createLineString(seq);
	}

	return factory->createLinearRing(seq);

}

Geometry::AutoPtr
GeometryTransformer::transformLineString(
		const LineString* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformLineString(LineString " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	// should check for 1-point sequences and downgrade them to points
	return factory->createLineString(
		transformCoordinates(geom->getCoordinatesRO(), geom));
}

Geometry::AutoPtr
GeometryTransformer::transformMultiLineString(
		const MultiLineString* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformMultiLineString(MultiLineString " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	vector<Geometry*>* transGeomList = new vector<Geometry*>();

	for (unsigned int i=0, n=geom->getNumGeometries(); i<n; i++)
	{
		assert(dynamic_cast<const LineString*>(geom->getGeometryN(i)));
		const LineString* l = static_cast<const LineString*>(
				geom->getGeometryN(i));

		Geometry::AutoPtr transformGeom = transformLineString(l, geom);
		if ( transformGeom.get() == NULL ) continue;
		if ( transformGeom->isEmpty() ) continue;

		// If an exception is thrown we'll leak
		transGeomList->push_back(transformGeom.release());
	}

	return Geometry::AutoPtr(factory->buildGeometry(transGeomList));

}

Geometry::AutoPtr
GeometryTransformer::transformPolygon(
		const Polygon* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformPolygon(Polygon " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	bool isAllValidLinearRings = true;

	assert(dynamic_cast<const LinearRing*>(geom->getExteriorRing()));
	const LinearRing* lr = static_cast<const LinearRing*>(
			geom->getExteriorRing());

	Geometry::AutoPtr shell = transformLinearRing(lr, geom);
	if ( shell.get() == NULL
		|| ! dynamic_cast<LinearRing*>(shell.get())
		|| shell->isEmpty() )
	{
		isAllValidLinearRings = false;
	}

	vector<Geometry*>* holes = new vector<Geometry*>();
	for (unsigned int i=0, n=geom->getNumInteriorRing(); i<n; i++)
	{
		assert(dynamic_cast<const LinearRing*>(
			geom->getInteriorRingN(i)));
		const LinearRing* lr = static_cast<const LinearRing*>(
			geom->getInteriorRingN(i));

		Geometry::AutoPtr hole(transformLinearRing(lr, geom));

		if ( hole.get() == NULL || hole->isEmpty() ) {
			continue;
		}

		if ( ! dynamic_cast<LinearRing*>(hole.get()) )
		{
			isAllValidLinearRings = false;
		}

		holes->push_back(hole.release());
	}

	if ( isAllValidLinearRings)
	{
		Geometry* sh = shell.release();
		assert(dynamic_cast<LinearRing*>(sh));
		return Geometry::AutoPtr(factory->createPolygon(
			static_cast<LinearRing*>(sh),
			holes));
	}
	else
	{
		// would like to use a manager constructor here
		vector<Geometry*>* components = new vector<Geometry*>();
		if ( shell.get() != NULL ) {
			components->push_back(shell.release());
		}

		components->insert(components->end(),
			holes->begin(), holes->end());

		delete holes; // :(

		return Geometry::AutoPtr(factory->buildGeometry(components));
	}

}

Geometry::AutoPtr
GeometryTransformer::transformMultiPolygon(
		const MultiPolygon* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformMultiPolygon(MultiPolygon " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	auto_ptr< vector<Geometry*> > transGeomList( new vector<Geometry*>() );

	for (unsigned int i=0, n=geom->getNumGeometries(); i<n; i++)
	{
		assert(dynamic_cast<const Polygon*>(geom->getGeometryN(i)));
		const Polygon* p = static_cast<const Polygon*>(
				geom->getGeometryN(i));

		Geometry::AutoPtr transformGeom = transformPolygon(p, geom);
		if ( transformGeom.get() == NULL ) continue;
		if ( transformGeom->isEmpty() ) continue;

		// If an exception is thrown we'll leak
		transGeomList->push_back(transformGeom.release());
	}

	return Geometry::AutoPtr(factory->buildGeometry(transGeomList.release()));

}

Geometry::AutoPtr
GeometryTransformer::transformGeometryCollection(
		const GeometryCollection* geom,
		const Geometry* parent)
{
    UNREFERENCED_PARAMETER(parent);

#if GEOS_DEBUG
	std::cerr << "GeometryTransformer::transformGeometryCollection(GeometryCollection " << geom <<", Geometry " << parent << ");" << std::endl;
#endif

	vector<Geometry*>* transGeomList = new vector<Geometry*>();

	for (unsigned int i=0, n=geom->getNumGeometries(); i<n; i++)
	{
		Geometry::AutoPtr transformGeom = transform(
			geom->getGeometryN(i)); // no parent ?
		if ( transformGeom.get() == NULL ) continue;
		if ( pruneEmptyGeometry && transformGeom->isEmpty() ) continue;

		// If an exception is thrown we'll leak
		transGeomList->push_back(transformGeom.release());
	}

	if ( preserveGeometryCollectionType )
	{
		return Geometry::AutoPtr(factory->createGeometryCollection(
			transGeomList));
	}
	else
	{
		return Geometry::AutoPtr(factory->buildGeometry(transGeomList));
	}

}

} // namespace geos.geom.util
} // namespace geos.geom
} // namespace geos

/**********************************************************************
 * $Log$
 * Revision 1.3  2006/06/19 21:20:22  strk
 * updated port info
 *
 * Revision 1.2  2006/04/11 16:04:34  strk
 * geos::simplify::DouglasPeukerSimplifier class + unit test
 *
 * Revision 1.1  2006/04/11 12:21:48  strk
 * GeometryTransformer class ported
 *
 **********************************************************************/

<|endoftext|>


<commit_before>// $Id$
//
//  Copyright (C) 2005-2006 Rational Discovery LLC
//
//   @@ All Rights Reserved  @@
//
#define PY_ARRAY_UNIQUE_SYMBOL rdshapehelpers_array_API
#include <boost/python.hpp>
#include "Numeric/arrayobject.h"
#include <GraphMol/ROMol.h>
#include <RDBoost/Wrap.h>

#include <Geometry/Transform3D.h>
#include <Geometry/UniformGrid3D.h>

#include <GraphMol/ShapeHelpers/ShapeEncoder.h>
#include <GraphMol/ShapeHelpers/ShapeUtils.h>
#include <DataStructs/DiscreteValueVect.h>
#include <Geometry/point.h>

namespace python = boost::python;

namespace RDKit {
  void _copyTransform(const PyArrayObject *transMat, RDGeom::Transform3D &trans) {
    unsigned int nrows = transMat->dimensions[0];
    unsigned int ncols = transMat->dimensions[1];
    if ((nrows != 4) || (ncols != 4)) {
      throw_value_error("The transform has to be square matrix, of size 4x4");
    }
    if (transMat->descr->type_num != PyArray_DOUBLE)
      throw_value_error("Only double arrays allowed for transform object ");

    unsigned int dSize = nrows*nrows;
    const double *inData = reinterpret_cast<const double *>(transMat->data);
    double *tData  = trans.getData();
    memcpy(static_cast<void *>(tData), static_cast<const void *>(inData), dSize*sizeof(double));
  }

  python::tuple getConformerDimsAndOffset(const Conformer &conf, python::object trans=python::object(),
                                          double padding=2.5) {
    RDGeom::Point3D dims, offSet;
    PyObject *transObj = trans.ptr();
    if (PyArray_Check(transObj)) {
      PyArrayObject *transMat = reinterpret_cast<PyArrayObject *>(transObj);
      RDGeom::Transform3D ctrans;
      _copyTransform(transMat, ctrans);
      MolShapes::computeConfDimsAndOffset(conf, dims, offSet, &ctrans, padding);
    } else {
      MolShapes::computeConfDimsAndOffset(conf, dims, offSet, 0, padding);
    }

    python::tuple res = python::make_tuple(dims, offSet);
    return res;
  }

  python::tuple getConfBox(const Conformer &conf, python::object trans=python::object(),
                           double padding=2.5) {
    RDGeom::Point3D lowerCorner, upperCorner;
    PyObject *transObj = trans.ptr();
    if (PyArray_Check(transObj)) {
      PyArrayObject *transMat = reinterpret_cast<PyArrayObject *>(transObj);
      RDGeom::Transform3D ctrans;
      _copyTransform(transMat, ctrans);
      MolShapes::computeConfBox(conf, lowerCorner, upperCorner, &ctrans, padding);
    } else {
      MolShapes::computeConfBox(conf, lowerCorner, upperCorner, 0, padding);
    }
    python::tuple res = python::make_tuple(lowerCorner, upperCorner);
    return res;
  }

  python::tuple getUnionOfTwoBox(python::tuple box1, python::tuple box2) {
    unsigned int len1 = python::extract<unsigned int>(box1.attr("__len__")());
    unsigned int len2 = python::extract<unsigned int>(box2.attr("__len__")());
    if ((len1 != 2) || (len2 != 2)) {
      throw_value_error("In correct format for one of the box: expecting a tuple of two Point3D");
    }
    RDGeom::Point3D lC1 = python::extract<RDGeom::Point3D>(box1.attr("__getitem__")(0));
    RDGeom::Point3D uC1 = python::extract<RDGeom::Point3D>(box1.attr("__getitem__")(1));

    RDGeom::Point3D lC2 = python::extract<RDGeom::Point3D>(box2.attr("__getitem__")(0));
    RDGeom::Point3D uC2 = python::extract<RDGeom::Point3D>(box2.attr("__getitem__")(1));

    RDGeom::Point3D lowerCorner, upperCorner;
    MolShapes::computeUnionBox(lC1, uC1, lC2, uC2, lowerCorner, upperCorner);
    python::tuple res = python::make_tuple(lowerCorner, upperCorner);
    return res;
  }

  void EncodeMolShape(const ROMol &mol, RDGeom::UniformGrid3D &grid,
                      int confId=-1, python::object trans=python::object(), //PyObject *trans=0,
                      double vdwScale=0.8, double stepSize=0.25,
                      int maxLayers=-1, bool ignoreHs=true) {
    PyObject *transObj = trans.ptr();

    if (PyArray_Check(transObj)) {
      PyArrayObject *transMat = reinterpret_cast<PyArrayObject *>(transObj);
      RDGeom::Transform3D ctrans;
      _copyTransform(transMat, ctrans);
      MolShapes::EncodeShape(mol, grid, confId, &ctrans, vdwScale, stepSize, maxLayers, ignoreHs);
    } else {
      MolShapes::EncodeShape(mol, grid, confId, 0, vdwScale, stepSize, maxLayers, ignoreHs);
    }
  }

  double tanimotoMolShapes(const ROMol &mol1, const ROMol &mol2, int confId1=-1, int confId2=-1,
                           double gridSpacing=0.5,
                           DiscreteValueVect::DiscreteValueType bitsPerPoint=DiscreteValueVect::TWOBITVALUE,
                           double vdwScale=0.8, double stepSize=0.25, int maxLayers=-1, bool ignoreHs=true) {
    return MolShapes::tanimotoDistance(mol1, mol2, confId1, confId2, gridSpacing, bitsPerPoint,
                                       vdwScale, stepSize, maxLayers, ignoreHs);
  }
}

BOOST_PYTHON_MODULE(rdShapeHelpers) {
  python::scope().attr("__doc__") =
    "Module containing functions to encode ans compre the shapes of molecules"
    ;

  import_array();

  //RegisterListConverter<RDKit::Atom*>();

  std::string docString = "Encode the shape of a molecule (one of it conformer) onto a grid\n\n\
 \n\
 ARGUMENTS:\n\n\
    - mol : the molecule of interest\n\
    - grid : grid onto which the encoding is written \n\
    - confId : id of the conformation of interest on mol (defaults to the first one) \n\
    - trans : any transformation that needs to be used to encode onto the grid (note the molecule remain unchanged) \n\
    - vdwScale : Scaling factor for the radius of the atoms to determine the base radius \n\
                 used in the encoding - grid points inside this sphere carry the maximum occupany \n\
    - setpSize : thickness of the layers outside the base radius, the occupancy value is decreased \n\
                 from layer to layer from the maximum value \n\
    - maxLayers : the maximum number of layers - defaults to the number allowed the number of bits \n\
                  use per grid point - e.g. two bits per grid point will allow 3 layers\n";
  python::def("EncodeShape", RDKit::EncodeMolShape,
              (python::arg("mol"), python::arg("grid"),
               python::arg("confId")=-1, python::arg("trans")=python::object(),
               python::arg("vdwScale")=0.8, python::arg("stepSize")=0.25,
               python::arg("maxLayers")=-1, python::arg("ignoreHs")=true),
              docString.c_str());

  docString = "Compute the shape tanimoto distance between two molecule based on a predefined alignment\n\
  \n\
  ARGUMENTS:\n\
    - mol1 : The first molecule of interest \n\
    - mol2 : The second molecule of interest \n\
    - confId1 : Conformer in the first molecule (defaults to first conformer) \n\
    - confId2 : Conformer in the second molecule (defaults to first conformer) \n\
    - gridSpacing : resolution of the grid used to encode the molecular shapes \n\
    - bitsPerPoint : number of bit used to encode the occupancy at each grid point \n\
                          defaults to two bits per grid point \n\
    - vdwScale : Scaling factor for the radius of the atoms to determine the base radius \n\
                used in the encoding - grid points inside this sphere carry the maximum occupan \n\
    - stepSize : thickness of the each layer outside the base radius, the occupancy value is decreased \n\
                 from layer to layer from the maximum value \n\
    - maxLayers : the maximum number of layers - defaults to the number allowed the number of bits \n\
                  use per grid point - e.g. two bits per grid point will allow 3 layers \n";
  python::def("ShapeTanimotoDist", RDKit::tanimotoMolShapes,
              (python::arg("mol1"), python::arg("mol2"),
               python::arg("confId1")=-1, python::arg("confId2")=-1,
               python::arg("gridSpacing")=0.5,
               python::arg("bitsPerPoint")=DiscreteValueVect::TWOBITVALUE,
               python::arg("vdwScale")=0.8, python::arg("stepSize")=0.25,
               python::arg("maxLayers")=-1, python::arg("ignoreHs")=true),
              docString.c_str());

  docString = "Compute the size of the box that can fit the conformations, and offset \n\
   of the box from the origin\n";
  python::def("ComputeConfDimsAndOffset", RDKit::getConformerDimsAndOffset,
              (python::arg("conf"), python::arg("trans")=python::object(),
               python::arg("padding")=2.0), docString.c_str());

  docString = "Compute the lower and upper corners of a cuboid that will fit the conformer";
  python::def("ComputeConfBox", RDKit::getConfBox,
              (python::arg("conf"), python::arg("trans")=python::object(),
               python::arg("padding")=2.0), docString.c_str());

  docString = "Compute the union of two boxes, so that all the points in both boxes are \n\
    contain in the new box";
  python::def("ComputeUnionBox", RDKit::getUnionOfTwoBox, docString.c_str());

}

<commit_msg>fix the build<commit_after>// $Id$
//
//  Copyright (C) 2005-2006 Rational Discovery LLC
//
//   @@ All Rights Reserved  @@
//
#define PY_ARRAY_UNIQUE_SYMBOL rdshapehelpers_array_API
#include <boost/python.hpp>
#include "Numeric/arrayobject.h"
#include <GraphMol/ROMol.h>
#include <RDBoost/Wrap.h>

#include <Geometry/Transform3D.h>
#include <Geometry/UniformGrid3D.h>

#include <GraphMol/ShapeHelpers/ShapeEncoder.h>
#include <GraphMol/ShapeHelpers/ShapeUtils.h>
#include <DataStructs/DiscreteValueVect.h>
#include <Geometry/point.h>

namespace python = boost::python;

namespace RDKit {
  void _copyTransform(const PyArrayObject *transMat, RDGeom::Transform3D &trans) {
    unsigned int nrows = transMat->dimensions[0];
    unsigned int ncols = transMat->dimensions[1];
    if ((nrows != 4) || (ncols != 4)) {
      throw_value_error("The transform has to be square matrix, of size 4x4");
    }
    if (transMat->descr->type_num != PyArray_DOUBLE)
      throw_value_error("Only double arrays allowed for transform object ");

    unsigned int dSize = nrows*nrows;
    const double *inData = reinterpret_cast<const double *>(transMat->data);
    double *tData  = trans.getData();
    memcpy(static_cast<void *>(tData), static_cast<const void *>(inData), dSize*sizeof(double));
  }

  python::tuple getConformerDimsAndOffset(const Conformer &conf, python::object trans=python::object(),
                                          double padding=2.5) {
    RDGeom::Point3D dims, offSet;
    PyObject *transObj = trans.ptr();
    if (PyArray_Check(transObj)) {
      PyArrayObject *transMat = reinterpret_cast<PyArrayObject *>(transObj);
      RDGeom::Transform3D ctrans;
      _copyTransform(transMat, ctrans);
      MolShapes::computeConfDimsAndOffset(conf, dims, offSet, &ctrans, padding);
    } else {
      MolShapes::computeConfDimsAndOffset(conf, dims, offSet, 0, padding);
    }

    python::tuple res = python::make_tuple(dims, offSet);
    return res;
  }

  python::tuple getConfBox(const Conformer &conf, python::object trans=python::object(),
                           double padding=2.5) {
    RDGeom::Point3D lowerCorner, upperCorner;
    PyObject *transObj = trans.ptr();
    if (PyArray_Check(transObj)) {
      PyArrayObject *transMat = reinterpret_cast<PyArrayObject *>(transObj);
      RDGeom::Transform3D ctrans;
      _copyTransform(transMat, ctrans);
      MolShapes::computeConfBox(conf, lowerCorner, upperCorner, &ctrans, padding);
    } else {
      MolShapes::computeConfBox(conf, lowerCorner, upperCorner, 0, padding);
    }
    python::tuple res = python::make_tuple(lowerCorner, upperCorner);
    return res;
  }

  python::tuple getUnionOfTwoBox(python::tuple box1, python::tuple box2) {
    unsigned int len1 = python::extract<unsigned int>(box1.attr("__len__")());
    unsigned int len2 = python::extract<unsigned int>(box2.attr("__len__")());
    if ((len1 != 2) || (len2 != 2)) {
      throw_value_error("In correct format for one of the box: expecting a tuple of two Point3D");
    }
    RDGeom::Point3D lC1 = python::extract<RDGeom::Point3D>(box1.attr("__getitem__")(0));
    RDGeom::Point3D uC1 = python::extract<RDGeom::Point3D>(box1.attr("__getitem__")(1));

    RDGeom::Point3D lC2 = python::extract<RDGeom::Point3D>(box2.attr("__getitem__")(0));
    RDGeom::Point3D uC2 = python::extract<RDGeom::Point3D>(box2.attr("__getitem__")(1));

    RDGeom::Point3D lowerCorner, upperCorner;
    MolShapes::computeUnionBox(lC1, uC1, lC2, uC2, lowerCorner, upperCorner);
    python::tuple res = python::make_tuple(lowerCorner, upperCorner);
    return res;
  }

  void EncodeMolShape(const ROMol &mol, RDGeom::UniformGrid3D &grid,
                      int confId=-1, python::object trans=python::object(), //PyObject *trans=0,
                      double vdwScale=0.8, double stepSize=0.25,
                      int maxLayers=-1, bool ignoreHs=true) {
    PyObject *transObj = trans.ptr();

    if (PyArray_Check(transObj)) {
      PyArrayObject *transMat = reinterpret_cast<PyArrayObject *>(transObj);
      RDGeom::Transform3D ctrans;
      _copyTransform(transMat, ctrans);
      MolShapes::EncodeShape(mol, grid, confId, &ctrans, vdwScale, stepSize, maxLayers, ignoreHs);
    } else {
      MolShapes::EncodeShape(mol, grid, confId, 0, vdwScale, stepSize, maxLayers, ignoreHs);
    }
  }

  double tanimotoMolShapes(const ROMol &mol1, const ROMol &mol2, int confId1=-1, int confId2=-1,
                           double gridSpacing=0.5,
                           DiscreteValueVect::DiscreteValueType bitsPerPoint=DiscreteValueVect::TWOBITVALUE,
                           double vdwScale=0.8, double stepSize=0.25, int maxLayers=-1, bool ignoreHs=true) {
    return MolShapes::tanimotoDistance(mol1, mol2, confId1, confId2, gridSpacing, bitsPerPoint,
                                       vdwScale, stepSize, maxLayers, ignoreHs);
  }
}

BOOST_PYTHON_MODULE(rdShapeHelpers) {
  python::scope().attr("__doc__") =
    "Module containing functions to encode ans compre the shapes of molecules"
    ;

  import_array();

  //RegisterListConverter<RDKit::Atom*>();

  std::string docString = "Encode the shape of a molecule (one of it conformer) onto a grid\n\n\
 \n\
 ARGUMENTS:\n\n\
    - mol : the molecule of interest\n\
    - grid : grid onto which the encoding is written \n\
    - confId : id of the conformation of interest on mol (defaults to the first one) \n\
    - trans : any transformation that needs to be used to encode onto the grid (note the molecule remain unchanged) \n\
    - vdwScale : Scaling factor for the radius of the atoms to determine the base radius \n\
                 used in the encoding - grid points inside this sphere carry the maximum occupany \n\
    - setpSize : thickness of the layers outside the base radius, the occupancy value is decreased \n\
                 from layer to layer from the maximum value \n\
    - maxLayers : the maximum number of layers - defaults to the number allowed the number of bits \n\
                  use per grid point - e.g. two bits per grid point will allow 3 layers\n";
  python::def("EncodeShape", RDKit::EncodeMolShape,
              (python::arg("mol"), python::arg("grid"),
               python::arg("confId")=-1, python::arg("trans")=python::object(),
               python::arg("vdwScale")=0.8, python::arg("stepSize")=0.25,
               python::arg("maxLayers")=-1, python::arg("ignoreHs")=true),
              docString.c_str());

  docString = "Compute the shape tanimoto distance between two molecule based on a predefined alignment\n\
  \n\
  ARGUMENTS:\n\
    - mol1 : The first molecule of interest \n\
    - mol2 : The second molecule of interest \n\
    - confId1 : Conformer in the first molecule (defaults to first conformer) \n\
    - confId2 : Conformer in the second molecule (defaults to first conformer) \n\
    - gridSpacing : resolution of the grid used to encode the molecular shapes \n\
    - bitsPerPoint : number of bit used to encode the occupancy at each grid point \n\
                          defaults to two bits per grid point \n\
    - vdwScale : Scaling factor for the radius of the atoms to determine the base radius \n\
                used in the encoding - grid points inside this sphere carry the maximum occupan \n\
    - stepSize : thickness of the each layer outside the base radius, the occupancy value is decreased \n\
                 from layer to layer from the maximum value \n\
    - maxLayers : the maximum number of layers - defaults to the number allowed the number of bits \n\
                  use per grid point - e.g. two bits per grid point will allow 3 layers \n";
  python::def("ShapeTanimotoDist", RDKit::tanimotoMolShapes,
              (python::arg("mol1"), python::arg("mol2"),
               python::arg("confId1")=-1, python::arg("confId2")=-1,
               python::arg("gridSpacing")=0.5,
               python::arg("bitsPerPoint")=RDKit::DiscreteValueVect::TWOBITVALUE,
               python::arg("vdwScale")=0.8, python::arg("stepSize")=0.25,
               python::arg("maxLayers")=-1, python::arg("ignoreHs")=true),
              docString.c_str());

  docString = "Compute the size of the box that can fit the conformations, and offset \n\
   of the box from the origin\n";
  python::def("ComputeConfDimsAndOffset", RDKit::getConformerDimsAndOffset,
              (python::arg("conf"), python::arg("trans")=python::object(),
               python::arg("padding")=2.0), docString.c_str());

  docString = "Compute the lower and upper corners of a cuboid that will fit the conformer";
  python::def("ComputeConfBox", RDKit::getConfBox,
              (python::arg("conf"), python::arg("trans")=python::object(),
               python::arg("padding")=2.0), docString.c_str());

  docString = "Compute the union of two boxes, so that all the points in both boxes are \n\
    contain in the new box";
  python::def("ComputeUnionBox", RDKit::getUnionOfTwoBox, docString.c_str());

}

<|endoftext|>


<commit_before>int main(int argc, char *argv[])
{
   // Reads from the file build/version_number the new version
   // number and generates the header base/inc/RVersion.h.
   // To be executed as CINT script by build/unix/makeversion.sh.
   //
   // Author: Fons Rademakers   11/10/99

   const char *in  = "build/version_number";
   const char *inr = "etc/svninfo.txt";

   FILE *fp = fopen(in, "r");
   if (!fp) {
      printf("%s: can not open input file %s\n", argv[0], in);
      exit(1);
   }
   char vers[32];
   fgets(vers, sizeof(vers), fp);
   if (vers[strlen(vers)-1] == '\n') vers[strlen(vers)-1] = 0;
   fclose(fp);

   fp = fopen(inr, "r");
   if (!fp) {
      printf("%s: can not open input file %s\n", argv[0], in);
      exit(1);
   }
   char branch[2048];
   fgets(branch, sizeof(branch), fp);
   if (branch[strlen(branch)-1] == '\n') branch[strlen(branch)-1] = 0;
   char revs[32];
   fgets(revs, sizeof(revs), fp);
   if (revs[strlen(revs)-1] == '\n') revs[strlen(revs)-1] = 0;
   fclose(fp);

   const char *out = "base/inc/RVersion.h";
   fp = fopen(out, "w");
   if (!fp) {
      printf("%s: can not open output file %s\n", argv[0], out);
      exit(1);
   }

   fprintf(fp, "#ifndef ROOT_RVersion\n");
   fprintf(fp, "#define ROOT_RVersion\n\n");
   fprintf(fp, "/* Version information automatically generated by installer. */\n\n");
   fprintf(fp, "/*\n");
   fprintf(fp, " * These macros can be used in the following way:\n");
   fprintf(fp, " *\n");
   fprintf(fp, " *    #if ROOT_VERSION_CODE >= ROOT_VERSION(2,23,4)\n");
   fprintf(fp, " *       #include <newheader.h>\n");
   fprintf(fp, " *    #else\n");
   fprintf(fp, " *       #include <oldheader.h>\n");
   fprintf(fp, " *    #endif\n");
   fprintf(fp, " *\n");
   fprintf(fp, "*/\n\n");

   int xx, yy, zz, rev;
   sscanf(vers, "%d.%d/%d", &xx, &yy, &zz);
   int vers_code = (xx << 16) + (yy << 8) + zz;
   sscanf(revs, "%d", &rev);

   fprintf(fp, "#define ROOT_RELEASE \"%s\"\n", vers);
   fprintf(fp, "#define ROOT_RELEASE_DATE \"%s\"\n", __DATE__);
   fprintf(fp, "#define ROOT_RELEASE_TIME \"%s\"\n", __TIME__);
   fprintf(fp, "#define ROOT_SVN_REVISION %d\n", rev);
   fprintf(fp, "#define ROOT_SVN_BRANCH \"%s\"\n", branch);
   fprintf(fp, "#define ROOT_VERSION_CODE %d\n", vers_code);
   fprintf(fp, "#define ROOT_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))\n");
   fprintf(fp, "\n#endif\n");

   fclose(fp);

   exit(0);
}
<commit_msg>Change to reflect new directory structure<commit_after>int main(int argc, char *argv[])
{
   // Reads from the file build/version_number the new version
   // number and generates the header base/inc/RVersion.h.
   // To be executed as CINT script by build/unix/makeversion.sh.
   //
   // Author: Fons Rademakers   11/10/99

   const char *in  = "build/version_number";
   const char *inr = "etc/svninfo.txt";

   FILE *fp = fopen(in, "r");
   if (!fp) {
      printf("%s: can not open input file %s\n", argv[0], in);
      exit(1);
   }
   char vers[32];
   fgets(vers, sizeof(vers), fp);
   if (vers[strlen(vers)-1] == '\n') vers[strlen(vers)-1] = 0;
   fclose(fp);

   fp = fopen(inr, "r");
   if (!fp) {
      printf("%s: can not open input file %s\n", argv[0], in);
      exit(1);
   }
   char branch[2048];
   fgets(branch, sizeof(branch), fp);
   if (branch[strlen(branch)-1] == '\n') branch[strlen(branch)-1] = 0;
   char revs[32];
   fgets(revs, sizeof(revs), fp);
   if (revs[strlen(revs)-1] == '\n') revs[strlen(revs)-1] = 0;
   fclose(fp);

   const char *out = "core/base/inc/RVersion.h";
   fp = fopen(out, "w");
   if (!fp) {
      printf("%s: can not open output file %s\n", argv[0], out);
      exit(1);
   }

   fprintf(fp, "#ifndef ROOT_RVersion\n");
   fprintf(fp, "#define ROOT_RVersion\n\n");
   fprintf(fp, "/* Version information automatically generated by installer. */\n\n");
   fprintf(fp, "/*\n");
   fprintf(fp, " * These macros can be used in the following way:\n");
   fprintf(fp, " *\n");
   fprintf(fp, " *    #if ROOT_VERSION_CODE >= ROOT_VERSION(2,23,4)\n");
   fprintf(fp, " *       #include <newheader.h>\n");
   fprintf(fp, " *    #else\n");
   fprintf(fp, " *       #include <oldheader.h>\n");
   fprintf(fp, " *    #endif\n");
   fprintf(fp, " *\n");
   fprintf(fp, "*/\n\n");

   int xx, yy, zz, rev;
   sscanf(vers, "%d.%d/%d", &xx, &yy, &zz);
   int vers_code = (xx << 16) + (yy << 8) + zz;
   sscanf(revs, "%d", &rev);

   fprintf(fp, "#define ROOT_RELEASE \"%s\"\n", vers);
   fprintf(fp, "#define ROOT_RELEASE_DATE \"%s\"\n", __DATE__);
   fprintf(fp, "#define ROOT_RELEASE_TIME \"%s\"\n", __TIME__);
   fprintf(fp, "#define ROOT_SVN_REVISION %d\n", rev);
   fprintf(fp, "#define ROOT_SVN_BRANCH \"%s\"\n", branch);
   fprintf(fp, "#define ROOT_VERSION_CODE %d\n", vers_code);
   fprintf(fp, "#define ROOT_VERSION(a,b,c) (((a) << 16) + ((b) << 8) + (c))\n");
   fprintf(fp, "\n#endif\n");

   fclose(fp);

   exit(0);
}
<|endoftext|>