repo_name
stringlengths 6
97
| path
stringlengths 3
341
| text
stringlengths 8
1.02M
|
---|---|---|
agrishutin/teambook | contrib/su4/cpp2tex/include/sql/result.h | <gh_stars>10-100
/*
* This file [sql/result.h] is part of the “libtamias” library
* Copyright (c) 2007-2009 <NAME>, <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Our contacts:
* mailto: <EMAIL> (<NAME>)
* mailto: <EMAIL> (<NAME>)
*/
#pragma once
#include "../basic/types.h"
#include "../basic/string.h"
#include "../sql/driver.h"
#include "../sql/exception.h"
namespace tamias
{
namespace sql
{
class Result
{
private:
Driver *driver;
uinttype32 result, error;
Result( Driver *newDriver, uinttype32 newResult );
public:
Result();
Result( const Result &result );
Result& operator = ( const Result &result );
~Result();
bool next();
String get( sizetype column );
String get( const String &column );
friend class Connection;
};
}
}
|
agrishutin/teambook | contrib/su4/cpp2tex/include/data/map.h | <filename>contrib/su4/cpp2tex/include/data/map.h<gh_stars>10-100
/*
* This file [data/map.h] is part of the “libtamias” library
* Copyright (c) 2007-2010 <NAME>, <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Our contacts:
* mailto: <EMAIL> (<NAME>)
* mailto: <EMAIL> (<NAME>)
*/
#pragma once
namespace tamias {
namespace hidden {
template <typename KeyType, typename ValueType> class MapElement;
}
template <template <typename Type> class CollectionTemplate, typename Key, typename Value> class Map;
}
#include "../basic/types.h"
#include "../data/pair.h"
template <typename KeyType, typename ValueType>
class tamias::hidden::MapElement : public Pair <KeyType, ValueType> {
public:
MapElement();
MapElement( KeyType const &key, ValueType const &value );
MapElement( MapElement <KeyType, ValueType> const &element );
MapElement& operator = ( MapElement <KeyType, ValueType> const &element );
~MapElement();
bool operator < ( const MapElement<KeyType, ValueType> &element ) const;
};
template <template <typename Type> class CollectionTemplate, typename Key, typename Value>
class tamias::Map {
public:
typedef typename CollectionTemplate<hidden::MapElement <Key, Value> >::Iterator Iterator;
typedef typename CollectionTemplate<hidden::MapElement <Key, Value> >::ConstIterator ConstIterator;
// TODO: reverse iterators
public:
Map();
Map( Map <CollectionTemplate, Key, Value> const &map );
Map& operator = ( Map <CollectionTemplate, Key, Value> const &map );
~Map();
sizetype size() const;
Value& operator [] ( Key const &key );
Value const& operator [] ( Key const &key ) const;
sizetype count( Key const &key ) const;
void erase( Key const &key );
Iterator begin();
Iterator end();
ConstIterator begin() const;
ConstIterator end() const;
void clear();
private:
CollectionTemplate <hidden::MapElement <Key, Value> > collection;
Value empty;
};
#include "map_implementation.h"
|
agrishutin/teambook | contrib/su4/cpp2tex/include/data/vector_implementation.h | /*
* This file [data/vector_implementation.h] is part of the “libtamias” library
* Copyright (c) 2007-2010 <NAME>, <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Our contacts:
* mailto: <EMAIL> (<NAME>)
* mailto: <EMAIL> (<NAME>)
*/
template <typename Type>
tamias::Vector<Type>::Vector() : tamias::hidden::AbstractData(0), mSize(0)
{
}
template <typename Type>
tamias::Vector<Type>::Vector( sizetype initialSize, Type const &value ) : hidden::AbstractData(initialSize * sizeof(Type)), mSize(initialSize)
{
for (sizetype i = 0; i < initialSize; i++)
new ((Type*)data() + i) Type(value);
}
template <typename Type>
tamias::Vector<Type>::Vector( Vector <Type> const &vector ) : hidden::AbstractData(vector.mSize * sizeof(Type)), mSize(vector.mSize)
{
for (sizetype i = 0; i < mSize; i++)
new ((Type*)data() + i) Type(vector[i]);
}
template <typename Type>
tamias::Vector<Type>& tamias::Vector<Type>::operator = ( Vector const &vector )
{
for (sizetype i = 0; i < mSize; i++)
(*this)[i].~Type();
mSize = vector.mSize;
manualReserve(mSize * sizeof(Type));
for (sizetype i = 0; i < mSize; i++)
new ((Type*)data() + i) Type(vector[i]);
return *this;
}
template <typename Type>
tamias::Vector<Type>::~Vector()
{
for (sizetype i = 0; i < mSize; i++)
(*this)[i].~Type();
}
template <typename Type>
tamias::sizetype tamias::Vector<Type>::size() const
{
return mSize;
}
template <typename Type>
typename tamias::Vector<Type>::Reference tamias::Vector<Type>::operator [] ( sizetype index )
{
utilities::assert<OutOfBoundsException>(index < mSize);
return ((Type*)data())[index];
}
template <typename Type>
typename tamias::Vector<Type>::ConstReference tamias::Vector<Type>::operator [] ( sizetype index ) const
{
utilities::assert<OutOfBoundsException>(index < mSize);
return ((Type*)data())[index];
}
template <typename Type>
typename tamias::Vector<Type>::Iterator tamias::Vector<Type>::begin()
{
return Iterator((Type*)data());
}
template <typename Type>
typename tamias::Vector<Type>::Iterator tamias::Vector<Type>::end()
{
return Iterator((Type*)((Type*)data() + mSize));
}
template <typename Type>
typename tamias::Vector<Type>::ConstIterator tamias::Vector<Type>::begin() const
{
return ConstIterator((Type*)data());
}
template <typename Type>
typename tamias::Vector<Type>::ConstIterator tamias::Vector<Type>::end() const
{
return ConstIterator((Type*)((Type*)data() + mSize));
}
template <typename Type>
typename tamias::Vector<Type>::ReverseIterator tamias::Vector<Type>::rbegin()
{
return ReverseIterator((Type*)data() + mSize - 1);
}
template <typename Type>
typename tamias::Vector<Type>::ReverseIterator tamias::Vector<Type>::rend()
{
return ReverseIterator((Type*)((Type*)data() - 1));
}
template <typename Type>
typename tamias::Vector<Type>::ConstReverseIterator tamias::Vector<Type>::rbegin() const
{
return ConstReverseIterator((Type*)data() + mSize - 1);
}
template <typename Type>
typename tamias::Vector<Type>::ConstReverseIterator tamias::Vector<Type>::rend() const
{
return ConstReverseIterator((Type*)((Type*)data() - 1));
}
template <typename Type>
void tamias::Vector<Type>::clear()
{
for (sizetype i = 0; i < mSize; i++)
(*this)[i].~Type();
mSize = 0;
manualReserve(0);
}
template <typename Type>
void tamias::Vector<Type>::resize( sizetype newSize )
{
for (sizetype i = newSize; i < mSize; i++)
(*this)[i].~Type();
sizetype oldSize = mSize;
mSize = newSize;
manualReserve(mSize * sizeof(Type));
for (sizetype i = oldSize; i < mSize; i++)
new((Type*)data() + i) Type();
}
template <typename Type>
void tamias::Vector<Type>::pushBack( Type const& source )
{
autoReserveUp((mSize + 1) * sizeof(Type));
new ((Type*)data() + mSize++) Type(source);
}
template <typename Type>
tamias::VectorCreator<Type>::VectorCreator() : result()
{
}
template <typename Type>
tamias::VectorCreator<Type>::VectorCreator( Type const &value ) : result(1, value)
{
}
template <typename Type>
tamias::VectorCreator<Type>::VectorCreator( VectorCreator const &creator ) : result(creator.result)
{
}
template <typename Type>
tamias::VectorCreator<Type>& tamias::VectorCreator<Type>::operator = ( VectorCreator const &creator )
{
result = creator.result;
return *this;
}
template <typename Type>
tamias::VectorCreator<Type>::~VectorCreator()
{
}
template <typename Type>
tamias::VectorCreator<Type>& tamias::VectorCreator<Type>::operator () ( Type const &value )
{
result.pushBack(value);
return *this;
}
template <typename Type>
tamias::VectorCreator<Type>& tamias::VectorCreator<Type>::operator << ( Type const &value )
{
result.pushBack(value);
return *this;
}
template <typename Type>
tamias::VectorCreator<Type>::operator tamias::Vector<Type>() const
{
return result;
}
|
agrishutin/teambook | contrib/su4/cpp2tex/include/wtf/bsql.h | /*
* libtamias/wtf/bsql.h — some improvements for sql api
*/
#pragma once
#include <cstdarg> // Hmmm... Wtf?
#include "../basic/exception.h"
#include "../basic/string.h"
#include "../basic/types.h"
#include "../data/pair.h"
#include "../sql/connection.h"
#include "../sql/driver.h"
#include "../sql/result.h"
#include "../main/vector.h"
#include "../wtf/utilities.h"
/*
* Format specification:
* %s — string, argument must be a pointer to tamias::String
* %d — 32-bit signed integer, argument must be an inttype32
* %u — 32-bit unsigned integer, argument must be an uinttype32
* %lld — 64-bit signed integer, argument must be an inttype64
* %llu — 64-bit unsigned integer, argument must be an inttype64
* only %s & %u are implemented now
*/
namespace tamias
{
namespace wtf
{
class BSqlConnection : public tamias::sql::Connection
{
public:
enum LockType
{
LOCKTABLE_READ, LOCKTABLE_WRITE
};
BSqlConnection( tamias::sql::Driver *driver );
BSqlConnection( const BSqlConnection &connection );
~BSqlConnection();
BSqlConnection& operator = ( const BSqlConnection &connection );
tamias::sql::Result query( const tamias::String &queryString, ... );
void lockTables( const Vector <Pair <String, LockType> > &tables );
void unlockTables();
sizetype nextId( const String &tableName, const String &fieldName );
private:
String quoteString( const String &source ) const;
};
}
}
|
agrishutin/teambook | contrib/su4/cpp2tex/include/io/format.h | /*
* This file [io/format.h] is part of the “libtamias” library
* Copyright (c) 2007-2010 <NAME>, <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Our contacts:
* mailto: <EMAIL> (<NAME>)
* mailto: <EMAIL> (<NAME>)
*/
#pragma once
namespace tamias {
class Format;
}
/*
* about conversions
* the generic form is: %<flags><width><precision><modificators><specifier>
* specifiers:
* c — character
* d, i — decimal integer
* e — float number, exponential format
* f — float number, fixed format
* g — float number, automatic format
* o — octal integer
* s — string
* x — hex integer
* % — special, outputs '%' into output stream
*/
#include "../basic/exception.h"
#include "../basic/string.h"
#include "../basic/utilities.h"
#include "../data/pair.h"
#include "../data/vector.h"
class tamias::Format {
public:
Format( String const &format );
Format( Format const &format );
Format& operator = ( Format const &format );
virtual ~Format();
Format& operator << ( int value );
Format& operator << ( long value );
Format& operator << ( long long value );
Format& operator << ( unsigned int value );
Format& operator << ( unsigned long value );
Format& operator << ( unsigned long long value );
Format& operator << ( char value );
Format& operator << ( char const *value );
Format& operator << ( String const &value );
bool ready();
operator String() const;
String output() const;
static String intToString( int value );
static String intToString( long value );
static String intToString( long long value );
static String intToString( unsigned int value );
static String intToString( unsigned long value );
static String intToString( unsigned long long value );
protected:
enum ValueType {
TYPE_ECHO, TYPE_CHARACTER, TYPE_DECIMAL, TYPE_OCTAL, TYPE_HEX, TYPE_FLOAT, TYPE_EXPONENT, TYPE_STRING
};
virtual String handle( ValueType type, String const &spec, int value );
virtual String handle( ValueType type, String const &spec, long value );
virtual String handle( ValueType type, String const &spec, long long value );
virtual String handle( ValueType type, String const &spec, unsigned int value );
virtual String handle( ValueType type, String const &spec, unsigned long value );
virtual String handle( ValueType type, String const &spec, unsigned long long value );
virtual String handle( ValueType type, String const &spec, char value );
virtual String handle( ValueType type, String const &spec, char const *value );
virtual String handle( ValueType type, String const &spec, String const &value );
private:
Vector <Pair <ValueType, String> > mData;
tamias::sizetype mIndex;
void skip();
};
|
agrishutin/teambook | contrib/su4/cpp2tex/include/sql/exception.h | <reponame>agrishutin/teambook
/*
* This file [sql/exception.h] is part of the “libtamias” library
* Copyright (c) 2007-2009 <NAME>, <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Our contacts:
* mailto: <EMAIL> (<NAME>)
* mailto: <EMAIL> (<NAME>)
*/
#pragma once
#include "../basic/exception.h"
#include "../basic/string.h"
namespace tamias
{
namespace sql
{
class SQLException : public Exception
{
public:
enum SQLExceptionType
{
UNKNOWN_EXCEPTION = 0,
CANNOT_LOAD_DRIVER = 1,
DRIVER_EXCEPTION = 2,
RESULT_EMPTY = 3
};
public:
SQLException();
SQLException( SQLExceptionType newType, const String &newComment );
SQLException( const SQLException &exception );
~SQLException();
SQLException& operator = ( const SQLException &exceptoin );
const char* type() const;
const String& report() const;
private:
SQLExceptionType mType;
String mComment;
};
}
}
|
agrishutin/teambook | contrib/su4/cpp2tex/include/data/tree_rbst.h | /*
* This file [data/tree_rbst.h] is part of the “libtamias” library
* Copyright (c) 2007-2010 <NAME>, <NAME>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Our contacts:
* mailto: <EMAIL> (<NAME>)
* mailto: <EMAIL> (<NAME>)
*/
#pragma once
namespace tamias {
namespace hidden {
template <typename KeyType> struct RBSTreeNode;
}
template <typename KeyType> class RBSTree; // http://en.wikipedia.org/wiki/Randomized_binary_search_tree
namespace hidden {
template <typename KeyType> class RBSTreeIterator;
template <typename KeyType> class RBSTreeConstIterator;
}
}
#include "../basic/exception.h"
#include "../basic/types.h"
#include "../main/random_lcg.h" // TODO: setup random and do not make cross-links between sections
template <typename KeyType>
struct tamias::hidden::RBSTreeNode {
KeyType key;
RBSTreeNode *left, *right, *parent;
sizetype size;
RBSTreeNode( KeyType const &newKey = KeyType() );
RBSTreeNode( RBSTreeNode const &node );
RBSTreeNode& operator = ( RBSTreeNode const &node );
~RBSTreeNode();
};
template <typename KeyType>
class tamias::RBSTree {
public:
typedef KeyType* Pointer;
typedef KeyType& Reference;
typedef KeyType const* ConstPointer;
typedef KeyType const& ConstReference;
typedef hidden::RBSTreeIterator<KeyType> Iterator;
typedef hidden::RBSTreeConstIterator<KeyType> ConstIterator;
public:
RBSTree();
RBSTree( RBSTree const &tree );
RBSTree& operator = ( RBSTree const &tree );
~RBSTree();
sizetype size() const;
bool insert( KeyType const &value );
bool erase( KeyType const &value );
Iterator find( KeyType const &value );
ConstIterator find( KeyType const &value ) const;
Iterator findKth( sizetype k );
ConstIterator findKth( sizetype k ) const;
sizetype count( const KeyType &value ) const;
Iterator begin();
Iterator end();
ConstIterator begin() const;
ConstIterator end() const;
void clear();
private:
typedef hidden::RBSTreeNode<KeyType>* TreeReference;
TreeReference root;
LCGRandom random;
void recalc( TreeReference node );
TreeReference merge( TreeReference first, TreeReference second );
bool split( TreeReference root, TreeReference &left, TreeReference &right , KeyType const &splitter );
bool addKey( TreeReference &root, KeyType const &value );
Iterator beginIterator( TreeReference root );
ConstIterator beginIterator( TreeReference root ) const;
Iterator findIterator( TreeReference root, KeyType const &value );
ConstIterator findIterator( TreeReference root, KeyType const &value ) const;
TreeReference findKey( TreeReference root, KeyType const &value );
};
template <typename KeyType>
class tamias::hidden::RBSTreeIterator {
public:
typedef typename RBSTree<KeyType>::Pointer Pointer;
typedef typename RBSTree<KeyType>::Reference Reference;
public:
RBSTreeIterator();
RBSTreeIterator( RBSTreeNode <KeyType> *node );
RBSTreeIterator( RBSTreeIterator const &iterator );
RBSTreeIterator& operator = ( RBSTreeIterator const &iterator );
~RBSTreeIterator();
Reference operator * ();
Pointer operator -> ();
// TODO: all operators
RBSTreeIterator& operator ++ ();
RBSTreeIterator operator ++ ( int );
RBSTreeIterator& operator -- ();
RBSTreeIterator operator -- ( int );
bool operator == ( RBSTreeIterator const &iterator ) const;
bool operator != ( RBSTreeIterator const &iterator ) const;
private:
RBSTreeNode<KeyType> *mNode;
};
template <typename KeyType>
class tamias::hidden::RBSTreeConstIterator {
public:
typedef typename RBSTree<KeyType>::ConstPointer Pointer;
typedef typename RBSTree<KeyType>::ConstReference Reference;
public:
RBSTreeConstIterator();
RBSTreeConstIterator( RBSTreeNode <KeyType> const *node );
RBSTreeConstIterator( RBSTreeConstIterator const &iterator );
RBSTreeConstIterator& operator = ( RBSTreeConstIterator const &iterator );
~RBSTreeConstIterator();
Reference operator * ();
Pointer operator -> ();
RBSTreeConstIterator& operator ++ ();
RBSTreeConstIterator operator ++ ( int );
RBSTreeConstIterator& operator -- ();
RBSTreeConstIterator operator -- ( int );
bool operator == ( const RBSTreeConstIterator &iterator ) const;
bool operator != ( const RBSTreeConstIterator &iterator ) const;
private:
RBSTreeNode<KeyType> const *mNode;
};
#include "tree_rbst_implementation.h"
|
jjcasmar/cgal | Combinatorial_map/include/CGAL/internal/Combinatorial_map_utility.h | <gh_stars>1-10
// Copyright (c) 2010-2011 CNRS and LIRIS' Establishments (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org)
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial
//
// Author(s) : <NAME> <<EMAIL>>
//
#ifndef CGAL_INTERNAL_COMBINATORIAL_MAP_UTILITY_H
#define CGAL_INTERNAL_COMBINATORIAL_MAP_UTILITY_H 1
#include <CGAL/tuple.h>
#include <CGAL/Compact_container.h>
#include <iostream>
#include <boost/type_traits/is_same.hpp>
#include <boost/function.hpp>
#include <boost/mpl/has_xxx.hpp>
/** Some utilities allowing to manage attributes. Indeed, as they as stores
* in tuples, we need to define functors with variadic templated arguments
* to deal with these attributes.
*
* The class Combinatorial_map_helper<CMap> defines:
*
*/
namespace CGAL
{
namespace internal
{
// There is a problem on windows to handle tuple containing void.
// To solve this, we transform such a tuple in tuple containing Void.
template<typename T>
struct Convert_void
{ typedef T type; };
template<>
struct Convert_void<void>
{ typedef CGAL::Void type; };
// Get the type Dart_info defined as inner type of T.
// If T::Dart_info is not defined or if T::Dart_info is void, defined
// CGAL::Void as type.
BOOST_MPL_HAS_XXX_TRAIT_NAMED_DEF(Has_dart_info,Dart_info,false)
template<typename T, bool typedefined=Has_dart_info<T>::value >
struct Get_dart_info
{ typedef CGAL::Void type; };
template<typename T>
struct Get_dart_info<T, true>
{ typedef typename Convert_void<typename T::Dart_info>::type type; };
// Get the type Darts_with_id as inner type of T.
// If T::Darts_with_id is not defined or if T::Darts_widh_id is Tag_false
BOOST_MPL_HAS_XXX_TRAIT_NAMED_DEF(Has_darts_with_id,Darts_with_id,false)
template<typename T, bool typedefined=Has_darts_with_id<T>::value >
struct Get_darts_with_id
{ typedef CGAL::Tag_false type; };
template<typename T>
struct Get_darts_with_id<T, true>
{ typedef CGAL::Tag_true type; };
// Get the type Attributes defined as inner type of T.
// If T::Attributes is not defined, defined std::tuple<> as type.
BOOST_MPL_HAS_XXX_TRAIT_NAMED_DEF(Has_attributes_tuple,Attributes,false)
template<typename T, bool typedefined=Has_attributes_tuple<T>::value >
struct Get_attributes_tuple
{ typedef std::tuple<> type; };
template<typename T>
struct Get_attributes_tuple<T, true>
{ typedef typename T::Attributes type; };
// Convert a tuple in a same tuple where each void type was replaced into
// CGAL::Void.
template<typename ... Items>
struct Convert_tuple_with_void;
template<typename ... Items>
struct Convert_tuple_with_void<std::tuple<Items...> >
{
typedef std::tuple<typename Convert_void<Items>::type... > type;
};
// Length of a variadic template
template<typename ... T>
struct My_length;
template<typename T1, typename ... T>
struct My_length<std::tuple<T1, T...> >
{
static const int value = My_length<std::tuple<T...> >::value + 1;
};
template<>
struct My_length<std::tuple<> >
{
static const int value = 0;
};
//count the number of time a given type is present in a tuple
template<class Type,class Tuple>
struct Number_of_type_in_tuple;
template<class Type,typename ... Items>
struct Number_of_type_in_tuple<Type,std::tuple<Type,Items...> >{
static const int value=Number_of_type_in_tuple
<Type,std::tuple<Items...> >::value+1;
};
template<class Type,class Other, typename ... Items>
struct Number_of_type_in_tuple<Type,std::tuple<Other,Items...> >{
static const int value=Number_of_type_in_tuple
<Type,std::tuple<Items...> >::value;
};
template<class Type>
struct Number_of_type_in_tuple<Type,std::tuple<> >{
static const int value=0;
};
//count the number of different types from Type is present in a tuple
template<class Type, class Tuple>
struct Number_of_different_type_in_tuple;
template<class Type, typename Other, typename ... Items>
struct Number_of_different_type_in_tuple<Type,std::tuple
<Other, Items...> >
{
static const int value=Number_of_different_type_in_tuple
<Type,std::tuple<Items...> >::value+1;
};
template<class Type, typename ... Items>
struct Number_of_different_type_in_tuple<Type, std::tuple
<Type,Items...> >
{
static const int value=Number_of_different_type_in_tuple
<Type,std::tuple<Items...> >::value;
};
template<class Type>
struct Number_of_different_type_in_tuple<Type, std::tuple<> >
{
static const int value=0;
};
//count the number of time a given type have been found
//within a tuple, until reaching position the k'th type of the tuple.
//dim is the total size of the tuple
template <class Type,int k,class T,
int dim=CGAL::internal::My_length<T>::value-1>
struct Nb_type_in_tuple_up_to_k;
template <class Type,int dim,int k,class T1,class ... T>
struct Nb_type_in_tuple_up_to_k<Type,k,std::tuple<T1,T...>,dim>
{
static const int pos= Nb_type_in_tuple_up_to_k
<Type,k,std::tuple<T...>,dim>::pos - 1;
static const int value =
( pos==k ) ? ( boost::is_same<T1,Type>::value ? 0:-dim-1 )
: ( ( pos<k ) ? ( ( boost::is_same<T1,Type>::value ? 1:0 )
+ Nb_type_in_tuple_up_to_k
<Type,k,std::tuple
<T...>,dim >::value)
:0
);
};
template <class Type,int dim,int k,class T1>
struct Nb_type_in_tuple_up_to_k<Type,k,std::tuple<T1>,dim >
{
static const int pos=dim;
static const int value=(pos==k?
(boost::is_same<T1,Type>::value?0:-dim-1) :
0);
};
//count the number of time a type different from Type have been found
//within a tuple, until reaching position the k'th type of the tuple.
//dim is the total size of the tuple
template <class Type, int k,class T,
int dim=CGAL::internal::My_length<T>::value-1>
struct Nb_type_different_in_tuple_up_to_k;
template <class Type,int dim,int k,class T1,class ... T>
struct Nb_type_different_in_tuple_up_to_k<Type,k,
std::tuple<T1,T...>,dim>
{
static const int pos = Nb_type_different_in_tuple_up_to_k
<Type,k,std::tuple<T...>,dim >::pos - 1;
static const int value =
( pos==k ) ? ( boost::is_same<T1,Type>::value ? -dim-1 : 0 )
: ( ( pos<k ) ? ( ( boost::is_same<T1,Type>::value ? 0:1 )
+ Nb_type_different_in_tuple_up_to_k
<Type,k,std::tuple<T...>,dim >::value)
:0
);
};
template <class Type,int dim,int k,class T1>
struct Nb_type_different_in_tuple_up_to_k<Type,k,
std::tuple<T1>,dim >
{
static const int pos=dim;
static const int value=(pos==k?
(boost::is_same<T1,Type>::value?-dim-1:0) :
0);
};
//Convert a tuple of T... to a tuple of Functor<T>::type...
template <template <class D> class Functor,class T>
struct Tuple_converter;
template <template <class D> class Functor,class ...T>
struct Tuple_converter<Functor,std::tuple<T...> >{
typedef std::tuple<typename Functor<T>::type... > type;
};
// To scan a given tuple, and keep only type different from Type
// to build the tuple Attribute_type.
template <class Type,class Res, class Tuple=std::tuple<> >
struct Keep_type_different_of;
template < class Type,class ... Res >
struct Keep_type_different_of<Type,std::tuple<>,
std::tuple<Res...> >
{
typedef std::tuple<Res...> type;
};
template < class Type,class ... T, class ... Res >
struct Keep_type_different_of<Type,
std::tuple<Type,T ...>,
std::tuple<Res...> >
{
typedef typename Keep_type_different_of
<Type,std::tuple<T ...>,std::tuple<Res...> >::type type;
};
template < class Type, class Other, class ... T, class ... Res >
struct Keep_type_different_of<Type,std::tuple<Other,T...>,
std::tuple<Res...> >
{
typedef typename Keep_type_different_of
<Type, std::tuple<T...>,
std::tuple<Res...,Other> >::type type;
};
//Helper class to statically call a functor
// for (int i=n;i>=0;--i) Functor::run<i>(....)
//Usage:
//
// struct Functor{
// template <int n>
// static void run(){std::cout << n << std::endl;}
// };
//
// Foreach_static<Functor,5>::run();
//
template <class Functor,int n>
struct Foreach_static{
template <class ... T>
static void run(T& ... t){
Functor:: template run<n>(t...);
Foreach_static<Functor,n-1>::run(t...);
}
};
template <class Functor>
struct Foreach_static<Functor,0>{
template <class ... T>
static void run(T& ... t)
{
Functor:: template run<0>( t... );
}
};
//Helper function that is calling
//Functor if TAG is different from Void
template <class Functor,int n,class Type>
struct Conditionnal_run{
template <class ... T>
static void run(T& ... t){
Functor:: template run<n>(t...);
}
};
template <class Functor,int n>
struct Conditionnal_run<Functor,n,Void>
{
template <class ... T>
static void run(T& ...){}
};
//Helper function that is calling
//Functor if TAG is different from Void and n!=j
template <class Functor,int n,int j,class Type>
struct Conditionnal_run_except{
template <class ... T>
static void run(T& ... t){
Functor:: template run<n>(t...);
}
};
template <class Functor,int n,int j>
struct Conditionnal_run_except<Functor,n,j,Void>
{
template <class ... T>
static void run(T& ...){}
};
template <class Functor,int n,class Type>
struct Conditionnal_run_except<Functor,n,n,Type>
{
template <class ... T>
static void run(T& ...){}
};
template <class Functor,int n>
struct Conditionnal_run_except<Functor,n,n,Void>
{
template <class ... T>
static void run(T& ...){}
};
//Same as Foreach_static excepted that Functor
//is called for case k only if the k'th type in the tuple
//is different from Void. Note that to the converse of Foreach_static
//Functor are called from n =0 to k
template <class Functor,class T,int n=0>
struct Foreach_static_restricted;
template <class Functor,class Head, class ... Items,int n>
struct Foreach_static_restricted<Functor,
std::tuple<Head,Items...>,n>
{
template <class ... T>
static void run(T& ... t){
Conditionnal_run<Functor,n,Head>::run(t...);
Foreach_static_restricted
<Functor,std::tuple<Items...>,n+1>::run(t...);
}
};
template <class Functor,int n>
struct Foreach_static_restricted<Functor,std::tuple<>,n>{
template <class ... T>
static void run(T& ... ){}
};
//Same as Foreach_static_restricted excepted that Functor
//is called for case k only if the k'th type in the tuple
//is different from Void and k!=j.
template <class Functor,int j,class T,int n=0>
struct Foreach_static_restricted_except;
template <class Functor,int j,class Head, class ... Items,int n>
struct Foreach_static_restricted_except<Functor, j,
std::tuple<Head,Items...>,n>
{
template <class ... T>
static void run(T& ... t){
Conditionnal_run_except<Functor,n,j,Head>::run(t...);
Foreach_static_restricted_except
<Functor,j,std::tuple<Items...>,n+1>::run(t...);
}
};
template <class Functor,int j,int n>
struct Foreach_static_restricted_except<Functor,j,std::tuple<>,n>
{
template <class ... T>
static void run(T& ... ){}
};
//Apply a functor to each element of a tuple
template<class Functor,class Tuple,
int pos=CGAL::internal::My_length<Tuple>::value-1>
struct Apply_functor_to_each_tuple_element
{
static void run(Tuple& t){
Functor() ( std::get<pos>(t) );
Apply_functor_to_each_tuple_element<Functor,Tuple,pos-1>::run(t);
}
};
template<class Functor,class Tuple>
struct Apply_functor_to_each_tuple_element<Functor,Tuple,-1>
{
static void run(Tuple&){}
};
struct Clear_functor
{
template<class T>
void operator()(T&t)
{ t.clear(); }
};
struct Clear_all
{
template<class Tuple>
static void run(Tuple& t)
{
Apply_functor_to_each_tuple_element<Clear_functor,Tuple>::run(t);
}
};
// Helper class, templated by a given combinatorial map.
template <class CMap>
struct Combinatorial_map_helper
{
// defines as type Compact_container<T>
template <class T>
struct Add_compact_container{
typedef std::allocator_traits<typename CMap::Alloc> Allocator_traits;
typedef typename Allocator_traits::template rebind_alloc<T> Attr_allocator;
typedef typename CMap::template Container_for_attributes<T> type;
};
// defines as type Compact_container<T>::iterator
template <class T>
struct Add_compact_container_iterator{
typedef std::allocator_traits<typename CMap::Alloc> Allocator_traits;
typedef typename Allocator_traits::template rebind_alloc<T> Attr_allocator;
typedef typename CMap::template Container_for_attributes<T>::iterator
iterator_type;
// TODO case when there is no Use_index typedef in CMap
typedef typename boost::mpl::if_
< typename boost::is_same<typename CMap::Use_index,Tag_true>::type,
typename CMap::Dart_handle, iterator_type >::type type;
};
// defines as type Compact_container<T>::const_iterator
template <class T>
struct Add_compact_container_const_iterator{
typedef std::allocator_traits<typename CMap::Alloc> Allocator_traits;
typedef typename Allocator_traits::template rebind_alloc<T> Attr_allocator;
typedef typename CMap::template Container_for_attributes<T>::
const_iterator iterator_type;
typedef typename boost::mpl::if_
< typename boost::is_same<typename CMap::Use_index,Tag_true>::type,
typename CMap::Dart_handle, iterator_type >::type type;
};
// All the attributes (with CGAL::Void)
typedef typename CGAL::internal::Convert_tuple_with_void
<typename CMap::Attributes>::type Attributes;
// defines as type Cell_attribute_binary_functor<T>
template <class T>
struct Define_cell_attribute_binary_functor{
typedef typename boost::function<void(T&, T&)> type;
};
// Enabled attributes (without CGAL::Void)
typedef typename CGAL::internal::Keep_type_different_of
<CGAL::Void,Attributes>::type Enabled_attributes;
// Number of all attributes
/* Does not compile on windows !!
static const unsigned int number_of_attributes =
CGAL::internal::My_length<Attributes>::value; */
// Number of enabled attributes
static const unsigned int nb_attribs =
Number_of_different_type_in_tuple<Void,Enabled_attributes>::value;
// Given a dimension of the cell, return the index of
// corresponding attribute
template <int d>
struct Dimension_index
{ static const int value=
Nb_type_different_in_tuple_up_to_k<Void,d,Attributes>::value; };
// All these type contains as many entries than the number of
// enabled attributes
typedef typename Tuple_converter
< Add_compact_container, Enabled_attributes >::type Attribute_containers;
typedef typename Tuple_converter< Add_compact_container_iterator,
Enabled_attributes >::type
Attribute_iterators;
typedef typename Tuple_converter< Add_compact_container_const_iterator,
Enabled_attributes >::type
Attribute_const_iterators;
typedef Attribute_containers Attribute_ranges;
typedef Attribute_iterators Attribute_handles;
typedef Attribute_const_iterators Attribute_const_handles;
typedef typename Tuple_converter< Define_cell_attribute_binary_functor,
Enabled_attributes >::type
Merge_functors;
typedef typename Tuple_converter< Define_cell_attribute_binary_functor,
Enabled_attributes >::type
Split_functors;
//Helper class allowing to retrieve the type of the
// attribute of dimension d
template<int d, int in_tuple=(d<CGAL::internal::My_length
<Attributes>::value)>
struct Attribute_type
{ typedef typename std::tuple_element<d,Attributes>::type type; };
template<int d>
struct Attribute_type<d,0>
{ typedef Void type; };
// Helper class allowing to retreive the d-cell-handle attribute
template<int d, class Type=typename Attribute_type<d>::type>
struct Attribute_handle
{
typedef typename std::tuple_element
<Dimension_index<d>::value,Attribute_handles>::type type;
};
template<int d>
struct Attribute_handle<d, CGAL::Void>
{ typedef CGAL::Void* type; };
// Helper class allowing to retreive the d-cell-const handle attribute
template<int d, class Type=typename Attribute_type<d>::type>
struct Attribute_const_handle
{
typedef typename std::tuple_element
<Dimension_index<d>::value, Attribute_const_handles>::type type;
};
template<int d>
struct Attribute_const_handle<d, CGAL::Void>
{ typedef CGAL::Void* type; };
// Helper class allowing to retreive the d-cell-iterator attribute
template<int d, class Type=typename Attribute_type<d>::type>
struct Attribute_iterator
{
typedef typename std::tuple_element
<Dimension_index<d>::value, Attribute_iterators>::type type;
};
template<int d>
struct Attribute_iterator<d, CGAL::Void>
{ typedef CGAL::Void* type; };
// Helper class allowing to retreive the d-cell-const handle attribute
template<int d, class Type=typename Attribute_type<d>::type>
struct Attribute_const_iterator
{
typedef typename std::tuple_element
<Dimension_index<d>::value, Attribute_const_iterators>::type type;
};
template<int d>
struct Attribute_const_iterator<d, CGAL::Void>
{ typedef CGAL::Void* type; };
// Helper class allowing to retreive the d-cell-attribute range
template<int d, class Type=typename Attribute_type<d>::type>
struct Attribute_range
{
typedef typename std::tuple_element
<Dimension_index<d>::value, Attribute_ranges>::type type;
};
template<int d>
struct Attribute_range<d, CGAL::Void>
{ typedef CGAL::Void type; };
// Helper class allowing to retreive the d-cell-attribute const range
template<int d, class Type=typename Attribute_type<d>::type>
struct Attribute_const_range
{
typedef const typename std::tuple_element
<Dimension_index<d>::value, Attribute_ranges >::type type;
};
template<int d>
struct Attribute_const_range<d, CGAL::Void>
{ typedef CGAL::Void type; };
// To iterate onto each enabled attributes
template <class Functor>
struct Foreach_enabled_attributes
{
template <class ...Ts>
static void run(Ts& ... t)
{ Foreach_static_restricted<Functor, Attributes>::run(t...); }
};
// To iterate onto each enabled attributes, except j-attributes
template <class Functor, unsigned int j>
struct Foreach_enabled_attributes_except
{
template <class ...Ts>
static void run(Ts& ... t)
{ Foreach_static_restricted_except<Functor, j, Attributes>::run(t...); }
};
};
} //namespace internal
} //namespace CGAL
#endif //CGAL_INTERNAL_COMBINATORIAL_MAP_UTILITY_H
|
jjcasmar/cgal | Intersections_3/include/CGAL/Intersections_3/internal/intersection_3_1_impl.h | // Copyright (c) 1997-2010
// Utrecht University (The Netherlands),
// ETH Zurich (Switzerland),
// INRIA Sophia-Antipolis (France),
// Max-Planck-Institute Saarbruecken (Germany),
// and Tel-Aviv University (Israel). All rights reserved.
//
// This file is part of CGAL (www.cgal.org)
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s) : <NAME> <<EMAIL>>
// <NAME> <<EMAIL>>
#ifndef CGAL_INTERSECTIONS_3_INTERNAL_INTERSECTION_3_1_IMPL_H
#define CGAL_INTERSECTIONS_3_INTERNAL_INTERSECTION_3_1_IMPL_H
#include <CGAL/wmult.h>
#include <boost/next_prior.hpp>
#include <CGAL/Intersection_traits_3.h>
#include <CGAL/number_utils.h>
#include <CGAL/Intersections_3/Iso_cuboid_3_Iso_cuboid_3.h>
#include <CGAL/Intersections_3/Iso_cuboid_3_Line_3.h>
#include <CGAL/utils_classes.h>
#include <CGAL/squared_distance_3.h>
#include <CGAL/Intersections_3/internal/bbox_intersection_3.h>
namespace CGAL {
template <class K>
class Plane_3;
template <class K>
class Line_3;
template <class K>
class Segment_3;
template <class K>
class Ray_3;
template <class K>
class Sphere_3;
template <class K>
class Triangle_3;
template <class K>
class Iso_cuboid_3;
template <class K>
class Point_3;
// the special plane_3 function
template <class K>
inline
typename cpp11::result_of<typename K::Intersect_3(typename K::Plane_3, typename K::Plane_3, typename K::Plane_3)>::type
intersection(const Plane_3<K> &plane1, const Plane_3<K> &plane2,
const Plane_3<K> &plane3)
{
return K().intersect_3_object()(plane1, plane2, plane3);
}
template <class R>
inline bool
do_intersect(const Plane_3<R> &plane1, const Plane_3<R> &plane2,
const Plane_3<R> &plane3) {
return R().do_intersect_3_object()(plane1, plane2, plane3);
}
namespace Intersections {
namespace internal {
template <class K>
typename Intersection_traits<K, typename K::Plane_3, typename K::Line_3>::result_type
intersection(const typename K::Plane_3 &plane,
const typename K::Line_3 &line,
const K& /*k*/)
{
typedef typename K::Point_3 Point_3;
typedef typename K::Direction_3 Direction_3;
typedef typename K::RT RT;
const Point_3 &line_pt = line.point();
const Direction_3 &line_dir = line.direction();
RT num = plane.a()*line_pt.hx() + plane.b()*line_pt.hy()
+ plane.c()*line_pt.hz() + wmult_hw((K*)0, plane.d(), line_pt);
RT den = plane.a()*line_dir.dx() + plane.b()*line_dir.dy()
+ plane.c()*line_dir.dz();
if (den == 0) {
if (num == 0) {
// all line
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Line_3>(line);
} else {
// no intersection
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Line_3>();
}
}
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Line_3>(Point_3(
den*line_pt.hx()-num*line_dir.dx(),
den*line_pt.hy()-num*line_dir.dy(),
den*line_pt.hz()-num*line_dir.dz(),
wmult_hw((K*)0, den, line_pt)));
}
template <class K>
inline
typename Intersection_traits<K, typename K::Plane_3, typename K::Line_3>::result_type
intersection(const typename K::Line_3 &line,
const typename K::Plane_3 &plane,
const K& k)
{
return intersection(plane, line, k);
}
template <class K>
typename Intersection_traits<K, typename K::Plane_3, typename K::Plane_3>::result_type
intersection(const typename K::Plane_3 &plane1,
const typename K::Plane_3 &plane2,
const K&)
{
typedef typename K::Point_3 Point_3;
typedef typename K::Direction_3 Direction_3;
typedef typename K::Line_3 Line_3;
typedef typename K::RT RT;
const RT &a = plane1.a();
const RT &b = plane1.b();
const RT &c = plane1.c();
const RT &d = plane1.d();
const RT &p = plane2.a();
const RT &q = plane2.b();
const RT &r = plane2.c();
const RT &s = plane2.d();
RT det = a*q-p*b;
if (det != 0) {
Point_3 is_pt = Point_3(b*s-d*q, p*d-a*s, 0, det);
Direction_3 is_dir = Direction_3(b*r-c*q, p*c-a*r, det);
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Plane_3>(Line_3(is_pt, is_dir));
}
det = a*r-p*c;
if (det != 0) {
Point_3 is_pt = Point_3(c*s-d*r, 0, p*d-a*s, det);
Direction_3 is_dir = Direction_3(c*q-b*r, det, p*b-a*q);
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Plane_3>(Line_3(is_pt, is_dir));
}
det = b*r-c*q;
if (det != 0) {
Point_3 is_pt = Point_3(0, c*s-d*r, d*q-b*s, det);
Direction_3 is_dir = Direction_3(det, c*p-a*r, a*q-b*p);
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Plane_3>(Line_3(is_pt, is_dir));
}
// degenerate case
if (a!=0 || p!=0) {
if (a*s == p*d)
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Plane_3>(plane1);
else
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Plane_3>();
}
if (b!=0 || q!=0) {
if (b*s == q*d)
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Plane_3>(plane1);
else
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Plane_3>();
}
if (c!=0 || r!=0) {
if (c*s == r*d)
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Plane_3>(plane1);
else
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Plane_3>();
}
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Plane_3>(plane1);
}
template <class K>
boost::optional< boost::variant<typename K::Point_3,
typename K::Line_3,
typename K::Plane_3> >
intersection(const typename K::Plane_3 &plane1,
const typename K::Plane_3 &plane2,
const typename K::Plane_3 &plane3,
const K& k)
{
typedef
typename boost::optional<
boost::variant<typename K::Point_3,
typename K::Line_3,
typename K::Plane_3> >
result_type;
typedef typename K::Point_3 Point_3;
typedef typename K::Line_3 Line_3;
typedef typename K::Plane_3 Plane_3;
// Intersection between plane1 and plane2 can either be
// a line, a plane, or empty.
typename Intersection_traits<K, Plane_3, Plane_3>::result_type
o12 = internal::intersection(plane1, plane2, k);
if(o12) {
if(const Line_3* l = intersect_get<Line_3>(o12)) {
// either point or line
typename Intersection_traits<K, Plane_3, Line_3>::result_type
v = internal::intersection(plane3, *l, k);
if(v) {
if(const Point_3* p = intersect_get<Point_3>(v))
return result_type(*p);
else if(const Line_3* l = intersect_get<Line_3>(v))
return result_type(*l);
}
} else if(const Plane_3 *pl = intersect_get<Plane_3>(o12)) {
// either line or plane
typename Intersection_traits<K, Plane_3, Plane_3>::result_type
v = internal::intersection(plane3, *pl, k);
if(v) {
if(const Plane_3* p = intersect_get<Plane_3>(v))
return result_type(*p);
else if(const Line_3* l = intersect_get<Line_3>(v))
return result_type(*l);
}
}
}
return result_type();
}
template <class K>
bool
do_intersect(const typename K::Plane_3 &plane,
const typename K::Line_3 &line,
const K&)
{
typedef typename K::Point_3 Point_3;
typedef typename K::Direction_3 Direction_3;
typedef typename K::RT RT;
const Point_3 &line_pt = line.point();
const Direction_3 &line_dir = line.direction();
RT den = plane.a()*line_dir.dx() + plane.b()*line_dir.dy()
+ plane.c()*line_dir.dz();
if (den != 0)
return true;
RT num = plane.a()*line_pt.hx() + plane.b()*line_pt.hy()
+ plane.c()*line_pt.hz() + wmult_hw((K*)0, plane.d(), line_pt);
if (num == 0) {
// all line
return true;
} else {
// no intersection
return false;
}
}
template <class K>
inline
bool
do_intersect(const typename K::Line_3 &line,
const typename K::Plane_3 &plane,
const K& k)
{
return do_intersect(plane, line, k);
}
template <class K>
typename Intersection_traits<K, typename K::Line_3, typename K::Line_3>::result_type
intersection(const typename K::Line_3 &l1,
const typename K::Line_3 &l2,
const K&)
{
typedef typename K::FT FT;
typedef typename K::Point_3 Point_3;
typedef typename K::Vector_3 Vector_3;
if(K().has_on_3_object()(l1, l2.point())) {
const Vector_3& v1 = l1.to_vector();
const Vector_3& v2 = l2.to_vector();
if((v1.x() * v2.y() == v1.y() * v2.x()) &&
(v1.x() * v2.z() == v1.z() * v2.x()) &&
(v1.y() * v2.z() == v1.z() * v2.y()))
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Line_3>(l1);
}
if(K().are_parallel_3_object()(l1,l2)) return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Line_3>();
const Point_3 &p1 = l1.point();
const Point_3 &p3 = l2.point();
const Vector_3 &v1 = l1.to_vector();
const Vector_3 &v2 = l2.to_vector();
const Point_3 p2 = p1 + v1;
const Point_3 p4 = p2 + v2;
if(!K().coplanar_3_object()(p1,p2,p3,p4)) return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Line_3>();
const Vector_3 v3 = p3 - p1;
const Vector_3 v3v2 = cross_product(v3,v2);
const Vector_3 v1v2 = cross_product(v1,v2);
const FT sl = v1v2.squared_length();
if(certainly(sl == FT(0)))
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Line_3>();
const FT t = ((v3v2.x()*v1v2.x()) + (v3v2.y()*v1v2.y()) + (v3v2.z()*v1v2.z())) / sl;
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Line_3>(p1 + (v1 * t));
}
template <class K>
bool
do_intersect(const typename K::Line_3 &l1,
const typename K::Line_3 &l2,
const K&)
{
typedef typename K::Point_3 Point_3;
typedef typename K::Vector_3 Vector_3;
if(K().has_on_3_object()(l1, l2.point())) return true;
if(K().are_parallel_3_object()(l1,l2)) return false;
const Point_3 &p1 = l1.point();
const Point_3 &p3 = l2.point();
const Vector_3 &v1 = l1.to_vector();
const Vector_3 &v2 = l2.to_vector();
const Point_3 p2 = p1 + v1;
const Point_3 p4 = p2 + v2;
return K().coplanar_3_object()(p1,p2,p3,p4);
}
template <class K>
typename Intersection_traits<K, typename K::Segment_3, typename K::Segment_3>::result_type
intersection_collinear_segments(const typename K::Segment_3 &s1,
const typename K::Segment_3 &s2,
const K& k)
{
CGAL_precondition(! s1.is_degenerate () && ! s2.is_degenerate () );
const typename K::Point_3& p=s1[0],q=s1[1],r=s2[0],s=s2[1];
typename K::Collinear_are_ordered_along_line_3 cln_order=k.collinear_are_ordered_along_line_3_object();
if ( cln_order(p,r,q) ){
if ( cln_order(p,s,q) )
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>(s2);
if ( cln_order(r,p,s) ){
if (r!=p) return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>( typename K::Segment_3(r,p) );
if ( cln_order(r,q,s) ) return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>(s1);
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>(p);
}
return r!=q ? intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>( typename K::Segment_3(r,q) )
: intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>(q);
}
if ( cln_order(p,s,q) ){
if ( cln_order(r,p,s) ){
if (s!=p) return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>( typename K::Segment_3(s,p) );
if (cln_order(r,q,s)) return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>(s1);
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>(p);
}
return s!=q ? intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>( typename K::Segment_3(s,q) )
: intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>(q);
}
if ( cln_order(r,p,s) )
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>(s1);
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>();
}
template<class K>
struct L_p_visitor : public boost::static_visitor<
typename Intersection_traits<K, typename K::Segment_3,
typename K::Segment_3>::result_type
>
{
typedef typename Intersection_traits<K, typename K::Segment_3,
typename K::Segment_3>::result_type result_type;
L_p_visitor(const typename K::Segment_3& s1, const typename K::Segment_3& s2) :
s1(s1), s2(s2) { }
const typename K::Segment_3& s1;
const typename K::Segment_3& s2;
result_type
operator()(const typename K::Point_3& p) const {
typename K::Collinear_are_ordered_along_line_3 cln_order=K().collinear_are_ordered_along_line_3_object();
if ( cln_order(s1[0],p,s1[1]) && cln_order(s2[0],p,s2[1]) )
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>(p);
else
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>();
}
result_type
operator()(const typename K::Line_3&) const {
return intersection_collinear_segments(s1,s2,K());
}
};
template <class K>
typename Intersection_traits<K, typename K::Segment_3, typename K::Segment_3>::result_type
intersection(const typename K::Segment_3 &s1,
const typename K::Segment_3 &s2,
const K&)
{
CGAL_precondition(! s1.is_degenerate () && ! s2.is_degenerate () );
typename Intersection_traits<K, typename K::Line_3, typename K::Line_3>::result_type
v = internal::intersection(s1.supporting_line(),s2.supporting_line(), K());
if(v) {
return apply_visitor(L_p_visitor<K>(s1, s2) , *v);
}
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Segment_3>();
}
template <class K>
inline
bool
do_intersect(const typename K::Segment_3 &s1,
const typename K::Segment_3 &s2,
const K & k)
{
CGAL_precondition(! s1.is_degenerate () && ! s2.is_degenerate () );
bool b=internal::do_intersect(s1.supporting_line(),s2.supporting_line(),k);
if (b)
{
//supporting_line intersects: points are coplanar
typename K::Coplanar_orientation_3 cpl_orient=k.coplanar_orientation_3_object();
::CGAL::Orientation or1 = cpl_orient(s1[0],s1[1],s2[0]);
::CGAL::Orientation or2 = cpl_orient(s1[0],s1[1],s2[1]);
if ( or1 == COLLINEAR && or2 ==COLLINEAR )
{
//segments are collinear
typename K::Collinear_are_ordered_along_line_3 cln_order=k.collinear_are_ordered_along_line_3_object();
return cln_order(s1[0],s2[0],s1[1]) ||
cln_order(s1[0],s2[1],s1[1]) ||
cln_order(s2[0],s1[0],s2[1]) ;
}
if ( or1 != or2 ){
or1=cpl_orient(s2[0],s2[1],s1[0]);
return (or1 == COLLINEAR || or1 != cpl_orient(s2[0],s2[1],s1[1]));
}
}
return false;
}
template <class K>
typename Intersection_traits<K, typename K::Line_3, typename K::Segment_3>::result_type
intersection(const typename K::Line_3 &l,
const typename K::Segment_3 &s,
const K& k)
{
CGAL_precondition(! l.is_degenerate () && ! s.is_degenerate () );
typename Intersection_traits<K, typename K::Line_3, typename K::Line_3>::result_type
v = internal::intersection(l,s.supporting_line(), K());
if(v) {
if(const typename K::Point_3* p = intersect_get<typename K::Point_3> (v)) {
typename K::Collinear_are_ordered_along_line_3 cln_order=k.collinear_are_ordered_along_line_3_object();
if(cln_order(s[0],*p,s[1]))
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Segment_3>(*p);
} else {
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Segment_3>(s);
}
}
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Segment_3>();
}
template <class K>
typename Intersection_traits<K, typename K::Line_3, typename K::Segment_3>::result_type
intersection(const typename K::Segment_3 &s,
const typename K::Line_3 &l,
const K& k)
{
return intersection(l,s,k);
}
template <class K>
inline
bool
do_intersect(const typename K::Line_3 &l,
const typename K::Segment_3 &s,
const K & k)
{
CGAL_precondition(! l.is_degenerate () && ! s.is_degenerate () );
bool b=do_intersect(l,s.supporting_line(),k);
if (b)
{
//supporting_line intersects: points are coplanar
typename K::Coplanar_orientation_3 cpl_orient=k.coplanar_orientation_3_object();
typename K::Point_3 p1=l.point(0);
typename K::Point_3 p2=l.point(1);
::CGAL::Orientation or1 = cpl_orient(p1,p2,s[0]);
if ( or1 == COLLINEAR ) return true;
::CGAL::Orientation or2 = cpl_orient(p1,p2,s[1]);
return or1!=or2;
}
return false;
}
template <class K>
inline
bool
do_intersect(const typename K::Segment_3 &s,
const typename K::Line_3 &l,
const K & k)
{
return do_intersect(l,s,k);
}
template <class K>
bool
Ray_3_has_on_collinear_Point_3(
const typename K::Ray_3 &r,
const typename K::Point_3 &p,
const K& k)
{
return
k.equal_3_object()(r.source(),p)
||
k.equal_3_object() (
k.construct_direction_3_object()( k.construct_vector_3_object() (r.source(),p) ),
r.direction()
);
}
template <class K>
typename Intersection_traits<K, typename K::Line_3, typename K::Ray_3>::result_type
intersection(const typename K::Line_3 &l,
const typename K::Ray_3 &r,
const K& k)
{
CGAL_precondition(! l.is_degenerate () && ! r.is_degenerate () );
typename Intersection_traits<K, typename K::Line_3, typename K::Line_3>::result_type
v = internal::intersection(l,r.supporting_line(), k);
if(v) {
if(const typename K::Point_3* p = intersect_get<typename K::Point_3>(v)) {
if( Ray_3_has_on_collinear_Point_3(r,*p,k) )
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Ray_3>(*p);
} else if(intersect_get<typename K::Line_3>(v)) {
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Ray_3>(r);
}
}
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Ray_3>();
}
template <class K>
typename Intersection_traits<K, typename K::Ray_3, typename K::Line_3>::result_type
intersection(const typename K::Ray_3 &r,
const typename K::Line_3 &l,
const K& k)
{
return intersection(l,r,k);
}
template <class K>
inline
bool
do_intersect(const typename K::Line_3 &l,
const typename K::Ray_3 &r,
const K & k)
{
CGAL_precondition(! l.is_degenerate () && ! r.is_degenerate () );
if ( !do_intersect(l,r.supporting_line()) ) return false;
typename K::Coplanar_orientation_3 pred=k.coplanar_orientation_3_object();
Orientation p0p1s=pred(l.point(0),l.point(1),r.source());
if ( p0p1s == COLLINEAR) return true;
Orientation stp0 =pred(r.source(),r.second_point(),l.point(0));
if ( stp0 == COLLINEAR )
return Ray_3_has_on_collinear_Point_3(r,l.point(0),k);
return p0p1s!=stp0;
}
template <class K>
inline
bool
do_intersect(const typename K::Ray_3 &r,
const typename K::Line_3 &l,
const K & k)
{
return do_intersect(l,r,k);
}
template <class K>
typename Intersection_traits<K, typename K::Segment_3, typename K::Ray_3>::result_type
intersection(const typename K::Segment_3 &s,
const typename K::Ray_3 &r,
const K& k)
{
CGAL_precondition(! s.is_degenerate () && ! r.is_degenerate () );
typename Intersection_traits<K, typename K::Line_3, typename K::Segment_3>::result_type
v = internal::intersection(r.supporting_line(),s, K());
if(v) {
if(const typename K::Point_3* p = intersect_get<typename K::Point_3>(v)) {
if( Ray_3_has_on_collinear_Point_3(r,*p,k) )
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Ray_3>(*p);
} else if(const typename K::Segment_3* s2 = intersect_get<typename K::Segment_3>(v)) {
bool has_source=Ray_3_has_on_collinear_Point_3(r,s.source(),k);
bool has_target=Ray_3_has_on_collinear_Point_3(r,s.target(),k);
if (has_source){
if (has_target)
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Ray_3>(*s2);
else
{
if (k.equal_3_object() (r.source(),s.source()))
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Ray_3>(r.source());
else
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Ray_3>(
k.construct_segment_3_object()(r.source(),s.source()));
}
}
else{
if (has_target){
if (k.equal_3_object() (r.source(),s.target()))
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Ray_3>(r.source());
else
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Ray_3>(
k.construct_segment_3_object()(r.source(),s.target()));
}
}
}
}
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Ray_3>();
}
template <class K>
typename Intersection_traits<K, typename K::Ray_3, typename K::Segment_3>::result_type
intersection(const typename K::Ray_3 &r,
const typename K::Segment_3 &s,
const K& k)
{
return intersection(s,r,k);
}
template <class K>
inline
bool
do_intersect(const typename K::Segment_3 &s,
const typename K::Ray_3 &r,
const K & k)
{
CGAL_precondition(! s.is_degenerate () && ! r.is_degenerate () );
if ( !do_intersect(s,r.supporting_line()) ) return false;
typename K::Coplanar_orientation_3 pred=k.coplanar_orientation_3_object();
Orientation p0p1s=pred(s.point(0),s.point(1),r.source());
Orientation stp0 =pred(r.source(),r.second_point(),s.point(0));
if ( p0p1s == COLLINEAR) //s belongs to the supporting line of p0p1
{
if ( stp0 == COLLINEAR )//st and p0p1 have the same supporting line
return Ray_3_has_on_collinear_Point_3(r,s.point(0),k) || Ray_3_has_on_collinear_Point_3(r,s.point(1),k);
else
return true;
}
if ( stp0 == COLLINEAR )
return Ray_3_has_on_collinear_Point_3(r,s.point(0),k);
return p0p1s!=stp0;
}
template <class K>
inline
bool
do_intersect(const typename K::Ray_3 &r,
const typename K::Segment_3 &s,
const K & k)
{
return do_intersect(s,r,k);
}
template <class K>
typename Intersection_traits<K, typename K::Ray_3, typename K::Ray_3>::result_type
intersection(const typename K::Ray_3 &r1,
const typename K::Ray_3 &r2,
const K& k)
{
CGAL_precondition(! r1.is_degenerate () && ! r2.is_degenerate () );
typename Intersection_traits<K, typename K::Line_3, typename K::Ray_3>::result_type
v = internal::intersection(r1.supporting_line(),r2, k);
if(v) {
if(const typename K::Point_3* p = intersect_get<typename K::Point_3>(v)) {
if(Ray_3_has_on_collinear_Point_3(r1,*p,k))
return intersection_return<typename K::Intersect_3, typename K::Ray_3, typename K::Ray_3>(*p);
} else if(const typename K::Ray_3* r = intersect_get<typename K::Ray_3>(v)) {
bool r1_has_s2=Ray_3_has_on_collinear_Point_3(r1,r2.source(),k);
bool r2_has_s1=Ray_3_has_on_collinear_Point_3(r2,r1.source(),k);
if (r1_has_s2){
if (r2_has_s1)
{
if (k.equal_3_object()(r1.source(),r2.source()))
return intersection_return<typename K::Intersect_3, typename K::Ray_3, typename K::Ray_3>(r1.source());
else {
return intersection_return<typename K::Intersect_3, typename K::Ray_3, typename K::Ray_3>(
k.construct_segment_3_object()(r1.source(),r2.source()));
}
}
else
return intersection_return<typename K::Intersect_3, typename K::Ray_3, typename K::Ray_3>(*r);
}
else{
if (r2_has_s1)
return intersection_return<typename K::Intersect_3, typename K::Ray_3, typename K::Ray_3>(r1);
}
}
}
return intersection_return<typename K::Intersect_3, typename K::Ray_3, typename K::Ray_3>();
}
template <class K>
inline
bool
do_intersect(const typename K::Ray_3 &r1,
const typename K::Ray_3 &r2,
const K & k)
{
CGAL_precondition(! r1.is_degenerate () && ! r2.is_degenerate () );
if ( !do_intersect(r1,r2.supporting_line()) ) return false;
typename K::Coplanar_orientation_3 pred=k.coplanar_orientation_3_object();
Orientation p0p1s=pred(r1.point(0),r1.point(1),r2.source());
Orientation stp0 =pred(r2.source(),r2.second_point(),r1.point(0));
if ( p0p1s == COLLINEAR){
if(stp0 == COLLINEAR )
return Ray_3_has_on_collinear_Point_3(r2,r1.source(),k) ||
Ray_3_has_on_collinear_Point_3(r1,r2.source(),k);
else
return true;
}
if(stp0 == COLLINEAR )
return Ray_3_has_on_collinear_Point_3(r2,r1.point(0),k);
return p0p1s!=stp0;
}
template <class K>
typename Intersection_traits<K, typename K::Plane_3, typename K::Sphere_3>::result_type
intersection(const typename K::Plane_3 &p,
const typename K::Sphere_3 &s,
const K&)
{
typedef typename K::Circle_3 Circle_3;
typedef typename K::Point_3 Point_3;
typedef typename K::FT FT;
const FT d2 = CGAL::square(p.a()*s.center().x() +
p.b()*s.center().y() +
p.c()*s.center().z() + p.d()) /
(square(p.a()) + square(p.b()) + square(p.c()));
const FT cmp = d2 - s.squared_radius();
if(CGAL_NTS is_zero(cmp)) { // tangent
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Sphere_3>(p.projection(s.center()));
} else if(CGAL_NTS is_negative(cmp)) { // intersect
Point_3 center = p.projection(s.center());
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Sphere_3>(Circle_3(center,s.squared_radius() - d2,p));
} // do not intersect
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Sphere_3>();
}
template <class K>
inline
bool
do_intersect(const typename K::Plane_3 &p,
const typename K::Sphere_3 &s,
const K&)
{
typedef typename K::FT FT;
const FT d2 = CGAL::square(p.a()*s.center().x() +
p.b()*s.center().y() +
p.c()*s.center().z() + p.d()) /
(square(p.a()) + square(p.b()) + square(p.c()));
return d2 <= s.squared_radius();
}
template <class K>
inline
bool
do_intersect(const typename K::Sphere_3 &s,
const typename K::Plane_3 &p,
const K&)
{
return do_intersect(p,s);
}
template <class K>
inline
typename Intersection_traits<K, typename K::Sphere_3, typename K::Plane_3>::result_type
intersection(const typename K::Sphere_3 &s,
const typename K::Plane_3 &p,
const K& k)
{
return intersection(p, s, k);
}
template <class K>
inline
typename Intersection_traits<K, typename K::Sphere_3, typename K::Sphere_3>::result_type
intersection(const typename K::Sphere_3 &s1,
const typename K::Sphere_3 &s2,
const K& k)
{
typedef typename K::Plane_3 Plane_3;
if(s1.center() == s2.center()) {
if(s1.squared_radius() == s2.squared_radius()) {
if(is_zero(s1.squared_radius())) return intersection_return<typename K::Intersect_3, typename K::Sphere_3, typename K::Sphere_3>(s1.center());
else return intersection_return<typename K::Intersect_3, typename K::Sphere_3, typename K::Sphere_3>(s1);
} else return intersection_return<typename K::Intersect_3, typename K::Sphere_3, typename K::Sphere_3>(); // cocentrics
}
Plane_3 p = K().construct_radical_plane_3_object()(s1,s2);
typename Intersection_traits<K, typename K::Sphere_3, typename K::Plane_3>::result_type
v = intersection(p, s1, k);
if(v) {
if(const typename K::Point_3* p = intersect_get<typename K::Point_3>(v))
return intersection_return<typename K::Intersect_3, typename K::Sphere_3, typename K::Sphere_3>(*p);
else if(const typename K::Circle_3* c = intersect_get<typename K::Circle_3>(v))
return intersection_return<typename K::Intersect_3, typename K::Sphere_3, typename K::Sphere_3>(*c);
}
return intersection_return<typename K::Intersect_3, typename K::Sphere_3, typename K::Sphere_3>();
}
template <class K>
inline
bool
do_intersect(const typename K::Sphere_3 &s1,
const typename K::Sphere_3 &s2,
const K& k)
{
typedef typename K::Plane_3 Plane_3;
if(s1.center() == s2.center()) {
return s1.squared_radius() == s2.squared_radius();
}
Plane_3 p = K().construct_radical_plane_3_object()(s1,s2);
return do_intersect(p, s1, k);
}
template <class K>
typename Intersection_traits<K, typename K::Plane_3, typename K::Ray_3>::result_type
intersection(const typename K::Plane_3 &plane,
const typename K::Ray_3 &ray,
const K& k)
{
typedef typename K::Point_3 Point_3;
typename Intersection_traits<K, typename K::Plane_3, typename K::Line_3>::result_type
v = internal::intersection(plane, ray.supporting_line(), k);
if(v) {
if(const Point_3* p = intersect_get<Point_3>(v)) {
if (ray.collinear_has_on(*p))
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Ray_3>(*p);
else
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Ray_3>();
}
} else {
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Ray_3>();
}
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Ray_3>(ray);
}
template <class K>
inline
typename Intersection_traits<K, typename K::Ray_3, typename K::Plane_3>::result_type
intersection(const typename K::Ray_3 &ray,
const typename K::Plane_3 &plane,
const K& k)
{
return intersection(plane, ray, k);
}
template <class K>
bool
do_intersect(const typename K::Plane_3 &plane,
const typename K::Ray_3 &ray,
const K& k)
{
typedef typename K::Point_3 Point_3;
typename Intersection_traits<K, typename K::Plane_3, typename K::Line_3>
::result_type
line_intersection = internal::intersection(plane, ray.supporting_line(), k);
if(!line_intersection)
return false;
if(const Point_3 *isp = intersect_get<Point_3>(line_intersection))
return ray.collinear_has_on(*isp);
return true;
}
template <class K>
inline
bool
do_intersect(const typename K::Ray_3 &ray,
const typename K::Plane_3 &plane,
const K& k)
{
return do_intersect(plane, ray, k);
}
template <class K>
typename Intersection_traits<K, typename K::Plane_3, typename K::Segment_3>::result_type
intersection(const typename K::Plane_3 &plane,
const typename K::Segment_3 &seg,
const K& k)
{
typedef typename K::Point_3 Point_3;
const Point_3 &source = seg.source();
const Point_3 &target = seg.target();
Oriented_side source_side = plane.oriented_side(source);
Oriented_side target_side = plane.oriented_side(target);
switch (source_side) {
case ON_ORIENTED_BOUNDARY:
if (target_side == ON_ORIENTED_BOUNDARY)
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>(seg);
else
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>(source);
case ON_POSITIVE_SIDE:
switch (target_side) {
case ON_ORIENTED_BOUNDARY:
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>(target);
case ON_POSITIVE_SIDE:
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>();
default: // ON_NEGATIVE_SIDE:
{
// intersection object should be a point, but rounding errors
// could lead to:
// - a line: in such case, return seg,
// - the empty set: return the empty set.
typename Intersection_traits<K, typename K::Plane_3, typename K::Line_3>::result_type
v = internal::intersection(plane, seg.supporting_line(), k);
if(v) {
if(const typename K::Point_3* p = intersect_get<typename K::Point_3>(v))
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>(*p);
else
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>(seg);
}
else
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>();
}
}
case ON_NEGATIVE_SIDE:
switch (target_side) {
case ON_ORIENTED_BOUNDARY:
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>(target);
case ON_POSITIVE_SIDE:
{
// intersection object should be a point, but rounding errors
// could lead to:
// - a line: in such case, return seg,
// - the empty set: return the empty set.
typename Intersection_traits<K, typename K::Plane_3, typename K::Line_3>::result_type
v = internal::intersection(plane, seg.supporting_line(), k);
if(v) {
if(const typename K::Point_3* p = intersect_get<typename K::Point_3>(v))
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>(*p);
else
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>(seg);
}
else
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>();
}
case ON_NEGATIVE_SIDE:
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>();
}
}
CGAL_kernel_assertion_msg(false, "Supposedly unreachable code.");
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Segment_3>();
}
template <class K>
inline
typename Intersection_traits<K, typename K::Segment_3, typename K::Plane_3>::result_type
intersection(const typename K::Segment_3 &seg,
const typename K::Plane_3 &plane,
const K& k)
{
return intersection(plane, seg, k);
}
template <class K>
bool
do_intersect(const typename K::Plane_3 &plane,
const typename K::Segment_3 &seg,
const K&)
{
typedef typename K::Point_3 Point_3;
const Point_3 &source = seg.source();
const Point_3 &target = seg.target();
Oriented_side source_side = plane.oriented_side(source);
Oriented_side target_side = plane.oriented_side(target);
if ( source_side == target_side
&& target_side != ON_ORIENTED_BOUNDARY) {
return false;
}
return true;
}
template <class K>
inline
bool
do_intersect(const typename K::Segment_3 &seg,
const typename K::Plane_3 &plane,
const K& k)
{
return do_intersect(plane, seg, k);
}
template <class K>
inline
typename Intersection_traits<K, typename K::Plane_3, typename K::Triangle_3>::result_type
intersection(const typename K::Plane_3 &plane,
const typename K::Triangle_3 &tri,
const K& k)
{
typedef
typename Intersection_traits<K, typename K::Plane_3, typename K::Line_3>::result_type
pl_res;
typename K::Construct_vertex_3 vertex_on =
k.construct_vertex_3_object();
Oriented_side or0=plane.oriented_side(vertex_on(tri,0));
Oriented_side or1=plane.oriented_side(vertex_on(tri,1));
Oriented_side or2=plane.oriented_side(vertex_on(tri,2));
if (or0==ON_ORIENTED_BOUNDARY){
if (or1==ON_ORIENTED_BOUNDARY){
if (or2==ON_ORIENTED_BOUNDARY)
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Triangle_3>(tri);
else
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Triangle_3>(k.construct_segment_3_object()
(tri.vertex(0),tri.vertex(1)));
}
else{
if (or2==ON_ORIENTED_BOUNDARY)
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Triangle_3>(k.construct_segment_3_object()
(tri.vertex(0),tri.vertex(2)));
else{
if (or1==or2)
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Triangle_3>(tri.vertex(0));
else{
pl_res v = internal::intersection(plane, k.construct_line_3_object()(tri.vertex(1),tri.vertex(2)), k);
const typename K::Point_3* p = intersect_get<typename K::Point_3>(v);
CGAL_kernel_assertion(p!=nullptr);
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Triangle_3>(k.construct_segment_3_object()
(*p,tri.vertex(0)));
}
}
}
}
if (or1==ON_ORIENTED_BOUNDARY){
if (or2==ON_ORIENTED_BOUNDARY)
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Triangle_3>(k.construct_segment_3_object()
(tri.vertex(1),tri.vertex(2)));
if (or2==or0)
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Triangle_3>(tri.vertex(1));
else{
pl_res v = intersection(plane, k.construct_line_3_object()(tri.vertex(0),tri.vertex(2)), k);
const typename K::Point_3* p = intersect_get<typename K::Point_3>(v);
CGAL_kernel_assertion(p!=nullptr);
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Triangle_3>(k.construct_segment_3_object()
(*p,tri.vertex(1)));
}
}
if (or2==ON_ORIENTED_BOUNDARY){
if (or1==or0)
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Triangle_3>(tri.vertex(2));
else{
pl_res v = intersection(plane, k.construct_line_3_object()(tri.vertex(0),tri.vertex(1)), k);
const typename K::Point_3* p = intersect_get<typename K::Point_3>(v);
CGAL_kernel_assertion(p!=nullptr);
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Triangle_3>(k.construct_segment_3_object()
(*p,tri.vertex(2)));
}
}
//triangle vertices are not in the plane
std::vector<typename K::Point_3> pts;
pts.reserve(2);
if (or0!=or1){
pl_res v = intersection(plane, k.construct_line_3_object()(tri.vertex(0),tri.vertex(1)), k);
const typename K::Point_3* pt_ptr = intersect_get<typename K::Point_3>(v);
CGAL_kernel_assertion( pt_ptr!=nullptr );
pts.push_back( *pt_ptr );
}
if (or0!=or2){
pl_res v = intersection(plane, k.construct_line_3_object()(tri.vertex(0),tri.vertex(2)), k);
const typename K::Point_3* pt_ptr = intersect_get<typename K::Point_3>(v);
CGAL_kernel_assertion( pt_ptr!=nullptr );
pts.push_back( *pt_ptr );
}
if (or1!=or2){
pl_res v = intersection(plane, k.construct_line_3_object()(tri.vertex(1),tri.vertex(2)), k);
const typename K::Point_3* pt_ptr = intersect_get<typename K::Point_3>(v);
CGAL_kernel_assertion( pt_ptr!=nullptr );
pts.push_back( *pt_ptr );
}
if (pts.empty()) return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Triangle_3>();
CGAL_kernel_assertion(pts.size()==2);
return intersection_return<typename K::Intersect_3, typename K::Plane_3, typename K::Triangle_3>( k.construct_segment_3_object()
(*pts.begin(),*boost::prior(pts.end())) );
}
template <class K>
inline
typename Intersection_traits<K, typename K::Triangle_3, typename K::Plane_3>::result_type
intersection(const typename K::Triangle_3 &triangle,
const typename K::Plane_3 &plane,
const K& k)
{
return intersection(plane, triangle, k);
}
template <class K>
typename Intersection_traits<K, typename K::Line_3, Bbox_3>::result_type
intersection(const typename K::Line_3 &line,
const Bbox_3 &box,
const K&)
{
typedef typename K::Point_3 Point_3;
typedef typename K::Direction_3 Direction_3;
const Point_3 &linepoint = line.point();
const Direction_3 &linedir = line.direction();
return intersection_bl<K>(box,
CGAL::to_double(linepoint.x()),
CGAL::to_double(linepoint.y()),
CGAL::to_double(linepoint.z()),
CGAL::to_double(linedir.dx()),
CGAL::to_double(linedir.dy()),
CGAL::to_double(linedir.dz()),
true, true
);
}
template <class K>
inline
typename Intersection_traits<K, Bbox_3, typename K::Line_3>::result_type
intersection(const Bbox_3 &box,
const typename K::Line_3 &line,
const K& k)
{
return intersection(line, box, k);
}
template <class K>
typename Intersection_traits<K, typename K::Ray_3, Bbox_3>::result_type
intersection(const typename K::Ray_3 &ray,
const Bbox_3 &box,
const K&)
{
typedef typename K::Point_3 Point_3;
typedef typename K::Direction_3 Direction_3;
const Point_3 &linepoint = ray.source();
const Direction_3 &linedir = ray.direction();
return intersection_bl<K>(box,
CGAL::to_double(linepoint.x()),
CGAL::to_double(linepoint.y()),
CGAL::to_double(linepoint.z()),
CGAL::to_double(linedir.dx()),
CGAL::to_double(linedir.dy()),
CGAL::to_double(linedir.dz()),
false, true
);
}
template <class K>
inline
typename Intersection_traits<K, Bbox_3, typename K::Ray_3>::result_type
intersection(const Bbox_3 &box,
const typename K::Ray_3 &ray,
const K& k)
{
return intersection(ray, box, k);
}
template <class K>
typename Intersection_traits<K, typename K::Segment_3, Bbox_3>::result_type
intersection(const typename K::Segment_3 &seg,
const Bbox_3 &box,
const K&)
{
typedef typename K::Point_3 Point_3;
typedef typename K::Vector_3 Vector_3;
const Point_3 &linepoint = seg.source();
const Vector_3 &diffvec = seg.target()-linepoint;
return intersection_bl<K>(box,
CGAL::to_double(linepoint.x()),
CGAL::to_double(linepoint.y()),
CGAL::to_double(linepoint.z()),
CGAL::to_double(diffvec.x()),
CGAL::to_double(diffvec.y()),
CGAL::to_double(diffvec.z()),
false, false
);
}
template <class K>
inline
typename Intersection_traits<K, Bbox_3, typename K::Segment_3>::result_type
intersection(const Bbox_3 &box,
const typename K::Segment_3 &seg,
const K& k)
{
return intersection(seg, box, k);
}
template <class K>
inline
typename Intersection_traits<K, Bbox_3, Bbox_3>::result_type
intersection(const Bbox_3 &a,
const Bbox_3 &b,
const K&)
{
return CGAL::intersection<K>(a, b);
}
template <class K>
typename Intersection_traits<K, CGAL::Bbox_3, typename K::Iso_cuboid_3>::result_type
intersection(const CGAL::Bbox_3 &box,
const typename K::Iso_cuboid_3 &cub,
const K&)
{
typename K::Iso_cuboid_3 iso_cub(box);
return intersection(iso_cub, cub);
}
template <class K>
inline
typename Intersection_traits<K, typename K::Iso_cuboid_3, CGAL::Bbox_3>::result_type
intersection(const typename K::Iso_cuboid_3 &cub,
const CGAL::Bbox_3 &box,
const K& k)
{
return intersection(box,cub, k);
}
template <class K>
typename Intersection_traits<K, typename K::Line_3, typename K::Iso_cuboid_3>::result_type
intersection(const typename K::Line_3 &line,
const typename K::Iso_cuboid_3 &box,
const K&)
{
typedef typename K::Point_3 Point_3;
typedef typename K::Vector_3 Vector_3;
typedef typename K::Segment_3 Segment_3;
typedef typename K::FT FT;
bool all_values = true;
FT _min = 0, _max = 0; // initialization to stop compiler warning
Point_3 const & _ref_point=line.point();
Vector_3 const & _dir=line.direction().vector();
Point_3 const & _iso_min=(box.min)();
Point_3 const & _iso_max=(box.max)();
for (int i=0; i< _ref_point.dimension(); i++) {
if (_dir.homogeneous(i) == 0) {
if (_ref_point.cartesian(i) < _iso_min.cartesian(i)) {
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Iso_cuboid_3>();
}
if (_ref_point.cartesian(i) > _iso_max.cartesian(i)) {
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Iso_cuboid_3>();
}
} else {
FT newmin, newmax;
if (_dir.homogeneous(i) > 0) {
newmin = (_iso_min.cartesian(i) - _ref_point.cartesian(i)) /
_dir.cartesian(i);
newmax = (_iso_max.cartesian(i) - _ref_point.cartesian(i)) /
_dir.cartesian(i);
} else {
newmin = (_iso_max.cartesian(i) - _ref_point.cartesian(i)) /
_dir.cartesian(i);
newmax = (_iso_min.cartesian(i) - _ref_point.cartesian(i)) /
_dir.cartesian(i);
}
if (all_values) {
_min = newmin;
_max = newmax;
} else {
if (newmin > _min)
_min = newmin;
if (newmax < _max)
_max = newmax;
if (_max < _min) {
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Iso_cuboid_3>();
}
}
all_values = false;
}
}
CGAL_kernel_assertion(!all_values);
if (_max == _min) {
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Iso_cuboid_3>(Point_3(_ref_point + _dir * _min ));
}
return intersection_return<typename K::Intersect_3, typename K::Line_3, typename K::Iso_cuboid_3>(
Segment_3(_ref_point + _dir*_min, _ref_point + _dir*_max));
}
template <class K>
inline
typename Intersection_traits<K, typename K::Iso_cuboid_3, typename K::Line_3>::result_type
intersection(const typename K::Iso_cuboid_3 &box,
const typename K::Line_3 &line,
const K& k)
{
return intersection(line, box, k);
}
template <class K>
typename Intersection_traits<K, typename K::Ray_3, typename K::Iso_cuboid_3>::result_type
intersection(const typename K::Ray_3 &ray,
const typename K::Iso_cuboid_3 &box,
const K&)
{
typedef typename K::Point_3 Point_3;
typedef typename K::Vector_3 Vector_3;
typedef typename K::Segment_3 Segment_3;
typedef typename K::FT FT;
bool all_values = true;
FT _min = 0, _max = 0; // initialization to prevent compiler warning
Point_3 const & _ref_point=ray.source();
Vector_3 const & _dir=ray.direction().vector();
Point_3 const & _iso_min=(box.min)();
Point_3 const & _iso_max=(box.max)();
for (int i=0; i< _ref_point.dimension(); i++) {
if (_dir.homogeneous(i) == 0) {
if (_ref_point.cartesian(i) < _iso_min.cartesian(i)) {
return intersection_return<typename K::Intersect_3, typename K::Ray_3, typename K::Iso_cuboid_3>();
}
if (_ref_point.cartesian(i) > _iso_max.cartesian(i)) {
return intersection_return<typename K::Intersect_3, typename K::Ray_3, typename K::Iso_cuboid_3>();
}
} else {
FT newmin, newmax;
if (_dir.homogeneous(i) > 0) {
newmin = (_iso_min.cartesian(i) - _ref_point.cartesian(i)) /
_dir.cartesian(i);
newmax = (_iso_max.cartesian(i) - _ref_point.cartesian(i)) /
_dir.cartesian(i);
} else {
newmin = (_iso_max.cartesian(i) - _ref_point.cartesian(i)) /
_dir.cartesian(i);
newmax = (_iso_min.cartesian(i) - _ref_point.cartesian(i)) /
_dir.cartesian(i);
}
if (all_values) {
_max = newmax;
} else {
if (newmax < _max)
_max = newmax;
}
if (newmin > _min)
_min = newmin;
if (_max < _min)
return intersection_return<typename K::Intersect_3, typename K::Ray_3, typename K::Iso_cuboid_3>();
all_values = false;
}
}
CGAL_kernel_assertion(!all_values);
if (_max == _min) {
return intersection_return<typename K::Intersect_3, typename K::Ray_3, typename K::Iso_cuboid_3>(Point_3(_ref_point + _dir * _min ));
}
return intersection_return<typename K::Intersect_3, typename K::Ray_3, typename K::Iso_cuboid_3>(
Segment_3(_ref_point + _dir*_min, _ref_point + _dir*_max));
}
template <class K>
inline
typename Intersection_traits<K, typename K::Iso_cuboid_3, typename K::Ray_3>::result_type
intersection(const typename K::Iso_cuboid_3 &box,
const typename K::Ray_3 &ray,
const K& k)
{
return intersection(ray, box, k);
}
template <class K>
typename Intersection_traits<K, typename K::Segment_3, typename K::Iso_cuboid_3>::result_type
intersection(const typename K::Segment_3 &seg,
const typename K::Iso_cuboid_3 &box,
const K&)
{
typedef typename K::Point_3 Point_3;
typedef typename K::Vector_3 Vector_3;
typedef typename K::Segment_3 Segment_3;
typedef typename K::FT FT;
FT _min = 0, _max;
Point_3 const & _ref_point=seg.source();
Vector_3 const & _dir=seg.direction().vector();
Point_3 const & _iso_min=(box.min)();
Point_3 const & _iso_max=(box.max)();
int main_dir =
(CGAL_NTS abs(_dir.x()) > CGAL_NTS abs(_dir.y()) )
? (CGAL_NTS abs(_dir.x()) > CGAL_NTS abs(_dir.z()) ? 0 : 2)
: (CGAL_NTS abs(_dir.y()) > CGAL_NTS abs(_dir.z()) ? 1 : 2);
_max = (seg.target().cartesian(main_dir)-_ref_point.cartesian(main_dir)) /
_dir.cartesian(main_dir);
for (int i=0; i< _ref_point.dimension(); i++) {
if (_dir.homogeneous(i) == 0) {
if (_ref_point.cartesian(i) < _iso_min.cartesian(i)) {
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Iso_cuboid_3>();
}
if (_ref_point.cartesian(i) > _iso_max.cartesian(i)) {
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Iso_cuboid_3>();
}
} else {
FT newmin, newmax;
if (_dir.homogeneous(i) > 0) {
newmin = (_iso_min.cartesian(i) - _ref_point.cartesian(i)) /
_dir.cartesian(i);
newmax = (_iso_max.cartesian(i) - _ref_point.cartesian(i)) /
_dir.cartesian(i);
} else {
newmin = (_iso_max.cartesian(i) - _ref_point.cartesian(i)) /
_dir.cartesian(i);
newmax = (_iso_min.cartesian(i) - _ref_point.cartesian(i)) /
_dir.cartesian(i);
}
if (newmax < _max)
_max = newmax;
if (newmin > _min)
_min = newmin;
if (_max < _min)
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Iso_cuboid_3>();
}
}
if (_max == _min) {
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Iso_cuboid_3>(Point_3(_ref_point + _dir * _min ));
}
return intersection_return<typename K::Intersect_3, typename K::Segment_3, typename K::Iso_cuboid_3>(
Segment_3(_ref_point + _dir*_min, _ref_point + _dir*_max));
}
template <class K>
inline
typename Intersection_traits<K, typename K::Iso_cuboid_3, typename K::Segment_3>::result_type
intersection(const typename K::Iso_cuboid_3 &box,
const typename K::Segment_3 &seg,
const K& k)
{
return intersection(seg, box, k);
}
template <class K>
typename Intersection_traits<K, typename K::Iso_cuboid_3, typename K::Iso_cuboid_3>::result_type
intersection(
const typename K::Iso_cuboid_3 &icub1,
const typename K::Iso_cuboid_3 &icub2,
const K&)
{
typedef typename K::Point_3 Point_3;
typedef typename K::Iso_cuboid_3 Iso_cuboid_3;
Point_3 min_points[2];
Point_3 max_points[2];
min_points[0] = (icub1.min)();
min_points[1] = (icub2.min)();
max_points[0] = (icub1.max)();
max_points[1] = (icub2.max)();
const int DIM = 3;
int min_idx[DIM];
int max_idx[DIM];
Point_3 newmin;
Point_3 newmax;
for (int dim = 0; dim < DIM; ++dim) {
min_idx[dim] =
min_points[0].cartesian(dim) >= min_points[1].cartesian(dim) ? 0 : 1;
max_idx[dim] =
max_points[0].cartesian(dim) <= max_points[1].cartesian(dim) ? 0 : 1;
if (min_idx[dim] != max_idx[dim]
&& max_points[max_idx[dim]].cartesian(dim)
< min_points[min_idx[dim]].cartesian(dim))
return intersection_return<typename K::Intersect_3, typename K::Iso_cuboid_3, typename K::Iso_cuboid_3>();
}
if (min_idx[0] == min_idx[1] && min_idx[0] == min_idx[2]) {
newmin = min_points[min_idx[0]];
} else {
newmin = Point_3(
min_idx[0] == 0
? wmult_hw((K*)0, min_points[0].hx(), min_points[1])
: wmult_hw((K*)0, min_points[1].hx(), min_points[0])
,
min_idx[1] == 0
? wmult_hw((K*)0, min_points[0].hy(), min_points[1])
: wmult_hw((K*)0, min_points[1].hy(), min_points[0])
,
min_idx[2] == 0
? wmult_hw((K*)0, min_points[0].hz(), min_points[1])
: wmult_hw((K*)0, min_points[1].hz(), min_points[0])
,
wmult_hw((K*)0, min_points[0].hw(), min_points[1]) );
}
if (max_idx[0] == max_idx[1] && max_idx[0] == max_idx[2]) {
newmax = max_points[max_idx[0]];
} else {
newmax = Point_3(
max_idx[0] == 0
? wmult_hw((K*)0, max_points[0].hx(), max_points[1])
: wmult_hw((K*)0, max_points[1].hx(), max_points[0])
,
max_idx[1] == 0
? wmult_hw((K*)0, max_points[0].hy(), max_points[1])
: wmult_hw((K*)0, max_points[1].hy(), max_points[0])
,
max_idx[2] == 0
? wmult_hw((K*)0, max_points[0].hz(), max_points[1])
: wmult_hw((K*)0, max_points[1].hz(), max_points[0])
,
wmult_hw((K*)0, max_points[0].hw(), max_points[1]) );
}
return intersection_return<typename K::Intersect_3, typename K::Iso_cuboid_3, typename K::Iso_cuboid_3>(Iso_cuboid_3(newmin, newmax));
}
template <class R>
inline bool
do_intersect(const Plane_3<R>& plane1, const Plane_3<R>& plane2, const R&)
{
return bool(intersection(plane1, plane2));
}
template <class R>
inline bool
do_intersect(const Plane_3<R> &plane1, const Plane_3<R> &plane2,
const Plane_3<R> &plane3, const R& r)
{
return bool(intersection(plane1, plane2, plane3, r));
}
template <class R>
inline bool
do_intersect(const Iso_cuboid_3<R> &i, const Iso_cuboid_3<R> &j, const R&)
{
return bool(CGAL::intersection(i, j));
}
template <class R>
inline bool
do_intersect(const Line_3<R> &l, const Iso_cuboid_3<R> &j, const R&)
{
return bool(CGAL::intersection(l, j));
}
template <class R>
inline bool
do_intersect(const Iso_cuboid_3<R> &j, const Line_3<R> &l, const R&)
{
return bool(CGAL::intersection(l, j));
}
} // namespace internal
} // namespace Intersections
} // namespace CGAL
#endif // CGAL_INTERSECTIONS_3_INTERNAL_INTERSECTION_3_1_IMPL_H
|
jjcasmar/cgal | Surface_mesh_simplification/doc/Surface_mesh_simplification/Concepts/GetCost.h | <filename>Surface_mesh_simplification/doc/Surface_mesh_simplification/Concepts/GetCost.h
/*!
\ingroup PkgSurfaceMeshSimplificationConcepts
\cgalConcept
The concept `GetCost` describes the requirements for the <I>policy function object</I>
which gets the <I>collapse cost</I> of an edge.
The cost returned is a `boost::optional` value (i.e.\ it can be absent).
An <I>absent</I> cost indicates that the edge should not be collapsed.
This could be the result of a computational limitation (such as an overflow),
or can be intentionally returned to prevent the edge from being collapsed.
\cgalRefines `DefaultConstructible`
\cgalRefines `CopyConstructible`
\cgalHasModel `CGAL::Surface_mesh_simplification::Edge_length_cost<TriangleMesh>`
\cgalHasModel `CGAL::Surface_mesh_simplification::LindstromTurk_cost<TriangleMesh>`
\cgalHasModel `CGAL::Surface_mesh_simplification::GarlandHeckbert_policies<TriangleMesh, GeomTraits>`
*/
class GetCost
{
public:
/// The class Edge_profile regroups useful information about an edge, such as its incident vertices and faces.
typedef CGAL::Surface_mesh_simplification::Edge_profile Edge_profile;
/// \name Operations
/// @{
/*!
Computes and returns the cost of collapsing the edge (represented by its profile),
using the calculated placement.
*/
boost::optional<typename Edge_profile::FT> operator()(const Edge_profile& edge_profile,
const boost::optional<typename Edge_profile::Point>& placement) const;
/// @}
}; /* end GetCost */
|
jjcasmar/cgal | Polygon_mesh_processing/include/CGAL/Polygon_mesh_processing/internal/Isotropic_remeshing/remesh_impl.h | // Copyright (c) 2015 GeometryFactory (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
//
// Author(s) : <NAME>
#ifndef CGAL_POLYGON_MESH_PROCESSING_REMESH_IMPL_H
#define CGAL_POLYGON_MESH_PROCESSING_REMESH_IMPL_H
#include <CGAL/license/Polygon_mesh_processing/meshing_hole_filling.h>
#include <CGAL/Polygon_mesh_processing/compute_normal.h>
#include <CGAL/Polygon_mesh_processing/border.h>
#include <CGAL/Polygon_mesh_processing/repair.h>
#include <CGAL/Polygon_mesh_processing/measure.h>
#include <CGAL/Polygon_mesh_processing/connected_components.h>
#include <CGAL/Polygon_mesh_processing/shape_predicates.h>
#include <CGAL/AABB_tree.h>
#include <CGAL/AABB_traits.h>
#include <CGAL/AABB_triangle_primitive.h>
#include <CGAL/property_map.h>
#include <CGAL/iterator.h>
#include <CGAL/boost/graph/Euler_operations.h>
#include <CGAL/boost/graph/properties.h>
#include <boost/graph/graph_traits.hpp>
#include <CGAL/tags.h>
#include <boost/bimap.hpp>
#include <boost/bimap/multiset_of.hpp>
#include <boost/bimap/set_of.hpp>
#include <boost/range.hpp>
#include <boost/range/join.hpp>
#include <boost/unordered_map.hpp>
#include <boost/unordered_set.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/container/flat_set.hpp>
#include <map>
#include <list>
#include <vector>
#include <iterator>
#include <fstream>
#ifdef CGAL_PMP_REMESHING_DEBUG
#include <CGAL/Polygon_mesh_processing/self_intersections.h>
#define CGAL_DUMP_REMESHING_STEPS
#define CGAL_PMP_REMESHING_VERBOSE_PROGRESS
#endif
#ifdef CGAL_PMP_REMESHING_VERY_VERBOSE
#define CGAL_PMP_REMESHING_VERBOSE
#define CGAL_PMP_REMESHING_VERBOSE_PROGRESS
#endif
#ifdef CGAL_PMP_REMESHING_VERBOSE_PROGRESS
#define CGAL_PMP_REMESHING_VERBOSE
#endif
namespace CGAL {
namespace PMP = Polygon_mesh_processing;
namespace Polygon_mesh_processing {
namespace internal {
enum Halfedge_status {
PATCH, //h and hopp belong to the patch to be remeshed
PATCH_BORDER,//h belongs to the patch, hopp is MESH
MESH, //h and hopp belong to the mesh, not the patch
MESH_BORDER //h belongs to the mesh, face(hopp, pmesh) == null_face()
};
// A property map
template <typename PM, typename FaceIndexMap>
struct Border_constraint_pmap
{
typedef typename boost::graph_traits<PM>::halfedge_descriptor halfedge_descriptor;
typedef typename boost::graph_traits<PM>::edge_descriptor edge_descriptor;
typedef FaceIndexMap FIMap;
boost::shared_ptr< std::set<edge_descriptor> > border_edges_ptr;
const PM* pmesh_ptr_;
public:
typedef edge_descriptor key_type;
typedef bool value_type;
typedef value_type& reference;
typedef boost::read_write_property_map_tag category;
Border_constraint_pmap()
: border_edges_ptr(new std::set<edge_descriptor>() )
, pmesh_ptr_(nullptr)
{}
template <class FaceRange>
Border_constraint_pmap(const PM& pmesh
, const FaceRange& faces
, const FIMap& fimap)
: border_edges_ptr(new std::set<edge_descriptor>() )
, pmesh_ptr_(&pmesh)
{
std::vector<halfedge_descriptor> border;
PMP::border_halfedges(faces, *pmesh_ptr_, std::back_inserter(border)
, PMP::parameters::face_index_map(fimap));
for(halfedge_descriptor h : border)
border_edges_ptr->insert(edge(h, *pmesh_ptr_));
}
friend bool get(const Border_constraint_pmap<PM, FIMap>& map,
const edge_descriptor& e)
{
CGAL_assertion(map.pmesh_ptr_!=nullptr);
return map.border_edges_ptr->count(e)!=0;
}
friend void put(Border_constraint_pmap<PM, FIMap>& map,
const edge_descriptor& e,
const bool is)
{
CGAL_assertion(map.pmesh_ptr_ != nullptr);
if (is)
map.border_edges_ptr->insert(e);
else
map.border_edges_ptr->erase(e);
}
};
template <typename PM,
typename FaceIndexMap>
struct Connected_components_pmap
{
typedef typename boost::graph_traits<PM>::face_descriptor face_descriptor;
typedef std::size_t Patch_id;
typedef FaceIndexMap FIMap;
typedef Connected_components_pmap<PM, FIMap> CCMap;
typedef CGAL::dynamic_face_property_t<Patch_id> Face_property_tag;
typedef typename boost::property_map<PM, Face_property_tag >::type Patch_ids_map;
Patch_ids_map patch_ids_map;
std::size_t nb_cc;
template <class Range>
bool same_range(const Range& r1, const Range& r2)
{
return boost::begin(r1)==boost::begin(r2) &&
boost::end(r1)==boost::end(r2);
}
template <class Range1, class Range2>
bool same_range(const Range1& r1, const Range2& r2)
{
return std::distance(boost::begin(r1), boost::end(r1)) ==
std::distance(boost::begin(r2), boost::end(r2));
}
public:
typedef face_descriptor key_type;
typedef Patch_id value_type;
typedef Patch_id& reference;
typedef boost::read_write_property_map_tag category;
//note pmesh is a non-const ref because properties are added and removed
//modify the mesh data structure, but not the mesh itself
template <class FaceRange, class EdgeIsConstrainedMap>
Connected_components_pmap(const FaceRange& face_range
, PM& pmesh
, EdgeIsConstrainedMap ecmap
, FIMap fimap
, const bool do_init = true)
{
patch_ids_map = get(Face_property_tag(),pmesh);
if (do_init)
{
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << "Compute connected components property map." << std::endl;
#endif
if ( same_range(face_range, (faces(pmesh))) )
{
// applied on the whole mesh
nb_cc
= PMP::connected_components(pmesh,
patch_ids_map,
PMP::parameters::edge_is_constrained_map(ecmap)
.face_index_map(fimap));
}
else
{
// applied on a subset of the mesh
nb_cc
= PMP::connected_components(pmesh,
patch_ids_map,
PMP::parameters::edge_is_constrained_map(
make_OR_property_map(ecmap
, internal::Border_constraint_pmap<PM, FIMap>(pmesh, face_range, fimap) ) )
.face_index_map(fimap));
}
}
else
nb_cc=0; // default value
}
friend value_type get(const CCMap& m, const key_type& f)
{
if (m.nb_cc == 1)
return 0;
return get(m.patch_ids_map, f);
}
friend void put(CCMap& m, const key_type& f, const value_type i)
{
if (m.nb_cc != 1)
put(m.patch_ids_map, f, i);
}
};
template<typename PM,
typename EdgeConstraintMap,
typename VertexPointMap,
typename FacePatchMap>
bool constraints_are_short_enough(const PM& pmesh,
EdgeConstraintMap ecmap,
VertexPointMap vpmap,
const FacePatchMap& fpm,
const double& high)
{
double sqh = high*high;
typedef typename boost::graph_traits<PM>::halfedge_descriptor halfedge_descriptor;
typedef typename boost::graph_traits<PM>::edge_descriptor edge_descriptor;
for(edge_descriptor e : edges(pmesh))
{
halfedge_descriptor h = halfedge(e, pmesh);
if ( is_border(e, pmesh) ||
get(ecmap, e) ||
get(fpm, face(h,pmesh))!=get(fpm, face(opposite(h,pmesh),pmesh)) )
{
if (sqh < CGAL::squared_distance(get(vpmap, source(h, pmesh)),
get(vpmap, target(h, pmesh))))
{
return false;
}
}
}
return true;
}
template<typename PolygonMesh
, typename VertexPointMap
, typename GeomTraits
, typename EdgeIsConstrainedMap
, typename VertexIsConstrainedMap
, typename FacePatchMap
, typename FaceIndexMap
>
class Incremental_remesher
{
typedef PolygonMesh PM;
typedef typename boost::graph_traits<PM>::halfedge_descriptor halfedge_descriptor;
typedef typename boost::graph_traits<PM>::edge_descriptor edge_descriptor;
typedef typename boost::graph_traits<PM>::vertex_descriptor vertex_descriptor;
typedef typename boost::graph_traits<PM>::face_descriptor face_descriptor;
typedef typename GeomTraits::Point_3 Point;
typedef typename GeomTraits::Vector_3 Vector_3;
typedef typename GeomTraits::Plane_3 Plane_3;
typedef typename GeomTraits::Triangle_3 Triangle_3;
typedef Incremental_remesher<PM, VertexPointMap
, GeomTraits
, EdgeIsConstrainedMap
, VertexIsConstrainedMap
, FacePatchMap
, FaceIndexMap
> Self;
private:
typedef typename boost::property_traits<FacePatchMap>::value_type Patch_id;
typedef std::vector<Triangle_3> Triangle_list;
typedef std::vector<Patch_id> Patch_id_list;
typedef std::map<Patch_id,std::size_t> Patch_id_to_index_map;
typedef CGAL::AABB_triangle_primitive<GeomTraits,
typename Triangle_list::iterator> AABB_primitive;
typedef CGAL::AABB_traits<GeomTraits, AABB_primitive> AABB_traits;
typedef CGAL::AABB_tree<AABB_traits> AABB_tree;
typedef typename boost::property_map<
PM, CGAL::dynamic_halfedge_property_t<Halfedge_status> >::type Halfedge_status_pmap;
public:
Incremental_remesher(PolygonMesh& pmesh
, VertexPointMap& vpmap
, const GeomTraits& gt
, const bool protect_constraints
, EdgeIsConstrainedMap ecmap
, VertexIsConstrainedMap vcmap
, FacePatchMap fpmap
, FaceIndexMap fimap
, const bool build_tree = true)//built by the remesher
: mesh_(pmesh)
, vpmap_(vpmap)
, gt_(gt)
, build_tree_(build_tree)
, has_border_(false)
, input_triangles_()
, input_patch_ids_()
, protect_constraints_(protect_constraints)
, patch_ids_map_(fpmap)
, ecmap_(ecmap)
, vcmap_(vcmap)
, fimap_(fimap)
{
halfedge_status_pmap_ = get(CGAL::dynamic_halfedge_property_t<Halfedge_status>(),
pmesh);
CGAL_assertion_code(input_mesh_is_valid_ = CGAL::is_valid_polygon_mesh(pmesh));
CGAL_warning_msg(input_mesh_is_valid_,
"The input mesh is not a valid polygon mesh. "
"It could lead PMP::isotropic_remeshing() to fail.");
}
~Incremental_remesher()
{
if (build_tree_){
for(std::size_t i=0; i < trees.size();++i){
delete trees[i];
}
}
}
template<typename FaceRange>
void init_remeshing(const FaceRange& face_range)
{
tag_halfedges_status(face_range); //called first
for(face_descriptor f : face_range)
{
if(is_degenerate_triangle_face(f, mesh_, parameters::vertex_point_map(vpmap_)
.geom_traits(gt_)))
continue;
Patch_id pid = get_patch_id(f);
input_triangles_.push_back(triangle(f));
input_patch_ids_.push_back(pid);
std::pair<typename Patch_id_to_index_map::iterator, bool>
res = patch_id_to_index_map.insert(std::make_pair(pid,0));
if(res.second){
res.first->second = patch_id_to_index_map.size()-1;
}
}
CGAL_assertion(input_triangles_.size() == input_patch_ids_.size());
if (!build_tree_)
return;
trees.resize(patch_id_to_index_map.size());
for(std::size_t i=0; i < trees.size(); ++i){
trees[i] = new AABB_tree();
}
typename Triangle_list::iterator it;
typename Patch_id_list::iterator pit;
for(it = input_triangles_.begin(), pit = input_patch_ids_.begin();
it != input_triangles_.end();
++it, ++pit){
trees[patch_id_to_index_map[*pit]]->insert(it);
}
for(std::size_t i=0; i < trees.size(); ++i){
trees[i]->build();
}
}
// split edges of edge_range that have their length > high
// Note: only used to split a range of edges provided as input
template<typename EdgeRange>
void split_long_edges(const EdgeRange& edge_range,
const double& high)
{
typedef boost::bimap<
boost::bimaps::set_of<halfedge_descriptor>,
boost::bimaps::multiset_of<double, std::greater<double> > > Boost_bimap;
typedef typename Boost_bimap::value_type long_edge;
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << "Split long edges (" << high << ")...";
std::cout.flush();
#endif
double sq_high = high*high;
//collect long edges
Boost_bimap long_edges;
for(edge_descriptor e : edge_range)
{
double sqlen = sqlength(e);
if (sqlen > sq_high)
long_edges.insert(long_edge(halfedge(e, mesh_), sqlen));
}
//split long edges
unsigned int nb_splits = 0;
while (!long_edges.empty())
{
//the edge with longest length
typename Boost_bimap::right_map::iterator eit = long_edges.right.begin();
halfedge_descriptor he = eit->second;
double sqlen = eit->first;
long_edges.right.erase(eit);
//split edge
Point refinement_point = this->midpoint(he);
halfedge_descriptor hnew = CGAL::Euler::split_edge(he, mesh_);
// propagate the constrained status
put(ecmap_, edge(hnew, mesh_), get(ecmap_, edge(he, mesh_)));
CGAL_assertion(he == next(hnew, mesh_));
++nb_splits;
//move refinement point
vertex_descriptor vnew = target(hnew, mesh_);
put(vpmap_, vnew, refinement_point);
#ifdef CGAL_PMP_REMESHING_VERY_VERBOSE
std::cout << " refinement point : " << refinement_point << std::endl;
#endif
//check sub-edges
double sqlen_new = 0.25 * sqlen;
if (sqlen_new > sq_high)
{
//if it was more than twice the "long" threshold, insert them
long_edges.insert(long_edge(hnew, sqlen_new));
long_edges.insert(long_edge(next(hnew, mesh_), sqlen_new));
}
//insert new edges to keep triangular faces, and update long_edges
if (!is_border(hnew, mesh_))
{
halfedge_descriptor hnew2 =
CGAL::Euler::split_face(hnew, next(next(hnew, mesh_), mesh_), mesh_);
put(ecmap_, edge(hnew2, mesh_), false);
}
//do it again on the other side if we're not on boundary
halfedge_descriptor hnew_opp = opposite(hnew, mesh_);
if (!is_border(hnew_opp, mesh_))
{
halfedge_descriptor hnew2 =
CGAL::Euler::split_face(prev(hnew_opp, mesh_), next(hnew_opp, mesh_), mesh_);
put(ecmap_, edge(hnew2, mesh_), false);
}
}
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << " done (" << nb_splits << " splits)." << std::endl;
#endif
#ifdef CGAL_DUMP_REMESHING_STEPS
dump("0-border_split.off");
#endif
}
// PMP book :
// "visits all edges of the mesh
//if an edge is longer than the given threshold `high`, the edge
//is split at its midpoint and the two adjacent triangles are bisected (2-4 split)"
void split_long_edges(const double& high)
{
typedef boost::bimap<
boost::bimaps::set_of<halfedge_descriptor>,
boost::bimaps::multiset_of<double, std::greater<double> > > Boost_bimap;
typedef typename Boost_bimap::value_type long_edge;
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << "Split long edges (" << high << ")..." << std::endl;
#endif
double sq_high = high*high;
//collect long edges
Boost_bimap long_edges;
for(edge_descriptor e : edges(mesh_))
{
if (!is_split_allowed(e))
continue;
double sqlen = sqlength(e);
if(sqlen > sq_high)
long_edges.insert(long_edge(halfedge(e, mesh_), sqlen));
}
//split long edges
unsigned int nb_splits = 0;
while (!long_edges.empty())
{
//the edge with longest length
typename Boost_bimap::right_map::iterator eit = long_edges.right.begin();
halfedge_descriptor he = eit->second;
double sqlen = eit->first;
long_edges.right.erase(eit);
#ifdef CGAL_PMP_REMESHING_VERBOSE_PROGRESS
std::cout << "\r\t(" << long_edges.left.size() << " long edges, ";
std::cout << nb_splits << " splits)";
std::cout.flush();
#endif
if (protect_constraints_ && !is_longest_on_faces(edge(he, mesh_)))
continue;
//collect patch_ids
Patch_id patch_id = get_patch_id(face(he, mesh_));
Patch_id patch_id_opp = get_patch_id(face(opposite(he, mesh_), mesh_));
//split edge
Point refinement_point = this->midpoint(he);
halfedge_descriptor hnew = CGAL::Euler::split_edge(he, mesh_);
CGAL_assertion(he == next(hnew, mesh_));
put(ecmap_, edge(hnew, mesh_), get(ecmap_, edge(he, mesh_)) );
++nb_splits;
//move refinement point
vertex_descriptor vnew = target(hnew, mesh_);
put(vpmap_, vnew, refinement_point);
#ifdef CGAL_PMP_REMESHING_VERY_VERBOSE
std::cout << " Refinement point : " << refinement_point << std::endl;
#endif
//after splitting
halfedge_descriptor hnew_opp = opposite(hnew, mesh_);
halfedge_added(hnew, status(he));
halfedge_added(hnew_opp, status(opposite(he, mesh_)));
//check sub-edges
double sqlen_new = 0.25 * sqlen;
if (sqlen_new > sq_high)
{
//if it was more than twice the "long" threshold, insert them
long_edges.insert(long_edge(hnew, sqlen_new));
long_edges.insert(long_edge(next(hnew, mesh_), sqlen_new));
}
//insert new edges to keep triangular faces, and update long_edges
if (!is_on_border(hnew))
{
halfedge_descriptor hnew2 = CGAL::Euler::split_face(hnew,
next(next(hnew, mesh_), mesh_),
mesh_);
put(ecmap_, edge(hnew2, mesh_), false);
Halfedge_status snew = (is_on_patch(hnew) || is_on_patch_border(hnew))
? PATCH
: MESH;
halfedge_added(hnew2, snew);
halfedge_added(opposite(hnew2, mesh_), snew);
set_patch_id(face(hnew2, mesh_), patch_id);
set_patch_id(face(opposite(hnew2, mesh_), mesh_), patch_id);
if (snew == PATCH)
{
double sql = sqlength(hnew2);
if (sql > sq_high)
long_edges.insert(long_edge(hnew2, sql));
}
}
//do it again on the other side if we're not on boundary
if (!is_on_border(hnew_opp))
{
halfedge_descriptor hnew2 = CGAL::Euler::split_face(prev(hnew_opp, mesh_),
next(hnew_opp, mesh_),
mesh_);
put(ecmap_, edge(hnew2, mesh_), false);
Halfedge_status snew = (is_on_patch(hnew_opp) || is_on_patch_border(hnew_opp))
? PATCH
: MESH;
halfedge_added(hnew2, snew);
halfedge_added(opposite(hnew2, mesh_), snew);
set_patch_id(face(hnew2, mesh_), patch_id_opp);
set_patch_id(face(opposite(hnew2, mesh_), mesh_), patch_id_opp);
if (snew == PATCH)
{
double sql = sqlength(hnew2);
if (sql > sq_high)
long_edges.insert(long_edge(hnew2, sql));
}
}
}
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << " done ("<< nb_splits << " splits)." << std::endl;
#endif
#ifdef CGAL_PMP_REMESHING_DEBUG
debug_status_map();
debug_self_intersections();
#endif
#ifdef CGAL_DUMP_REMESHING_STEPS
dump("1-edge_split.off");
#endif
}
// PMP book :
// "collapses and thus removes all edges that are shorter than a
// threshold `low`. [...] testing before each collapse whether the collapse
// would produce an edge that is longer than `high`"
void collapse_short_edges(const double& low,
const double& high,
const bool collapse_constraints)
{
typedef boost::bimap<
boost::bimaps::set_of<halfedge_descriptor>,
boost::bimaps::multiset_of<double, std::less<double> > > Boost_bimap;
typedef typename Boost_bimap::value_type short_edge;
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << "Collapse short edges (" << low << ", " << high << ")..."
<< std::endl;
#endif
#ifdef CGAL_PMP_REMESHING_VERBOSE_PROGRESS
std::cout << "Fill bimap...";
std::cout.flush();
#endif
double sq_low = low*low;
double sq_high = high*high;
Boost_bimap short_edges;
for(edge_descriptor e : edges(mesh_))
{
double sqlen = sqlength(e);
if ((sqlen < sq_low) && is_collapse_allowed(e, collapse_constraints))
short_edges.insert(short_edge(halfedge(e, mesh_), sqlen));
}
#ifdef CGAL_PMP_REMESHING_VERBOSE_PROGRESS
std::cout << "done." << std::endl;
#endif
unsigned int nb_collapses = 0;
while (!short_edges.empty())
{
//the edge with shortest length
typename Boost_bimap::right_map::iterator eit = short_edges.right.begin();
halfedge_descriptor he = eit->second;
short_edges.right.erase(eit);
#ifdef CGAL_PMP_REMESHING_VERBOSE_PROGRESS
std::cout << "\r\t(" << short_edges.left.size() << " short edges, ";
std::cout << nb_collapses << " collapses)";
std::cout.flush();
#endif
edge_descriptor e = edge(he, mesh_);
if (!is_collapse_allowed(e, collapse_constraints))
continue; //situation could have changed since it was added to the bimap
//handle the boundary case :
//a PATCH_BORDER edge can be collapsed,
//and an edge incident to PATCH_BORDER can be collapsed,
//but only if the boundary vertex is kept,
//so re-insert opposite(he) to collapse it
if (!is_on_patch(he))
{
CGAL_assertion(!protect_constraints_);//is_collapse_allowed returned false
if (is_on_border(he) || is_on_mesh(he))
{
he = opposite(he, mesh_); //he now is PATCH_BORDER
e = edge(he, mesh_);
CGAL_assertion(is_on_patch_border(he));
}
}//end if(not on PATCH)
//let's try to collapse he into vb
vertex_descriptor va = source(he, mesh_);
vertex_descriptor vb = target(he, mesh_);
bool is_va_constrained = is_constrained(va) || is_corner(va);
bool is_vb_constrained = is_constrained(vb) || is_corner(vb);
// do not collapse edge with two constrained vertices
if (is_va_constrained && is_vb_constrained) continue;
bool can_swap = !is_vb_constrained;
//do not collapse an edge connecting two different constrained polylines
if (is_va_constrained && is_vb_constrained && !is_on_patch_border(he))
continue;
bool is_va_on_constrained_polyline = is_on_patch_border(va);
bool is_vb_on_constrained_polyline = is_on_patch_border(vb);
// swap if vb is not constrained and va is constrained or the only vertex on a constrained polyline
if (can_swap && (is_va_constrained || (is_va_on_constrained_polyline && !is_vb_on_constrained_polyline)))
{
he = opposite(he, mesh_);
e=edge(he, mesh_);
std::swap(va, vb);
// no need to swap is_vX_on_constrained_polyline and is_vX_constrained
can_swap=false;
}
if(collapse_would_invert_face(he))
{
if (can_swap//if swap allowed (no constrained vertices)
&& (!is_vb_on_constrained_polyline || is_va_on_constrained_polyline)
&& !collapse_would_invert_face(opposite(he, mesh_)))
{
he = opposite(he, mesh_);
e=edge(he, mesh_);
std::swap(va, vb);
}
else
continue;//both directions invert a face
}
CGAL_assertion(!collapse_would_invert_face(he));
CGAL_assertion(is_collapse_allowed(e, collapse_constraints));
if (!CGAL::Euler::does_satisfy_link_condition(e, mesh_))//necessary to collapse
continue;
//check that collapse would not create an edge with length > high
//iterate on vertices va_i of the one-ring of va
bool collapse_ok = true;
for(halfedge_descriptor ha : halfedges_around_target(va, mesh_))
{
vertex_descriptor va_i = source(ha, mesh_);
if (sqlength(vb, va_i) > sq_high)
{
collapse_ok = false;
break;
}
}
// before collapsing va into vb, check that it does not break a corner
// or a constrained vertex
if (collapse_ok)
{
//"collapse va into vb along e"
// remove edges incident to va and vb, because their lengths will change
for(halfedge_descriptor ha : halfedges_around_target(va, mesh_))
{
short_edges.left.erase(ha);
short_edges.left.erase(opposite(ha, mesh_));
}
for(halfedge_descriptor hb : halfedges_around_target(vb, mesh_))
{
short_edges.left.erase(hb);
short_edges.left.erase(opposite(hb, mesh_));
}
//before collapse
halfedge_descriptor he_opp= opposite(he, mesh_);
bool mesh_border_case = is_on_border(he);
bool mesh_border_case_opp = is_on_border(he_opp);
halfedge_descriptor ep_p = prev(he_opp, mesh_);
halfedge_descriptor en = next(he, mesh_);
halfedge_descriptor ep = prev(he, mesh_);
halfedge_descriptor en_p = next(he_opp, mesh_);
// merge halfedge_status to keep the more important on both sides
//do it before collapse is performed to be sure everything is valid
if (!mesh_border_case)
merge_and_update_status(en, ep);
if (!mesh_border_case_opp)
merge_and_update_status(en_p, ep_p);
if (!protect_constraints_)
put(ecmap_, e, false);
else
CGAL_assertion( !get(ecmap_, e) );
//perform collapse
CGAL_assertion(target(halfedge(e, mesh_), mesh_) == vb);
vertex_descriptor vkept = CGAL::Euler::collapse_edge(e, mesh_, ecmap_);
CGAL_assertion(is_valid(mesh_));
CGAL_assertion(vkept == vb);//is the constrained point still here
++nb_collapses;
//fix constrained case
CGAL_assertion((is_constrained(vkept) || is_corner(vkept) || is_on_patch_border(vkept)) ==
(is_va_constrained || is_vb_constrained || is_va_on_constrained_polyline || is_vb_on_constrained_polyline));
if (fix_degenerate_faces(vkept, short_edges, sq_low, collapse_constraints))
{
#ifdef CGAL_PMP_REMESHING_DEBUG
debug_status_map();
CGAL_assertion(!incident_to_degenerate(halfedge(vkept, mesh_)));
#endif
//insert new/remaining short edges
for (halfedge_descriptor ht : halfedges_around_target(vkept, mesh_))
{
double sqlen = sqlength(ht);
if ((sqlen < sq_low) && is_collapse_allowed(edge(ht, mesh_), collapse_constraints))
short_edges.insert(short_edge(ht, sqlen));
}
}
}//end if(collapse_ok)
}
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << " done (" << nb_collapses << " collapses)." << std::endl;
#endif
#ifdef CGAL_DUMP_REMESHING_STEPS
dump("2-edge_collapse.off");
#endif
#ifdef CGAL_PMP_REMESHING_DEBUG
debug_status_map();
debug_self_intersections();
CGAL_assertion(PMP::remove_degenerate_faces(mesh_,
parameters::vertex_point_map(vpmap_)
.geom_traits(gt_)));
#endif
}
// PMP book :
// "equalizes the vertex valences by flipping edges.
// The target valence is 6 and 4 for interior and boundary vertices, resp.
// The algo. tentatively flips each edge `e` and checks whether the deviation
// to the target valences decreases. If not, the edge is flipped back"
void equalize_valences()
{
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << "Equalize valences..." << std::endl;
#endif
unsigned int nb_flips = 0;
for(edge_descriptor e : edges(mesh_))
{
//only the patch edges are allowed to be flipped
if (!is_flip_allowed(e))
continue;
halfedge_descriptor he = halfedge(e, mesh_);
vertex_descriptor va = source(he, mesh_);
vertex_descriptor vb = target(he, mesh_);
vertex_descriptor vc = target(next(he, mesh_), mesh_);
vertex_descriptor vd = target(next(opposite(he, mesh_), mesh_), mesh_);
int vva = valence(va), tvva = target_valence(va);
int vvb = valence(vb), tvvb = target_valence(vb);
int vvc = valence(vc), tvvc = target_valence(vc);
int vvd = valence(vd), tvvd = target_valence(vd);
int deviation_pre = CGAL::abs(vva - tvva)
+ CGAL::abs(vvb - tvvb)
+ CGAL::abs(vvc - tvvc)
+ CGAL::abs(vvd - tvvd);
CGAL_assertion_code(Halfedge_status s1 = status(he));
CGAL_assertion_code(Halfedge_status s1o = status(opposite(he, mesh_)));
Patch_id pid = get_patch_id(face(he, mesh_));
CGAL_assertion( is_flip_topologically_allowed(edge(he, mesh_)) );
CGAL_assertion( !get(ecmap_, edge(he, mesh_)) );
CGAL::Euler::flip_edge(he, mesh_);
vva -= 1;
vvb -= 1;
vvc += 1;
vvd += 1;
++nb_flips;
#ifdef CGAL_PMP_REMESHING_VERBOSE_PROGRESS
std::cout << "\r\t(" << nb_flips << " flips)";
std::cout.flush();
#endif
CGAL_assertion_code(Halfedge_status s2 = status(he));
CGAL_assertion_code(Halfedge_status s2o = status(opposite(he, mesh_)));
CGAL_assertion(s1 == s2 && s1 == PATCH);
CGAL_assertion(s1o == s2o && s1o == PATCH);
CGAL_assertion(!is_border(he, mesh_));
CGAL_assertion(
(vc == target(he, mesh_) && vd == source(he, mesh_))
|| (vd == target(he, mesh_) && vc == source(he, mesh_)));
int deviation_post = CGAL::abs(vva - tvva)
+ CGAL::abs(vvb - tvvb)
+ CGAL::abs(vvc - tvvc)
+ CGAL::abs(vvd - tvvd);
//check that mesh does not become non-triangle,
//nor has inverted faces
if (deviation_pre <= deviation_post
|| !check_normals(he)
|| incident_to_degenerate(he)
|| incident_to_degenerate(opposite(he, mesh_))
|| !is_on_triangle(he)
|| !is_on_triangle(opposite(he, mesh_))
|| !check_normals(target(he, mesh_))
|| !check_normals(source(he, mesh_)))
{
CGAL_assertion( is_flip_topologically_allowed(edge(he, mesh_)) );
CGAL_assertion( !get(ecmap_, edge(he, mesh_)) );
CGAL::Euler::flip_edge(he, mesh_);
--nb_flips;
CGAL_assertion_code(Halfedge_status s3 = status(he));
CGAL_assertion(s1 == s3);
CGAL_assertion(!is_border(he, mesh_));
CGAL_assertion(
(va == source(he, mesh_) && vb == target(he, mesh_))
|| (vb == source(he, mesh_) && va == target(he, mesh_)));
}
set_patch_id(face(he, mesh_), pid);
set_patch_id(face(opposite(he, mesh_), mesh_), pid);
}
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << "\r\tdone ("<< nb_flips << " flips)" << std::endl;
#endif
#ifdef CGAL_PMP_REMESHING_DEBUG
debug_status_map();
CGAL_assertion(PMP::remove_degenerate_faces(mesh_,
PMP::parameters::vertex_point_map(vpmap_)
.geom_traits(gt_)));
debug_self_intersections();
#endif
#ifdef CGAL_DUMP_REMESHING_STEPS
dump("3-edge_flips.off");
#endif
}
// PMP book :
// "applies an iterative smoothing filter to the mesh.
// The vertex movement has to be constrained to the vertex tangent plane [...]
// smoothing algorithm with uniform Laplacian weights"
void tangential_relaxation(const bool relax_constraints/*1d smoothing*/
, const unsigned int nb_iterations)
{
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << "Tangential relaxation (" << nb_iterations << " iter.)...";
std::cout << std::endl;
#endif
for (unsigned int nit = 0; nit < nb_iterations; ++nit)
{
#ifdef CGAL_PMP_REMESHING_VERBOSE_PROGRESS
std::cout << "\r\t(iteration " << (nit + 1) << " / ";
std::cout << nb_iterations << ") ";
std::cout.flush();
#endif
//todo : use boost::vector_property_map to improve computing time
typedef std::map<vertex_descriptor, Vector_3> VNormalsMap;
VNormalsMap vnormals;
boost::associative_property_map<VNormalsMap> propmap_normals(vnormals);
std::map<vertex_descriptor, Point> barycenters;
// at each vertex, compute vertex normal
// at each vertex, compute barycenter of neighbors
for(vertex_descriptor v : vertices(mesh_))
{
if (is_constrained(v) || is_isolated(v))
continue;
else if (is_on_patch(v))
{
Vector_3 vn = PMP::compute_vertex_normal(v, mesh_,
parameters::vertex_point_map(vpmap_)
.geom_traits(gt_));
put(propmap_normals, v, vn);
Vector_3 move = CGAL::NULL_VECTOR;
unsigned int star_size = 0;
for(halfedge_descriptor h : halfedges_around_target(v, mesh_))
{
move = move + Vector_3(get(vpmap_, v), get(vpmap_, source(h, mesh_)));
++star_size;
}
CGAL_assertion(star_size > 0); //isolated vertices have already been discarded
move = (1. / (double)star_size) * move;
barycenters[v] = get(vpmap_, v) + move;
}
else if (relax_constraints
&& !protect_constraints_
&& is_on_patch_border(v)
&& !is_corner(v))
{
put(propmap_normals, v, CGAL::NULL_VECTOR);
std::vector<halfedge_descriptor> border_halfedges;
for(halfedge_descriptor h : halfedges_around_target(v, mesh_))
{
if (is_on_patch_border(h) || is_on_patch_border(opposite(h, mesh_)))
border_halfedges.push_back(h);
}
if (border_halfedges.size() == 2)//others are corner cases
{
vertex_descriptor ph0 = source(border_halfedges[0], mesh_);
vertex_descriptor ph1 = source(border_halfedges[1], mesh_);
double dot = to_double(Vector_3(get(vpmap_, v), get(vpmap_, ph0))
* Vector_3(get(vpmap_, v), get(vpmap_, ph1)));
//check squared cosine is < 0.25 (~120 degrees)
if (0.25 < dot / (sqlength(border_halfedges[0]) * sqlength(border_halfedges[0])))
barycenters[v] = CGAL::midpoint(midpoint(border_halfedges[0]),
midpoint(border_halfedges[1]));
}
}
}
// compute moves
typedef typename std::map<vertex_descriptor, Point>::value_type VP_pair;
std::map<vertex_descriptor, Point> new_locations;
for(const VP_pair& vp : barycenters)
{
vertex_descriptor v = vp.first;
Point pv = get(vpmap_, v);
Vector_3 nv = boost::get(propmap_normals, v);
Point qv = vp.second; //barycenter at v
new_locations[v] = qv + (nv * Vector_3(qv, pv)) * nv;
}
// perform moves
for(const VP_pair& vp : new_locations)
{
const Point initial_pos = get(vpmap_, vp.first);
const Vector_3 move(initial_pos, vp.second);
put(vpmap_, vp.first, vp.second);
//check that no inversion happened
double frac = 1.;
while (frac > 0.03 //5 attempts maximum
&& !check_normals(vp.first)) //if a face has been inverted
{
frac = 0.5 * frac;
put(vpmap_, vp.first, initial_pos + frac * move);//shorten the move by 2
}
if (frac <= 0.02)
put(vpmap_, vp.first, initial_pos);//cancel move
}
CGAL_assertion(!input_mesh_is_valid_ || is_valid_polygon_mesh(mesh_));
}//end for loop (nit == nb_iterations)
#ifdef CGAL_PMP_REMESHING_DEBUG
debug_self_intersections();
#endif
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << "done." << std::endl;
#endif
#ifdef CGAL_DUMP_REMESHING_STEPS
dump("4-relaxation.off");
#endif
}
// PMP book :
// "maps the vertices back to the surface"
void project_to_surface(internal_np::Param_not_found)
{
//todo : handle the case of boundary vertices
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << "Project to surface...";
std::cout.flush();
#endif
for(vertex_descriptor v : vertices(mesh_))
{
if (is_constrained(v) || is_isolated(v) || !is_on_patch(v))
continue;
//note if v is constrained, it has not moved
Point proj = trees[patch_id_to_index_map[get_patch_id(face(halfedge(v, mesh_), mesh_))]]->closest_point(get(vpmap_, v));
put(vpmap_, v, proj);
}
CGAL_assertion(!input_mesh_is_valid_ || is_valid_polygon_mesh(mesh_));
#ifdef CGAL_PMP_REMESHING_DEBUG
debug_self_intersections();
#endif
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << "done." << std::endl;
#endif
#ifdef CGAL_DUMP_REMESHING_STEPS
dump("5-project.off");
#endif
}
template <class ProjectionFunctor>
void project_to_surface(const ProjectionFunctor& proj)
{
//todo : handle the case of boundary vertices
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << "Project to surface...";
std::cout.flush();
#endif
for(vertex_descriptor v : vertices(mesh_))
{
if (is_constrained(v) || is_isolated(v) || !is_on_patch(v))
continue;
//note if v is constrained, it has not moved
put(vpmap_, v, proj(v));
}
CGAL_assertion(is_valid(mesh_));
#ifdef CGAL_PMP_REMESHING_DEBUG
debug_self_intersections();
#endif
#ifdef CGAL_PMP_REMESHING_VERBOSE
std::cout << "done." << std::endl;
#endif
#ifdef CGAL_DUMP_REMESHING_STEPS
dump("5-project.off");
#endif
}
private:
Patch_id get_patch_id(const face_descriptor& f) const
{
if (f == boost::graph_traits<PM>::null_face())
return Patch_id(-1);
return get(patch_ids_map_, f);
}
void set_patch_id(const face_descriptor& f, const Patch_id& i)
{
put(patch_ids_map_, f, i);
}
struct Patch_id_property_map
{
typedef boost::readable_property_map_tag category;
typedef Patch_id value_type;
typedef Patch_id& reference;
typedef typename Triangle_list::const_iterator key_type;
const Self* remesher_ptr_;
Patch_id_property_map()
: remesher_ptr_(nullptr) {}
Patch_id_property_map(const Self& remesher)
: remesher_ptr_(&remesher) {}
friend Patch_id get(const Patch_id_property_map& m, key_type tr_it)
{
//tr_it is an iterator from triangles_
std::size_t id_in_vec = std::distance(
m.remesher_ptr_->input_triangles().begin(), tr_it);
CGAL_assertion(id_in_vec < m.remesher_ptr_->input_patch_ids().size());
CGAL_assertion(*tr_it == m.remesher_ptr_->input_triangles()[id_in_vec]);
return m.remesher_ptr_->input_patch_ids()[id_in_vec];
}
};
private:
Triangle_3 triangle(face_descriptor f) const
{
halfedge_descriptor h = halfedge(f, mesh_);
vertex_descriptor v1 = target(h, mesh_);
vertex_descriptor v2 = target(next(h, mesh_), mesh_);
vertex_descriptor v3 = target(next(next(h, mesh_), mesh_), mesh_);
return Triangle_3(get(vpmap_, v1), get(vpmap_, v2), get(vpmap_, v3));
}
double sqlength(const vertex_descriptor& v1,
const vertex_descriptor& v2) const
{
return to_double(CGAL::squared_distance(get(vpmap_, v1), get(vpmap_, v2)));
}
double sqlength(const halfedge_descriptor& h) const
{
vertex_descriptor v1 = target(h, mesh_);
vertex_descriptor v2 = source(h, mesh_);
return sqlength(v1, v2);
}
double sqlength(const edge_descriptor& e) const
{
return sqlength(halfedge(e, mesh_));
}
Point midpoint(const halfedge_descriptor& he) const
{
Point p1 = get(vpmap_, target(he, mesh_));
Point p2 = get(vpmap_, source(he, mesh_));
return CGAL::midpoint(p1, p2);
}
void dump(const char* filename) const
{
std::ofstream out(filename);
out << mesh_;
out.close();
}
int valence(const vertex_descriptor& v) const
{
return static_cast<int>(degree(v, mesh_));
}
int target_valence(const vertex_descriptor& v) const
{
return (has_border_ && is_border(v, mesh_)) ? 4 : 6;
}
bool is_on_triangle(const halfedge_descriptor& h) const
{
return h == next(next(next(h, mesh_), mesh_), mesh_);
}
bool is_longest_on_faces(const edge_descriptor& e) const
{
halfedge_descriptor h = halfedge(e, mesh_);
halfedge_descriptor hopp = opposite(h, mesh_);
//check whether h is the longest edge in its associated face
//overwise refinement will go for an endless loop
double sqh = sqlength(h);
return sqh >= sqlength(next(h, mesh_))
&& sqh >= sqlength(next(next(h, mesh_), mesh_))
//do the same for hopp
&& sqh >= sqlength(next(hopp, mesh_))
&& sqh >= sqlength(next(next(hopp, mesh_), mesh_));
}
bool is_constrained(const edge_descriptor& e) const
{
return is_on_border(e) || is_on_patch_border(e);
}
bool is_split_allowed(const edge_descriptor& e) const
{
halfedge_descriptor h = halfedge(e, mesh_);
halfedge_descriptor hopp = opposite(h, mesh_);
if (protect_constraints_ && is_constrained(e))
return false;
else //allow splitting constraints
{
if (is_on_mesh(h) && is_on_mesh(hopp))
return false;
else if (is_on_mesh(h) && is_on_border(hopp))
return false;
else if (is_on_mesh(hopp) && is_on_border(h))
return false;
else
return true;
}
}
bool is_collapse_allowed(const edge_descriptor& e
, const bool collapse_constraints) const
{
halfedge_descriptor he = halfedge(e, mesh_);
halfedge_descriptor hopp = opposite(he, mesh_);
if (is_on_mesh(he) && is_on_mesh(hopp))
return false;
if ( (protect_constraints_ || !collapse_constraints) && is_constrained(e))
return false;
if (is_on_patch(he)) //hopp is also on patch
{
CGAL_assertion(is_on_patch(hopp));
if (is_on_patch_border(target(he, mesh_)) && is_on_patch_border(source(he, mesh_)))
return false;//collapse would induce pinching the selection
else
return (is_collapse_allowed_on_patch(he)
&& is_collapse_allowed_on_patch(hopp));
}
else if (is_on_patch_border(he))
return is_collapse_allowed_on_patch_border(he);
else if (is_on_patch_border(hopp))
return is_collapse_allowed_on_patch_border(hopp);
return false;
}
bool is_collapse_allowed_on_patch(const halfedge_descriptor& he) const
{
halfedge_descriptor hopp = opposite(he, mesh_);
if (is_on_patch_border(next(he, mesh_)) && is_on_patch_border(prev(he, mesh_)))
return false;//too many cases to be handled
if (is_on_patch_border(next(hopp, mesh_)) && is_on_patch_border(prev(hopp, mesh_)))
return false;//too many cases to be handled
else if (is_on_patch_border(next(he, mesh_)))
{
//avoid generation of degenerate faces, and self-intersections
if (source(he, mesh_) ==
target(next(next_on_patch_border(next(he, mesh_)), mesh_), mesh_))
return false;
}
else if (is_on_patch_border(prev(hopp, mesh_)))
{
//avoid generation of degenerate faces, and self-intersections
if (target(hopp, mesh_) ==
source(prev(prev_on_patch_border(prev(hopp, mesh_)), mesh_), mesh_))
return false;
}
return true;
}
bool is_collapse_allowed_on_patch_border(const halfedge_descriptor& h) const
{
CGAL_precondition(is_on_patch_border(h));
halfedge_descriptor hopp = opposite(h, mesh_);
if (is_on_patch_border(next(h, mesh_)) && is_on_patch_border(prev(h, mesh_)))
return false;
if (is_on_patch_border(hopp))
{
if (is_on_patch_border(next(hopp, mesh_)) && is_on_patch_border(prev(hopp, mesh_)))
return false;
else if (next_on_patch_border(h) == hopp && prev_on_patch_border(h) == hopp)
return false; //isolated patch border
else
return true;
}
CGAL_assertion(is_on_mesh(hopp) || is_on_border(hopp));
return true;//we already checked we're not pinching a hole in the patch
}
bool is_flip_topologically_allowed(const edge_descriptor& e) const
{
halfedge_descriptor h=halfedge(e, mesh_);
return !halfedge(target(next(h, mesh_), mesh_),
target(next(opposite(h, mesh_), mesh_), mesh_),
mesh_).second;
}
bool is_flip_allowed(const edge_descriptor& e) const
{
bool flip_possible = is_flip_allowed(halfedge(e, mesh_))
&& is_flip_allowed(opposite(halfedge(e, mesh_), mesh_));
if (!flip_possible) return false;
// the flip is not possible if the edge already exists
return is_flip_topologically_allowed(e);
}
bool is_flip_allowed(const halfedge_descriptor& h) const
{
if (!is_on_patch(h))
return false;
if (!is_on_patch_border(target(h, mesh_)))
return true;
if ( is_on_patch_border(next(h, mesh_))
&& is_on_patch_border(prev(opposite(h, mesh_), mesh_)))
return false;
return true;
}
halfedge_descriptor next_on_patch_border(const halfedge_descriptor& h) const
{
CGAL_precondition(is_on_patch_border(h));
CGAL_assertion_code(const Patch_id& pid = get_patch_id(face(h, mesh_)));
halfedge_descriptor end = opposite(h, mesh_);
halfedge_descriptor nxt = next(h, mesh_);
do
{
if (is_on_patch_border(nxt))
{
CGAL_assertion(get_patch_id(face(nxt, mesh_)) == pid);
return nxt;
}
nxt = next(opposite(nxt, mesh_), mesh_);
}
while (end != nxt);
CGAL_assertion(get_patch_id(face(nxt, mesh_)) == pid);
CGAL_assertion(is_on_patch_border(end));
return end;
}
halfedge_descriptor prev_on_patch_border(const halfedge_descriptor& h) const
{
CGAL_precondition(is_on_patch_border(h));
CGAL_assertion_code(const Patch_id& pid = get_patch_id(face(h, mesh_)));
halfedge_descriptor end = opposite(h, mesh_);
halfedge_descriptor prv = prev(h, mesh_);
do
{
if (is_on_patch_border(prv))
{
CGAL_assertion(get_patch_id(face(prv, mesh_)) == pid);
return prv;
}
prv = prev(opposite(prv, mesh_), mesh_);
}
while (end != prv);
CGAL_assertion(is_on_patch_border(end));
CGAL_assertion(get_patch_id(face(prv, mesh_)) == pid);
return end;
}
bool collapse_would_invert_face(const halfedge_descriptor& h) const
{
typename boost::property_traits<VertexPointMap>::reference
s = get(vpmap_, source(h, mesh_)); //s for source
typename boost::property_traits<VertexPointMap>::reference
t = get(vpmap_, target(h, mesh_)); //t for target
//check if collapsing the edge [src; tgt] towards tgt
//would inverse the normal to the considered face
//src and tgt are the endpoints of the edge to be collapsed
//p and q are the vertices that form the face to be tested
//along with src before collapse, and with tgt after collapse
for(halfedge_descriptor hd :
halfedges_around_target(opposite(h, mesh_), mesh_))
{
if (face(hd, mesh_) == boost::graph_traits<PM>::null_face())
continue;
typename boost::property_traits<VertexPointMap>::reference
p = get(vpmap_, target(next(hd, mesh_), mesh_));
typename boost::property_traits<VertexPointMap>::reference
q = get(vpmap_, target(next(next(hd, mesh_), mesh_), mesh_));
#ifdef CGAL_PMP_REMESHING_DEBUG
CGAL_assertion((Triangle_3(t, p, q).is_degenerate())
== GeomTraits().collinear_3_object()(t, p, q));
#endif
if ( GeomTraits().collinear_3_object()(s, p, q)
|| GeomTraits().collinear_3_object()(t, p, q))
continue;
#ifdef CGAL_PMP_REMESHING_DEBUG
typename GeomTraits::Construct_normal_3 normal
= GeomTraits().construct_normal_3_object();
Vector_3 normal_before_collapse = normal(s, p, q);
Vector_3 normal_after_collapse = normal(t, p, q);
CGAL::Sign s1 = CGAL::sign(normal_before_collapse * normal_after_collapse);
CGAL::Sign s2 = CGAL::sign(CGAL::cross_product(Vector_3(s, p), Vector_3(s, q))
* CGAL::cross_product(Vector_3(t, p), Vector_3(t, q)));
CGAL_assertion(s1 == s2);
#endif
if(CGAL::sign(CGAL::cross_product(Vector_3(s, p), Vector_3(s, q))
* CGAL::cross_product(Vector_3(t, p), Vector_3(t, q)))
!= CGAL::POSITIVE)
return true;
}
return false;
}
bool is_constrained(const vertex_descriptor& v) const
{
return get(vcmap_, v);
}
bool is_isolated(const vertex_descriptor& v) const
{
return halfedges_around_target(v, mesh_).empty();
}
bool is_corner(const vertex_descriptor& v) const
{
if(! has_border_){
return false;
}
unsigned int nb_incident_features = 0;
for(halfedge_descriptor h : halfedges_around_target(v, mesh_))
{
halfedge_descriptor hopp = opposite(h, mesh_);
if ( is_on_border(h) || is_on_patch_border(h)
|| is_on_border(hopp) || is_on_patch_border(hopp))
++nb_incident_features;
if (nb_incident_features > 2)
return true;
}
return (nb_incident_features == 1);
}
Vector_3 compute_normal(const face_descriptor& f) const
{
if (f == boost::graph_traits<PM>::null_face())
return CGAL::NULL_VECTOR;
return PMP::compute_face_normal(f, mesh_, parameters::vertex_point_map(vpmap_)
.geom_traits(gt_));
}
template<typename FaceRange>
void tag_halfedges_status(const FaceRange& face_range)
{
//init halfedges as:
// - MESH, //h and hopp belong to the mesh, not the patch
// - MESH_BORDER //h belongs to the mesh, face(hopp, pmesh) == null_face()
for(halfedge_descriptor h : halfedges(mesh_))
{
//being part of the border of the mesh is predominant
if (is_border(h, mesh_)){
set_status(h, MESH_BORDER); //erase previous value if exists
has_border_ = true;
} else {
set_status(h, MESH);
}
}
//tag PATCH, //h and hopp belong to the patch to be remeshed
for(face_descriptor f : face_range)
{
for(halfedge_descriptor h :
halfedges_around_face(halfedge(f, mesh_), mesh_))
{
set_status(h, PATCH);
}
}
// tag patch border halfedges
for(halfedge_descriptor h : halfedges(mesh_))
{
if (status(h) == PATCH
&& ( status(opposite(h, mesh_)) != PATCH
|| get_patch_id(face(h, mesh_)) != get_patch_id(face(opposite(h, mesh_), mesh_))))
{
set_status(h, PATCH_BORDER);
has_border_ = true;
}
}
// update status using constrained edge map
if (!boost::is_same<EdgeIsConstrainedMap,
Static_boolean_property_map<edge_descriptor, false> >::value)
{
for(edge_descriptor e : edges(mesh_))
{
if (get(ecmap_, e))
{
//deal with h and hopp for borders that are sharp edges to be preserved
halfedge_descriptor h = halfedge(e, mesh_);
if (status(h) == PATCH){
set_status(h, PATCH_BORDER);
has_border_ = true;
}
halfedge_descriptor hopp = opposite(h, mesh_);
if (status(hopp) == PATCH){
set_status(hopp, PATCH_BORDER);
has_border_ = true;
}
}
}
}
}
Halfedge_status status(const halfedge_descriptor& h) const
{
return get(halfedge_status_pmap_,h);
}
void set_status(const halfedge_descriptor& h,
const Halfedge_status& s)
{
put(halfedge_status_pmap_,h,s);
}
void merge_and_update_status(halfedge_descriptor en,
halfedge_descriptor ep)
{
halfedge_descriptor eno = opposite(en, mesh_);
halfedge_descriptor epo = opposite(ep, mesh_);
Halfedge_status s_eno = status(eno);
Halfedge_status s_epo = status(epo);
Halfedge_status s_ep = status(ep);
if(s_epo == MESH_BORDER
|| s_ep == MESH_BORDER
|| s_epo == PATCH_BORDER
|| s_ep == PATCH_BORDER)
{
set_status(en, s_epo);
set_status(eno, s_ep);
}
else
{
Halfedge_status s_en = status(en);
if(s_eno == MESH_BORDER
|| s_en == MESH_BORDER
|| s_eno == PATCH_BORDER
|| s_en == PATCH_BORDER)
{
set_status(ep, s_epo);
set_status(epo, s_ep);
}
}
// else keep current status for en and eno
}
template<typename Bimap>
bool fix_degenerate_faces(const vertex_descriptor& v,
Bimap& short_edges,
const double& sq_low,
const bool collapse_constraints)
{
CGAL_assertion_code(std::size_t nb_done = 0);
boost::unordered_set<halfedge_descriptor> degenerate_faces;
for(halfedge_descriptor h :
halfedges_around_target(halfedge(v, mesh_), mesh_))
{
if(!is_border(h, mesh_) &&
is_degenerate_triangle_face(face(h, mesh_), mesh_,
parameters::vertex_point_map(vpmap_)
.geom_traits(gt_)))
degenerate_faces.insert(h);
}
if(degenerate_faces.empty())
return true;
bool done = false;
while(!degenerate_faces.empty())
{
halfedge_descriptor h = *(degenerate_faces.begin());
degenerate_faces.erase(degenerate_faces.begin());
if (!is_degenerate_triangle_face(face(h, mesh_), mesh_,
parameters::vertex_point_map(vpmap_)
.geom_traits(gt_)))
//this can happen when flipping h has consequences further in the mesh
continue;
//check that opposite is not also degenerate
degenerate_faces.erase(opposite(h, mesh_));
if(is_border(h, mesh_))
continue;
for(halfedge_descriptor hf :
halfedges_around_face(h, mesh_))
{
if(face(opposite(hf, mesh_), mesh_) == boost::graph_traits<PM>::null_face())
continue;
vertex_descriptor vc = target(hf, mesh_);
vertex_descriptor va = target(next(hf, mesh_), mesh_);
vertex_descriptor vb = target(next(next(hf, mesh_), mesh_), mesh_);
Vector_3 ab(get(vpmap_,va), get(vpmap_,vb));
Vector_3 ac(get(vpmap_,va), get(vpmap_,vc));
if (ab * ac < 0)
{
halfedge_descriptor hfo = opposite(hf, mesh_);
halfedge_descriptor h_ab = prev(hf, mesh_);
halfedge_descriptor h_ca = next(hf, mesh_);
short_edges.left.erase(hf);
short_edges.left.erase(hfo);
CGAL_assertion( !get(ecmap_, edge(hf, mesh_)) );
if (!is_flip_topologically_allowed(edge(hf, mesh_)))
continue;
CGAL::Euler::flip_edge(hf, mesh_);
CGAL_assertion_code(++nb_done);
done = true;
//update status
set_status(h_ab, merge_status(h_ab, hf, hfo));
set_status(h_ca, merge_status(h_ca, hf, hfo));
if (is_on_patch(h_ca) || is_on_patch_border(h_ca))
{
set_status(hf, PATCH);
set_status(hfo, PATCH);
}
#ifdef CGAL_PMP_REMESHING_DEBUG
debug_status_map();
#endif
//insert new edges in 'short_edges'
if (is_collapse_allowed(edge(hf, mesh_), collapse_constraints))
{
double sqlen = sqlength(hf);
if (sqlen < sq_low)
short_edges.insert(typename Bimap::value_type(hf, sqlen));
}
if(!is_border(hf, mesh_) &&
is_degenerate_triangle_face(face(hf, mesh_), mesh_,
parameters::vertex_point_map(vpmap_)
.geom_traits(gt_)))
degenerate_faces.insert(hf);
if(!is_border(hfo, mesh_) &&
is_degenerate_triangle_face(face(hfo, mesh_), mesh_,
parameters::vertex_point_map(vpmap_)
.geom_traits(gt_)))
degenerate_faces.insert(hfo);
break;
}
}
}
#ifdef CGAL_PMP_REMESHING_DEBUG
debug_status_map();
#endif
return done;
}
bool incident_to_degenerate(const halfedge_descriptor& he)
{
for(halfedge_descriptor h :
halfedges_around_target(he, mesh_))
{
if(!is_border(h, mesh_) &&
is_degenerate_triangle_face(face(h, mesh_), mesh_,
parameters::vertex_point_map(vpmap_)
.geom_traits(gt_)))
return true;
}
return false;
}
Halfedge_status merge_status(const halfedge_descriptor& h1,
const halfedge_descriptor& h2,
const halfedge_descriptor& h3)
{
Halfedge_status s1 = status(h1);
if (s1 == MESH_BORDER) return s1;
Halfedge_status s2 = status(h2);
if (s2 == MESH_BORDER) return s2;
Halfedge_status s3 = status(h3);
if (s3 == MESH_BORDER) return s3;
else if (s1 == PATCH_BORDER) return s1;
else if (s2 == PATCH_BORDER) return s2;
else if (s3 == PATCH_BORDER) return s3;
CGAL_assertion(s1 == s2 && s1 == s3);
return s1;
}
bool is_on_patch(const halfedge_descriptor& h) const
{
bool res =(status(h) == PATCH);
CGAL_assertion(res == (status(opposite(h, mesh_)) == PATCH));
return res;
}
bool is_on_patch(const face_descriptor& f) const
{
for(halfedge_descriptor h :
halfedges_around_face(halfedge(f, mesh_), mesh_))
{
if (is_on_patch(h) || is_on_patch_border(h))
return true;
}
return false;
}
bool is_on_patch(const vertex_descriptor& v) const
{
if(! has_border_){
return true;
}
for(halfedge_descriptor h :
halfedges_around_target(v, mesh_))
{
if (!is_on_patch(h))
return false;
}
return true;
}
public:
bool is_on_patch_border(const halfedge_descriptor& h) const
{
bool res = (status(h) == PATCH_BORDER);
if (res)
{
CGAL_assertion_code(Halfedge_status hs = status(opposite(h, mesh_)));
CGAL_assertion(hs == MESH_BORDER
|| hs == MESH
|| hs == PATCH_BORDER);//when 2 incident patches are remeshed
}
return res;
}
bool is_on_patch_border(const edge_descriptor& e) const
{
return is_on_patch_border(halfedge(e,mesh_))
|| is_on_patch_border(opposite(halfedge(e, mesh_), mesh_));
}
bool is_on_patch_border(const vertex_descriptor& v) const
{
if(! has_border_){
return false;
}
for(halfedge_descriptor h : halfedges_around_target(v, mesh_))
{
if (is_on_patch_border(h) || is_on_patch_border(opposite(h, mesh_)))
return true;
}
return false;
}
bool is_on_border(const halfedge_descriptor& h) const
{
bool res = (status(h) == MESH_BORDER);
CGAL_assertion(res == is_border(h, mesh_));
CGAL_assertion(res == is_border(next(h, mesh_), mesh_));
return res;
}
bool is_on_border(const edge_descriptor& e) const
{
return is_on_border(halfedge(e, mesh_))
|| is_on_border(opposite(halfedge(e, mesh_), mesh_));
}
bool is_on_mesh(const halfedge_descriptor& h) const
{
return status(h) == MESH;
}
private:
void halfedge_added(const halfedge_descriptor& h,
const Halfedge_status& s)
{
set_status(h, s);
}
std::size_t nb_valid_halfedges() const
{
return static_cast<std::size_t>(
std::distance(halfedges(mesh_).first, halfedges(mesh_).second));
}
void debug_status_map() const
{
unsigned int nb_border = 0;
unsigned int nb_mesh = 0;
unsigned int nb_patch = 0;
unsigned int nb_patch_border = 0;
for(halfedge_descriptor h : halfedges(mesh_))
{
if(is_on_patch(h)) nb_patch++;
else if(is_on_patch_border(h)) nb_patch_border++;
else if(is_on_mesh(h)) nb_mesh++;
else if(is_on_border(h)) nb_border++;
else CGAL_assertion(false);
}
}
#ifdef CGAL_PMP_REMESHING_DEBUG
void debug_self_intersections() const
{
std::cout << "Test self intersections...";
std::vector<std::pair<face_descriptor, face_descriptor> > facets;
PMP::self_intersections(mesh_,
std::back_inserter(facets),
PMP::parameters::vertex_point_map(vpmap_)
.geom_traits(gt_));
//CGAL_assertion(facets.empty());
std::cout << "done ("<< facets.size() <<" facets)." << std::endl;
}
void debug_self_intersections(const vertex_descriptor& v) const
{
std::cout << "Test self intersections...";
std::vector<std::pair<face_descriptor, face_descriptor> > facets;
PMP::self_intersections(faces_around_target(halfedge(v, mesh_), mesh_),
mesh_,
std::back_inserter(facets),
PMP::parameters::vertex_point_map(vpmap_)
.geom_traits(gt_));
//CGAL_assertion(facets.empty());
std::cout << "done ("<< facets.size() <<" facets)." << std::endl;
}
#endif
//check whether the normals to faces incident to v
//have all their 2 by 2 dot products > 0
bool check_normals(const vertex_descriptor& v) const
{
return check_normals(halfedges_around_target(halfedge(v, mesh_), mesh_));
}
template <typename HalfedgeRange>
bool check_normals(const HalfedgeRange& hedges) const
{
typedef std::multimap<Patch_id, Vector_3> Normals_multimap;
typedef typename Normals_multimap::iterator Normals_iterator;
Normals_multimap normals_per_patch;
for(halfedge_descriptor hd : hedges)
{
Vector_3 n = compute_normal(face(hd, mesh_));
if (n == CGAL::NULL_VECTOR) //for degenerate faces
continue;
Patch_id pid = get_patch_id(face(hd, mesh_));
normals_per_patch.insert(std::make_pair(pid, n));
}
//on each surface patch,
//check all normals have same orientation
for (Normals_iterator it = normals_per_patch.begin();
it != normals_per_patch.end();/*done inside loop*/)
{
std::vector<Vector_3> normals;
std::pair<Normals_iterator, Normals_iterator> n_range
= normals_per_patch.equal_range((*it).first);
for (Normals_iterator iit = n_range.first; iit != n_range.second; ++iit)
normals.push_back((*iit).second);
if (!check_orientation(normals))
return false;
it = n_range.second;
}
return true;
}
bool check_normals(const halfedge_descriptor& h) const
{
if (!is_on_patch(h))
return true;//nothing to say
Vector_3 n = compute_normal(face(h, mesh_));
Vector_3 no = compute_normal(face(opposite(h, mesh_), mesh_));
return n * no > 0.;
}
bool check_orientation(const std::vector<Vector_3>& normals) const
{
if (normals.size() < 2)
return true;
for (std::size_t i = 1; i < normals.size(); ++i)/*start at 1 on purpose*/
{
double dot = to_double(normals[i - 1] * normals[i]);
if (dot <= 0.)
return false;
}
return true;
}
public:
const Triangle_list& input_triangles() const {
return input_triangles_;
}
const Patch_id_list& input_patch_ids() const {
return input_patch_ids_;
}
private:
PolygonMesh& mesh_;
VertexPointMap& vpmap_;
const GeomTraits& gt_;
bool build_tree_;
bool has_border_;
std::vector<AABB_tree*> trees;
Patch_id_to_index_map patch_id_to_index_map;
Triangle_list input_triangles_;
Patch_id_list input_patch_ids_;
Halfedge_status_pmap halfedge_status_pmap_;
bool protect_constraints_;
FacePatchMap patch_ids_map_;
EdgeIsConstrainedMap ecmap_;
VertexIsConstrainedMap vcmap_;
FaceIndexMap fimap_;
CGAL_assertion_code(bool input_mesh_is_valid_;)
};//end class Incremental_remesher
}//end namespace internal
}//end namespace Polygon_mesh_processing
}//end namespace CGAL
#endif //CGAL_POLYGON_MESH_PROCESSING_REMESH_IMPL_H
|
jjcasmar/cgal | Polyhedron/include/CGAL/draw_polyhedron.h | // Copyright (c) 2018-2020 ETH Zurich (Switzerland).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org).
//
// $URL$
// $Id$
// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-Commercial
//
// Author(s) : <NAME> <<EMAIL>>
#ifndef CGAL_DRAW_POLYHEDRON_H
#define CGAL_DRAW_POLYHEDRON_H
#include <CGAL/license/Polyhedron.h>
#include <CGAL/Qt/Basic_viewer_qt.h>
#ifdef CGAL_USE_BASIC_VIEWER
#include <CGAL/Polyhedron_3.h>
#include <CGAL/draw_face_graph.h>
#include <CGAL/Random.h>
namespace CGAL
{
// Specialization of draw function.
#define CGAL_POLY_TYPE CGAL::Polyhedron_3 \
<PolyhedronTraits_3, PolyhedronItems_3, T_HDS, Alloc>
template<class PolyhedronTraits_3,
class PolyhedronItems_3,
template < class T, class I, class A>
class T_HDS,
class Alloc>
void draw(const CGAL_POLY_TYPE& apoly,
const char* title="Polyhedron Basic Viewer",
bool nofill=false)
{
#if defined(CGAL_TEST_SUITE)
bool cgal_test_suite=true;
#else
bool cgal_test_suite=qEnvironmentVariableIsSet("CGAL_TEST_SUITE");
#endif
if (!cgal_test_suite)
{
int argc=1;
const char* argv[2]={"polyhedron_viewer","\0"};
QApplication app(argc,const_cast<char**>(argv));
SimpleFaceGraphViewerQt
mainwindow(app.activeWindow(), apoly, title, nofill);
mainwindow.show();
app.exec();
}
}
#undef CGAL_POLY_TYPE
} // End namespace CGAL
#endif // CGAL_USE_BASIC_VIEWER
#endif // CGAL_DRAW_POLYHEDRON_H
|
jjcasmar/cgal | BGL/include/CGAL/boost/graph/generators.h | <gh_stars>1-10
// Copyright (c) 2014, 2017 GeometryFactory (France). All rights reserved.
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org)
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial
//
// Author(s) : <NAME>,
// <NAME>
#ifndef CGAL_BOOST_GRAPH_GENERATORS_H
#define CGAL_BOOST_GRAPH_GENERATORS_H
#include <CGAL/boost/graph/iterator.h>
#include <CGAL/boost/graph/properties.h>
#include <CGAL/Random.h>
#include <CGAL/function_objects.h>
namespace CGAL {
namespace Euler {
// Some forward declaration to break the helpers.h > generators.h > Euler_operations.h cycle
template< typename Graph>
void fill_hole(typename boost::graph_traits<Graph>::halfedge_descriptor h,
Graph& g);
template<typename Graph , typename VertexRange >
typename boost::graph_traits<Graph>::face_descriptor add_face(const VertexRange& vr,
Graph& g);
} // namespace Euler
namespace internal {
template <class FaceGraph>
void swap_vertices(typename boost::graph_traits<FaceGraph>::vertex_descriptor& p,
typename boost::graph_traits<FaceGraph>::vertex_descriptor& q,
FaceGraph& g);
template<typename InputIterator>
typename std::iterator_traits<InputIterator>::value_type
random_entity_in_range(InputIterator first, InputIterator beyond,
CGAL::Random& rnd = get_default_random())
{
typedef typename std::iterator_traits<InputIterator>::difference_type size_type;
size_type zero = 0, ne = std::distance(first, beyond);
std::advance(first, rnd.uniform_int(zero, ne - 1));
return *first;
}
template<typename InputIterator>
typename std::iterator_traits<InputIterator>::value_type
random_entity_in_range(const CGAL::Iterator_range<InputIterator>& range,
CGAL::Random& rnd = get_default_random())
{
return random_entity_in_range(range.begin(), range.end(), rnd);
}
// \brief returns a random non-null vertex incident to the face `fd` of the polygon mesh `g`.
// \tparam Graph a model of `HalfedgeGraph`
template<typename Graph>
typename boost::graph_traits<Graph>::vertex_descriptor
random_vertex_in_face(typename boost::graph_traits<Graph>::face_descriptor fd,
const Graph& g,
CGAL::Random& rnd = get_default_random())
{
return internal::random_entity_in_range(vertices_around_face(halfedge(fd, g), g), rnd);
}
// \brief returns a random non-null halfedge incident to the face `fd` of the polygon mesh `g`.
// \tparam Graph a model of `HalfedgeGraph`
template<typename Graph>
typename boost::graph_traits<Graph>::halfedge_descriptor
random_halfedge_in_face(typename boost::graph_traits<Graph>::face_descriptor fd,
const Graph& g,
CGAL::Random& rnd = get_default_random())
{
return internal::random_entity_in_range(halfedges_around_face(halfedge(fd, g), g), rnd);
}
// \brief returns a random non-null vertex of the polygon mesh `g`.
// \tparam Graph a model of `VertexListGraph`
template<typename Graph>
typename boost::graph_traits<Graph>::vertex_descriptor
random_vertex_in_mesh(const Graph& g, CGAL::Random& rnd = get_default_random())
{
return internal::random_entity_in_range(vertices(g), rnd);
}
// \brief returns a random non-null halfedge of the polygon mesh `g`.
// \tparam Graph a model of `HalfedgeListGraph`
template<typename Graph>
typename boost::graph_traits<Graph>::halfedge_descriptor
random_halfedge_in_mesh(const Graph& g, CGAL::Random& rnd = get_default_random())
{
return internal::random_entity_in_range(halfedges(g), rnd);
}
// \brief returns a random non-null edge of the polygon mesh `g`.
// \tparam Graph a model of `EdgeListGraph`
template<typename Graph>
typename boost::graph_traits<Graph>::edge_descriptor
random_edge_in_mesh(const Graph& g, CGAL::Random& rnd = get_default_random())
{
return internal::random_entity_in_range(edges(g), rnd);
}
// \brief returns a random non-null face of the polygon mesh `g`.
// \tparam Graph a model of `FaceListGraph`
template<typename Graph>
typename boost::graph_traits<Graph>::face_descriptor
random_face_in_mesh(const Graph& g, CGAL::Random& rnd = get_default_random())
{
return internal::random_entity_in_range(faces(g), rnd);
}
} // namespace internal
/**
* \ingroup PkgBGLHelperFct
*
* \brief Creates an isolated triangle
* with its vertices initialized to `p0`, `p1` and `p2`, and adds it to the graph `g`.
*
* \returns the non-border halfedge that has the target vertex associated with `p0`.
**/
template<typename Graph, typename P>
typename boost::graph_traits<Graph>::halfedge_descriptor
make_triangle(const P& p0, const P& p1, const P& p2, Graph& g)
{
typedef typename boost::graph_traits<Graph> Traits;
typedef typename Traits::vertex_descriptor vertex_descriptor;
typedef typename Traits::halfedge_descriptor halfedge_descriptor;
typedef typename Traits::face_descriptor face_descriptor;
typedef typename boost::property_map<Graph,vertex_point_t>::type Point_property_map;
Point_property_map ppmap = get(CGAL::vertex_point, g);
vertex_descriptor v0, v1, v2;
v0 = add_vertex(g);
v1 = add_vertex(g);
v2 = add_vertex(g);
ppmap[v0] = p0;
ppmap[v1] = p1;
ppmap[v2] = p2;
halfedge_descriptor h0 = halfedge(add_edge(g), g);
halfedge_descriptor h1 = halfedge(add_edge(g), g);
halfedge_descriptor h2 = halfedge(add_edge(g), g);
set_next(h0, h1, g);
set_next(h1, h2, g);
set_next(h2, h0, g);
set_target(h0, v1, g);
set_target(h1, v2, g);
set_target(h2, v0, g);
set_halfedge(v1, h0, g);
set_halfedge(v2, h1, g);
set_halfedge(v0, h2, g);
face_descriptor f = add_face(g);
set_face(h0, f, g);
set_face(h1, f, g);
set_face(h2, f, g);
set_halfedge(f, h0, g);
h0 = opposite(h0, g);
h1 = opposite(h1, g);
h2 = opposite(h2, g);
set_next(h0, h2, g);
set_next(h2, h1, g);
set_next(h1, h0, g);
set_target(h0, v0, g);
set_target(h1, v1, g);
set_target(h2, v2, g);
set_face(h0, boost::graph_traits<Graph>::null_face(), g);
set_face(h1, boost::graph_traits<Graph>::null_face(), g);
set_face(h2, boost::graph_traits<Graph>::null_face(), g);
return opposite(h2, g);
}
namespace internal {
template<typename Graph>
typename boost::graph_traits<Graph>::halfedge_descriptor
make_quad(typename boost::graph_traits<Graph>::vertex_descriptor v0,
typename boost::graph_traits<Graph>::vertex_descriptor v1,
typename boost::graph_traits<Graph>::vertex_descriptor v2,
typename boost::graph_traits<Graph>::vertex_descriptor v3,
Graph& g)
{
typedef typename boost::graph_traits<Graph>::halfedge_descriptor halfedge_descriptor;
typedef typename boost::graph_traits<Graph>::face_descriptor face_descriptor;
halfedge_descriptor h0 = halfedge(add_edge(g), g);
halfedge_descriptor h1 = halfedge(add_edge(g), g);
halfedge_descriptor h2 = halfedge(add_edge(g), g);
halfedge_descriptor h3 = halfedge(add_edge(g), g);
set_next(h0, h1, g);
set_next(h1, h2, g);
set_next(h2, h3, g);
set_next(h3, h0, g);
set_target(h0, v1, g);
set_target(h1, v2, g);
set_target(h2, v3, g);
set_target(h3, v0, g);
set_halfedge(v1, h0, g);
set_halfedge(v2, h1, g);
set_halfedge(v3, h2, g);
set_halfedge(v0, h3, g);
face_descriptor f = add_face(g);
set_face(h0, f, g);
set_face(h1, f, g);
set_face(h2, f, g);
set_face(h3, f, g);
set_halfedge(f, h0, g);
h0 = opposite(h0, g);
h1 = opposite(h1, g);
h2 = opposite(h2, g);
h3 = opposite(h3, g);
set_next(h0, h3, g);
set_next(h3, h2, g);
set_next(h2, h1, g);
set_next(h1, h0, g);
set_target(h0, v0, g);
set_target(h1, v1, g);
set_target(h2, v2, g);
set_target(h3, v3, g);
set_face(h0, boost::graph_traits<Graph>::null_face(), g);
set_face(h1, boost::graph_traits<Graph>::null_face(), g);
set_face(h2, boost::graph_traits<Graph>::null_face(), g);
set_face(h3, boost::graph_traits<Graph>::null_face(), g);
return opposite(h3, g);
}
// default Functor for make_grid
template<typename Size_type, typename Point>
struct Default_grid_maker
: public CGAL::Creator_uniform_3<Size_type, Point>
{
Point operator()(const Size_type& i, const Size_type& j) const {
return CGAL::Creator_uniform_3<Size_type, Point>::operator ()(i,j,0);
}
};
} // namespace internal
/**
* \ingroup PkgBGLHelperFct
*
* \brief Creates an isolated quad with
* its vertices initialized to `p0`, `p1`, `p2`, and `p3`, and adds it to the graph `g`.
*
* \returns the non-border halfedge that has the target vertex associated with `p0`.
**/
template<typename Graph, typename P>
typename boost::graph_traits<Graph>::halfedge_descriptor
make_quad(const P& p0, const P& p1, const P& p2, const P& p3, Graph& g)
{
typedef typename boost::graph_traits<Graph> Traits;
typedef typename Traits::vertex_descriptor vertex_descriptor;
typedef typename boost::property_map<Graph,vertex_point_t>::type Point_property_map;
Point_property_map ppmap = get(CGAL::vertex_point, g);
vertex_descriptor v0, v1, v2, v3;
v0 = add_vertex(g);
v1 = add_vertex(g);
v2 = add_vertex(g);
v3 = add_vertex(g);
ppmap[v0] = p0;
ppmap[v1] = p1;
ppmap[v2] = p2;
ppmap[v3] = p3;
return internal::make_quad(v0, v1, v2, v3, g);
}
/**
* \ingroup PkgBGLHelperFct
* \brief Creates an isolated hexahedron
* with its vertices initialized to `p0`, `p1`, ...\ , and `p7`, and adds it to the graph `g`.
* \image html hexahedron.png
* \image latex hexahedron.png
* \returns the halfedge that has the target vertex associated with `p0`, in the face with the vertices with the points `p0`, `p1`, `p2`, and `p3`.
**/
template<typename Graph, typename P>
typename boost::graph_traits<Graph>::halfedge_descriptor
make_hexahedron(const P& p0, const P& p1, const P& p2, const P& p3,
const P& p4, const P& p5, const P& p6, const P& p7, Graph& g)
{
typedef typename boost::graph_traits<Graph> Traits;
typedef typename Traits::halfedge_descriptor halfedge_descriptor;
typedef typename Traits::vertex_descriptor vertex_descriptor;
typedef typename boost::property_map<Graph,vertex_point_t>::type Point_property_map;
Point_property_map ppmap = get(CGAL::vertex_point, g);
vertex_descriptor v0, v1, v2, v3, v4, v5, v6, v7;
v0 = add_vertex(g);
v1 = add_vertex(g);
v2 = add_vertex(g);
v3 = add_vertex(g);
v4 = add_vertex(g);
v5 = add_vertex(g);
v6 = add_vertex(g);
v7 = add_vertex(g);
ppmap[v0] = p0;
ppmap[v1] = p1;
ppmap[v2] = p2;
ppmap[v3] = p3;
ppmap[v4] = p4;
ppmap[v5] = p5;
ppmap[v6] = p6;
ppmap[v7] = p7;
halfedge_descriptor ht = internal::make_quad(v4, v5, v6, v7, g);
halfedge_descriptor hb = prev(internal::make_quad(v0, v3, v2, v1, g), g);
for(int i=0; i <4; ++i)
{
halfedge_descriptor h = halfedge(add_edge(g), g);
set_target(h,target(hb, g), g);
set_next(h, opposite(hb, g), g);
set_next(opposite(prev(ht, g), g), h, g);
h = opposite(h, g);
set_target(h, source(prev(ht, g), g), g);
set_next(h, opposite(next(next(ht, g), g), g), g);
set_next(opposite(next(hb, g), g), h, g);
hb = next(hb, g);
ht = prev(ht, g);
}
for(int i=0; i <4; ++i)
{
Euler::fill_hole(opposite(hb, g), g);
hb = next(hb, g);
}
return next(next(hb, g), g);
}
/**
* \ingroup PkgBGLHelperFct
* \brief Creates an isolated tetrahedron
* with its vertices initialized to `p0`, `p1`, `p2`, and `p3`, and adds it to the graph `g`.
* \image html tetrahedron.png
* \image latex tetrahedron.png
* \returns the halfedge that has the target vertex associated with `p0`, in the face with the vertices with the points `p0`, `p1`, and `p2`.
**/
template<typename Graph, typename P>
typename boost::graph_traits<Graph>::halfedge_descriptor
make_tetrahedron(const P& p0, const P& p1, const P& p2, const P& p3, Graph& g)
{
typedef typename boost::graph_traits<Graph> Traits;
typedef typename Traits::halfedge_descriptor halfedge_descriptor;
typedef typename Traits::vertex_descriptor vertex_descriptor;
typedef typename Traits::face_descriptor face_descriptor;
typedef typename boost::property_map<Graph,vertex_point_t>::type Point_property_map;
Point_property_map ppmap = get(CGAL::vertex_point, g);
vertex_descriptor v0, v1, v2, v3;
v0 = add_vertex(g);
v2 = add_vertex(g); // this and the next line are switched to keep points in order
v1 = add_vertex(g);
v3 = add_vertex(g);
ppmap[v0] = p0;
ppmap[v1] = p2;// this and the next line are switched to reorient the surface
ppmap[v2] = p1;
ppmap[v3] = p3;
halfedge_descriptor h0 = halfedge(add_edge(g), g);
halfedge_descriptor h1 = halfedge(add_edge(g), g);
halfedge_descriptor h2 = halfedge(add_edge(g), g);
set_next(h0, h1, g);
set_next(h1, h2, g);
set_next(h2, h0, g);
set_target(h0, v1, g);
set_target(h1, v2, g);
set_target(h2, v0, g);
set_halfedge(v1, h0, g);
set_halfedge(v2, h1, g);
set_halfedge(v0, h2, g);
face_descriptor f = add_face(g);
set_face(h0, f, g);
set_face(h1, f, g);
set_face(h2, f, g);
set_halfedge(f, h0, g);
h0 = opposite(h0, g);
h1 = opposite(h1, g);
h2 = opposite(h2, g);
set_next(h0, h2, g);
set_next(h2, h1, g);
set_next(h1, h0, g);
set_target(h0, v0, g);
set_target(h1, v1, g);
set_target(h2, v2, g);
halfedge_descriptor h3 = halfedge(add_edge(g), g);
halfedge_descriptor h4 = halfedge(add_edge(g), g);
halfedge_descriptor h5 = halfedge(add_edge(g), g);
set_target(h3, v3, g);
set_target(h4, v3, g);
set_target(h5, v3, g);
set_halfedge(v3, h3, g);
set_next(h0, h3, g);
set_next(h1, h4, g);
set_next(h2, h5, g);
set_next(h3, opposite(h4, g), g);
set_next(h4, opposite(h5, g), g);
set_next(h5, opposite(h3, g), g);
set_next(opposite(h4, g), h0, g);
set_next(opposite(h5, g), h1, g);
set_next(opposite(h3, g), h2, g);
set_target(opposite(h3, g), v0, g);
set_target(opposite(h4, g), v1, g);
set_target(opposite(h5, g), v2, g);
f = add_face(g);
set_halfedge(f, h0, g);
set_face(h0, f, g);
set_face(h3, f, g);
set_face(opposite(h4, g), f, g);
f = add_face(g);
set_halfedge(f, h1, g);
set_face(h1, f, g);
set_face(h4, f, g);
set_face(opposite(h5, g), f, g);
f = add_face(g);
set_halfedge(f, h2, g);
set_face(h2, f, g);
set_face(h5, f, g);
set_face(opposite(h3, g), f, g);
return opposite(h2, g);
}
/**
* \ingroup PkgBGLHelperFct
*
* \brief Creates a triangulated regular prism, outward oriented,
* having `nb_vertices` vertices in each of its bases and adds it to the graph `g`.
* If `center` is (0, 0, 0), then the first point of the prism is (`radius`, `height`, 0)
*
* \param nb_vertices the number of vertices per base. It must be greater than or equal to 3.
* \param g the graph in which the regular prism will be created.
* \param base_center the center of the circle in which the lower base is inscribed.
* \param height the distance between the two bases.
* \param radius the radius of the circles in which the bases are inscribed.
* \param is_closed determines if the bases must be created or not. If `is_closed` is `true`, `center` is a vertex.
*
* \returns the halfedge that has the target vertex associated with the first point in the first face.
*/
template<class Graph, class P>
typename boost::graph_traits<Graph>::halfedge_descriptor
make_regular_prism(typename boost::graph_traits<Graph>::vertices_size_type nb_vertices,
Graph& g,
const P& base_center = P(0,0,0),
typename CGAL::Kernel_traits<P>::Kernel::FT height = 1.0,
typename CGAL::Kernel_traits<P>::Kernel::FT radius = 1.0,
bool is_closed = true)
{
CGAL_assertion(nb_vertices >= 3);
typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
typedef typename CGAL::Kernel_traits<P>::Kernel::FT FT;
typedef typename boost::property_map<Graph, vertex_point_t>::type Point_property_map;
Point_property_map vpmap = get(CGAL::vertex_point, g);
const FT to_rad = CGAL_PI / 180.0;
const FT precision = 360.0 / nb_vertices;
const FT diameter = 2 * radius;
std::vector<vertex_descriptor> vertices;
vertices.resize(nb_vertices*2);
for(typename boost::graph_traits<Graph>::vertices_size_type i=0; i<nb_vertices*2; ++i)
vertices[i] = add_vertex(g);
//fill vertices
for(typename boost::graph_traits<Graph>::vertices_size_type i=0; i < nb_vertices; ++i)
{
put(vpmap, vertices[i],
P(0.5*diameter * cos(i*precision*to_rad) + base_center.x(),
height+base_center.y(),
-0.5*diameter * sin(i*precision*to_rad) + base_center.z()));
put(vpmap,
vertices[i+nb_vertices],
P(0.5*diameter * cos(i*precision*to_rad) + base_center.x(),
base_center.y(),
-0.5*diameter * sin(i*precision*to_rad) + base_center.z()));
}
//fill faces
std::vector<vertex_descriptor> face;
face.resize(3);
for(typename boost::graph_traits<Graph>::vertices_size_type i=0; i<nb_vertices; ++i)
{
face[0] = vertices[(i+1)%(nb_vertices)];
face[1] = vertices[i];
face[2] = vertices[(i+1)%(nb_vertices) + nb_vertices];
Euler::add_face(face, g);
face[0] = vertices[(i+1)%(nb_vertices) + nb_vertices];
face[1] = vertices[i];
face[2] = vertices[i + nb_vertices];
Euler::add_face(face, g);
}
//close
if(is_closed)
{
//add the base_center of the fans
vertex_descriptor top = add_vertex(g);
vertex_descriptor bot = add_vertex(g);
put(vpmap, top, P(base_center.x(), height+base_center.y(),base_center.z()));
put(vpmap, bot, P(base_center.x(),base_center.y(),base_center.z()));
//add the faces
for(typename boost::graph_traits<Graph>::vertices_size_type i=0; i<nb_vertices; ++i)
{
face[0] = vertices[i];
face[1] = vertices[(i+1)%(nb_vertices)];
face[2] = top;
Euler::add_face(face, g);
face[0] = bot;
face[1] = vertices[(i+1)%(nb_vertices) + nb_vertices];
face[2] = vertices[i + nb_vertices];
Euler::add_face(face, g);
}
}
return halfedge(vertices[0], vertices[1], g).first;
}
/**
* \ingroup PkgBGLHelperFct
* \brief Creates a pyramid, outward oriented, having `nb_vertices` vertices in its base and adds it to the graph `g`.
*
* If `center` is `(0, 0, 0)`, then the first point of the base is `(radius, 0, 0)`
*
* \param nb_vertices the number of vertices in the base. It must be greater than or equal to 3.
* \param g the graph in which the pyramid will be created
* \param base_center the center of the circle in which the base is inscribed.
* \param height the distance between the base and the apex.
* \param radius the radius of the circle in which the base is inscribed.
* \param is_closed determines if the base must be created or not. If `is_closed` is `true`, `center` is a vertex.
*
* \returns the halfedge that has the target vertex associated with the apex point in the first face.
*/
template<class Graph, class P>
typename boost::graph_traits<Graph>::halfedge_descriptor
make_pyramid(typename boost::graph_traits<Graph>::vertices_size_type nb_vertices,
Graph& g,
const P& base_center = P(0,0,0),
typename CGAL::Kernel_traits<P>::Kernel::FT height = 1.0,
typename CGAL::Kernel_traits<P>::Kernel::FT radius = 1.0,
bool is_closed = true)
{
CGAL_assertion(nb_vertices >= 3);
typedef typename boost::property_map<Graph,vertex_point_t>::type Point_property_map;
typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
typedef typename CGAL::Kernel_traits<P>::Kernel::FT FT;
const FT to_rad = CGAL_PI / 180.0;
const FT precision = 360.0/nb_vertices;
const FT diameter = 2*radius;
Point_property_map vpmap = get(CGAL::vertex_point, g);
std::vector<vertex_descriptor> vertices;
vertices.resize(nb_vertices);
for(typename boost::graph_traits<Graph>::vertices_size_type i=0; i<nb_vertices; ++i)
vertices[i] = add_vertex(g);
vertex_descriptor apex = add_vertex(g);
//fill vertices
put(vpmap, apex,
P(base_center.x(),
base_center.y() + height,
base_center.z()));
for(typename boost::graph_traits<Graph>::vertices_size_type i=0; i<nb_vertices; ++i)
{
put(vpmap, vertices[i],
P(0.5*diameter*cos(i*precision*to_rad)+base_center.x(),
base_center.y(),
-0.5*diameter*sin(i*precision*to_rad)+base_center.z()));
}
//fill faces
std::vector<vertex_descriptor> face;
face.resize(3);
for(typename boost::graph_traits<Graph>::vertices_size_type i=0; i<nb_vertices; ++i)
{
face[0] = apex;
face[1] = vertices[i];
face[2] = vertices[(i+1)%(nb_vertices)];
Euler::add_face(face, g);
}
//close
if(is_closed)
{
//add the center of the fan
vertex_descriptor bot = add_vertex(g);
put(vpmap, bot, P(base_center.x(),base_center.y(),base_center.z()));
//add the faces
for(typename boost::graph_traits<Graph>::vertices_size_type i=0; i<nb_vertices; ++i)
{
face[0] = bot;
face[1] = vertices[(i+1)%(nb_vertices)];
face[2] = vertices[i];
Euler::add_face(face, g);
}
}
return halfedge(vertices[0], apex, g).first;
}
/**
* \ingroup PkgBGLHelperFct
*
* \brief Creates an icosahedron, outward oriented, centered in `center` and adds it to the graph `g`.
*
* \param g the graph in which the icosahedron will be created.
* \param center the center of the sphere in which the icosahedron is inscribed.
* \param radius the radius of the sphere in which the icosahedron is inscribed.
*
* \returns the halfedge that has the target vertex associated with the first point in the first face.
*/
template<class Graph, class P>
typename boost::graph_traits<Graph>::halfedge_descriptor
make_icosahedron(Graph& g,
const P& center = P(0,0,0),
typename CGAL::Kernel_traits<P>::Kernel::FT radius = 1.0)
{
typedef typename boost::property_map<Graph,vertex_point_t>::type Point_property_map;
typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
Point_property_map vpmap = get(CGAL::vertex_point, g);
// create the initial icosahedron
std::vector<vertex_descriptor> v_vertices;
v_vertices.resize(12);
for(int i=0; i<12; ++i)
v_vertices[i] = add_vertex(g);
typename CGAL::Kernel_traits<P>::Kernel::FT t = radius * (1.0 + CGAL::approximate_sqrt(5.0)) / 2.0;
put(vpmap, v_vertices[0], P(-radius + center.x(), t + center.y(), 0.0 + center.z()));
put(vpmap, v_vertices[1], P( radius + center.x(), t + center.y(), 0.0 + center.z()));
put(vpmap, v_vertices[2], P(-radius + center.x(), -t + center.y(), 0.0 + center.z()));
put(vpmap, v_vertices[3], P( radius + center.x(), -t + center.y(), 0.0 + center.z()));
put(vpmap, v_vertices[4], P( 0.0 + center.x(), -radius + center.y(), t + center.z()));
put(vpmap, v_vertices[5], P( 0.0 + center.x(), radius + center.y(), t + center.z()));
put(vpmap, v_vertices[6], P( 0.0 + center.x(), -radius + center.y(), -t + center.z()));
put(vpmap, v_vertices[7], P( 0.0 + center.x(), radius + center.y(), -t + center.z()));
put(vpmap, v_vertices[8], P( t + center.x(), 0.0 + center.y(), -radius + center.z()));
put(vpmap, v_vertices[9], P( t + center.x(), 0.0 + center.y(), radius + center.z()));
put(vpmap, v_vertices[10], P(-t + center.x(), 0.0 + center.y(), -radius + center.z()));
put(vpmap, v_vertices[11], P(-t + center.x(), 0.0 + center.y(), radius + center.z()));
std::vector<vertex_descriptor> face;
face.resize(3);
face[1] = v_vertices[0]; face[0] = v_vertices[5]; face[2] = v_vertices[11];
Euler::add_face(face, g);
face[1] = v_vertices[0]; face[0] = v_vertices[1]; face[2] = v_vertices[5];
Euler::add_face(face, g);
face[1] = v_vertices[0]; face[0] = v_vertices[7]; face[2] = v_vertices[1];
Euler::add_face(face, g);
face[1] = v_vertices[0]; face[0] = v_vertices[10]; face[2] = v_vertices[7];
Euler::add_face(face, g);
face[1] = v_vertices[0]; face[0] = v_vertices[11]; face[2] = v_vertices[10];
Euler::add_face(face, g);
face[1] = v_vertices[1]; face[0] = v_vertices[9]; face[2] = v_vertices[5];
Euler::add_face(face, g);
face[1] = v_vertices[5]; face[0] = v_vertices[4]; face[2] = v_vertices[11];
Euler::add_face(face, g);
face[1] = v_vertices[11]; face[0] = v_vertices[2]; face[2] = v_vertices[10];
Euler::add_face(face, g);
face[1] = v_vertices[10]; face[0] = v_vertices[6]; face[2] = v_vertices[7];
Euler::add_face(face, g);
face[1] = v_vertices[7]; face[0] = v_vertices[8]; face[2] = v_vertices[1];
Euler::add_face(face, g);
face[1] = v_vertices[3]; face[0] = v_vertices[4]; face[2] = v_vertices[9];
Euler::add_face(face, g);
face[1] = v_vertices[3]; face[0] = v_vertices[2]; face[2] = v_vertices[4];
Euler::add_face(face, g);
face[1] = v_vertices[3]; face[0] = v_vertices[6]; face[2] = v_vertices[2];
Euler::add_face(face, g);
face[1] = v_vertices[3]; face[0] = v_vertices[8]; face[2] = v_vertices[6];
Euler::add_face(face, g);
face[1] = v_vertices[3]; face[0] = v_vertices[9]; face[2] = v_vertices[8];
Euler::add_face(face, g);
face[1] = v_vertices[4]; face[0] = v_vertices[5]; face[2] = v_vertices[9];
Euler::add_face(face, g);
face[1] = v_vertices[2]; face[0] = v_vertices[11]; face[2] = v_vertices[4];
Euler::add_face(face, g);
face[1] = v_vertices[6]; face[0] = v_vertices[10]; face[2] = v_vertices[2];
Euler::add_face(face, g);
face[1] = v_vertices[8]; face[0] = v_vertices[7]; face[2] = v_vertices[6];
Euler::add_face(face, g);
face[1] = v_vertices[9]; face[0] = v_vertices[1]; face[2] = v_vertices[8];
Euler::add_face(face, g);
return halfedge(v_vertices[1], v_vertices[0], g).first;
}
/*!
* \ingroup PkgBGLHelperFct
*
* \brief Creates a row major ordered grid with `i` cells along the width and `j` cells
* along the height and adds it to the graph `g`.
* An internal property map for `CGAL::vertex_point_t` must be available in `Graph`.
*
* \param i the number of cells along the width.
* \param j the number of cells along the height.
* \param g the graph in which the grid will be created.
* \param calculator the functor that will assign coordinates to the grid vertices.
* \param triangulated decides if a cell is composed of one quad or two triangles.
* If `triangulated` is `true`, the diagonal of each cell is oriented from (0,0) to (1,1)
* in the cell coordinates.
*
*\tparam CoordinateFunctor a function object providing:
* `%Point_3 operator()(size_type I, size_type J)`, with `%Point_3` being the value_type
* of the internal property_map for `CGAL::vertex_point_t` and outputs an object of type
* `boost::property_traits<boost::property_map<Graph,CGAL::vertex_point_t>::%type>::%value_type`.
* It will be called with arguments (`w`, `h`), with `w` in [0..`i`] and `h` in [0..`j`].<br>
* %Default: a point with positive integer coordinates (`w`, `h`, 0), with `w` in [0..`i`] and `h` in [0..`j`]
*
* \returns the non-border non-diagonal halfedge that has the target vertex associated with the first point of the grid (default is (0,0,0) ).
*/
template<class Graph, class CoordinateFunctor>
typename boost::graph_traits<Graph>::halfedge_descriptor
make_grid(typename boost::graph_traits<Graph>::vertices_size_type i,
typename boost::graph_traits<Graph>::vertices_size_type j,
Graph& g,
const CoordinateFunctor& calculator,
bool triangulated = false)
{
typedef typename boost::property_map<Graph,vertex_point_t>::type Point_property_map;
typedef typename boost::graph_traits<Graph>::vertex_descriptor vertex_descriptor;
typename boost::graph_traits<Graph>::vertices_size_type w(i+1), h(j+1);
Point_property_map vpmap = get(CGAL::vertex_point, g);
//create the vertices
std::vector<vertex_descriptor> v_vertices;
v_vertices.resize(static_cast<std::size_t>(w*h));
for(std::size_t k = 0; k < v_vertices.size(); ++k)
v_vertices[k] = add_vertex(g);
//assign the coordinates
for(typename boost::graph_traits<Graph>::vertices_size_type a=0; a<w; ++a)
for(typename boost::graph_traits<Graph>::vertices_size_type b=0; b<h; ++b)
put(vpmap, v_vertices[a+w*b], calculator(a,b));
//create the faces
std::vector<vertex_descriptor> face;
if(triangulated)
face.resize(3);
else
face.resize(4);
for(typename boost::graph_traits<Graph>::vertices_size_type a = 0; a<w-1; ++a)
{
for(typename boost::graph_traits<Graph>::vertices_size_type b = 0; b<h-1; ++b)
{
if(triangulated)
{
face[0] = v_vertices[w*b+a];
face[1] = v_vertices[w*b+a+1];
face[2] = v_vertices[w*(b+1)+a];
Euler::add_face(face, g);
face[0] = v_vertices[w*b+a+1];
face[1] = v_vertices[w*(b+1)+a+1];
face[2] = v_vertices[w*(b+1)+a];
Euler::add_face(face, g);
}
else
{
face[0] = v_vertices[w*b+ a];
face[1] = v_vertices[w*b+ a+1];
face[2] = v_vertices[w*(b+1)+ a+1];
face[3] = v_vertices[w*(b+1)+ a];
Euler::add_face(face, g);
}
}
}
return halfedge(v_vertices[1], v_vertices[0], g).first;
}
template<class Graph>
typename boost::graph_traits<Graph>::halfedge_descriptor
make_grid(typename boost::graph_traits<Graph>::vertices_size_type w,
typename boost::graph_traits<Graph>::vertices_size_type h,
Graph& g,
bool triangulated = false)
{
typedef typename boost::graph_traits<Graph>::vertices_size_type Size_type;
typedef typename boost::property_traits<typename boost::property_map<Graph, vertex_point_t>::type>::value_type Point;
return make_grid(w, h, g, internal::Default_grid_maker<Size_type, Point>(), triangulated);
}
} // namespace CGAL
// Here at the bottom because helpers.h must include generators (for backward compatibility reasons),
// and Euler_operations.h needs helpers.h
#include <CGAL/boost/graph/Euler_operations.h>
#endif // CGAL_BOOST_GRAPH_GENERATORS_H
|
jjcasmar/cgal | Combinatorial_map/include/CGAL/Combinatorial_map_fwd.h | <reponame>jjcasmar/cgal<filename>Combinatorial_map/include/CGAL/Combinatorial_map_fwd.h
// Copyright (c) 2010-2011 CNRS and LIRIS' Establishments (France).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org)
//
// $URL$
// $Id$
// SPDX-License-Identifier: LGPL-3.0-or-later OR LicenseRef-Commercial
//
// Author(s) : <NAME> <<EMAIL>>
//
#ifndef COMBINATORIAL_MAP_FWD_H
#define COMBINATORIAL_MAP_FWD_H 1
#include <CGAL/memory.h>
namespace CGAL {
#if defined(CGAL_CMAP_DART_DEPRECATED) && !defined(CGAL_NO_DEPRECATED_CODE)
template <unsigned int d>
struct Combinatorial_map_min_items;
#else
struct Generic_map_min_items;
#endif
template<unsigned int d_, class Items_, class Alloc_ >
class Combinatorial_map_storage_1;
template < unsigned int d_, class Refs_,
#if defined(CGAL_CMAP_DART_DEPRECATED) && !defined(CGAL_NO_DEPRECATED_CODE)
class Items_=Combinatorial_map_min_items<d_>,
#else
class Items_=Generic_map_min_items,
#endif
class Alloc_=CGAL_ALLOCATOR(int),
class Storage_= Combinatorial_map_storage_1<d_, Items_, Alloc_> >
class Combinatorial_map_base;
template < unsigned int d_,
#if defined(CGAL_CMAP_DART_DEPRECATED) && !defined(CGAL_NO_DEPRECATED_CODE)
class Items_=Combinatorial_map_min_items<d_>,
#else
class Items_=Generic_map_min_items,
#endif
class Alloc_=CGAL_ALLOCATOR(int),
class Storage_= Combinatorial_map_storage_1<d_, Items_, Alloc_> >
class Combinatorial_map;
} // CGAL
#endif // COMBINATORIAL_MAP_FWD_H
|
leohu2011/Phoice_Proper | experiment/userInfo.h | //
// userInfo.h
// experiment
//
// Created by Sina on 16/6/28.
// Copyright © 2016年 <NAME>. All rights reserved.
//
#ifndef userInfo_h
#define userInfo_h
#import <UIKit/UIKit.h>
@interface userInfo : NSObject
@property (nonatomic, copy) NSString * user_name;
@property (nonatomic, copy) NSString * user_password;
@property (nonatomic, copy) NSString * user_ID;
@property (nonatomic, assign) BOOL autoLogin;
@property (nonatomic, assign) BOOL rememberUserName;
@end
#endif /* userInfo_h */
|
leohu2011/Phoice_Proper | Pods/Headers/Public/DZNPhotoPickerController/DZNPhotoDisplayViewCell.h | <filename>Pods/Headers/Public/DZNPhotoPickerController/DZNPhotoDisplayViewCell.h<gh_stars>1-10
//
// DZNPhotoDisplayViewCell.h
// DZNPhotoPickerController
// https://github.com/dzenbot/DZNPhotoPickerController
//
// Created by <NAME> on 10/5/13.
// Copyright (c) 2014 DZN Labs. All rights reserved.
// Licence: MIT-Licence
//
#import <UIKit/UIKit.h>
/**
The collection view cell to be displayed on search results, with photo thumbnail.
*/
@interface DZNPhotoDisplayViewCell : UICollectionViewCell
/** The image view of the cell. (read-only). */
@property (nonatomic, readonly) UIImageView *imageView;
/**
Sets the thumbnail URL for download. This also forces cancellation of previous image download.
@param URL The image url.
*/
- (void)setThumbURL:(NSURL *)URL;
@end |
leohu2011/Phoice_Proper | experiment/tableViewController.h | <reponame>leohu2011/Phoice_Proper<gh_stars>1-10
//
// tableViewController.h
// experiment
//
// Created by Sina on 16/6/17.
// Copyright © 2016年 <NAME>. All rights reserved.
//
#ifndef tableViewController_h
#define tableViewController_h
#import <UIKit/UIKit.h>
#import "FolderArray.h"
#import "detailViewController.h"
@interface tableViewController : UITableViewController <UITableViewDataSource, detailViewDelegate>
@property (nonatomic, strong) folderArray *tv_array;
@property (nonatomic, copy) NSString *uniqueID;
@end
#endif /* tableViewController_h */
|
leohu2011/Phoice_Proper | experiment/UserLoginController.h | //
// UserLoginController.h
// experiment
//
// Created by Sina on 16/6/28.
// Copyright © 2016年 <NAME>. All rights reserved.
//
#ifndef UserLoginController_h
#define UserLoginController_h
#import <UIKit/UIKit.h>
@interface userLoginController : UIViewController
@end
#endif /* UserLoginController_h */
|
leohu2011/Phoice_Proper | Pods/Headers/Public/DRCellSlideGestureRecognizer/DRCellSlideGestureRecognizer.h | //
// DRCellSlideGestureRecognizer.h
// DRCellSlideGestureRecognizer
//
// Created by <NAME> on 12/5/15.
//
//
#import <UIKit/UIKit.h>
#import "DRCellSlideAction.h"
@interface DRCellSlideGestureRecognizer : UIPanGestureRecognizer <UIGestureRecognizerDelegate>
- (void)addActions:(id)actions;
@end
|
leohu2011/Phoice_Proper | experiment/tableViewCell.h | <filename>experiment/tableViewCell.h
//
// tableViewCell.h
// experiment
//
// Created by <NAME> on 16/5/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#ifndef tableViewCell_h
#define tableViewCell_h
#import <UIKit/UIKit.h>
#import "photoItem.h"
@interface tableViewCell : UITableViewCell
//typedef void (^updateBlock)(BOOL contain);
//@property (nonatomic, strong) NSArray *photoArray;
//@property (nonatomic, strong) UIImageView *imgView;
@property (nonatomic, copy) NSString *photoAddress;
@property (nonatomic, copy) NSString *recordingAdress;
-(void)containRecordingInCell:(BOOL)contain;
@end
#endif /* tableViewCell_h */
|
leohu2011/Phoice_Proper | experiment/startUpViewController.h | <gh_stars>1-10
//
// startUpViewController.h
// experiment
//
// Created by Sina on 16/6/17.
// Copyright © 2016年 <NAME>. All rights reserved.
//
#ifndef startUpViewController_h
#define startUpViewController_h
#import <UIKit/UIKit.h>
@interface startUpController : UIViewController<UINavigationControllerDelegate>
@end
#endif /* startUpViewController_h */
|
leohu2011/Phoice_Proper | experiment/detailViewController.h | //
// detailView.h
// experiment
//
// Created by <NAME> on 17/5/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#ifndef detailView_h
#define detailView_h
#import <UIKit/UIKit.h>
@class rootViewController, photoItem;
@protocol detailViewDelegate <NSObject>
-(void) changeCellInfoWithText: (NSString*) string andDetailInfo: (NSString*) detail onIndexPath: (NSIndexPath*) indexpath;
@end
@interface detailViewController : UIViewController
-(instancetype) initWithIndex:(NSIndexPath*)index andAddress: (NSString*) address;
@property (nonatomic, weak) id <detailViewDelegate> delegate;
@property (nonatomic, copy) NSString *photoLocation;
@property (nonatomic, copy) NSString *audioLocation;
@property (nonatomic, copy) NSString *parant_unique_ID;
@property (nonatomic, copy) NSString *audio_unique_ID;
@end
#endif /* detailView_h */
|
leohu2011/Phoice_Proper | experiment/FolderArray.h | //
// Folder_Photo_Array.h
// experiment
//
// Created by Sina on 16/6/16.
// Copyright © 2016年 <NAME>. All rights reserved.
//
#ifndef Folder_Photo_Array_h
#define Folder_Photo_Array_h
#import <UIKit/UIKit.h>
//folderArray could contain both folder_array and AVUnit items.
@interface folderArray : NSObject<NSCoding>
//folder_count keeps track of the number of subfolders in the current fparray
//@property (nonatomic, assign) NSInteger folder_count;
//item_count keeps track of the number of photo_items in the current fparray
//@property (nonatomic, assign) NSInteger item_count;
@property (nonatomic, strong) NSMutableArray *content_array;
//@property (nonatomic, copy) folderArray *folder_array;
//
//@property (nonatomic, copy) NSMutableArray *item_array;
@property (nonatomic, copy) NSString *folderName;
//this ID is used as the key to its subarray objects
@property (nonatomic, copy) NSString *unique_ID;
@property (nonatomic, copy) NSString *parant_ID;
-(NSInteger) obtainFolderCount;
-(NSInteger) obtainItemCount;
/*
//rewriting nsmutableArray methods
- (NSUInteger)count;
- (id)objectAtIndex:(NSUInteger)index;
- (void)addObject:(id)anObject;
- (void)insertObject:(id)anObject atIndex:(NSUInteger)index;
- (void)removeLastObject;
- (void)removeObjectAtIndex:(NSUInteger)index;
- (void)replaceObjectAtIndex:(NSUInteger)index withObject:(id)anObject;
*/
@end
#endif /* Folder_Photo_Array_h */
|
leohu2011/Phoice_Proper | experiment/rootViewController.h | <gh_stars>1-10
//
// rootViewController.h
// experiment
//
// Created by <NAME> on 16/5/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#ifndef rootViewController_h
#define rootViewController_h
#import <UIKit/UIKit.h>
#import "tableViewCell.h"
#import "photoItem.h"
#import "detailViewController.h"
@interface rootViewController : UIViewController <UITableViewDataSource, UITableViewDelegate,detailViewDelegate>
@property (nonatomic, strong) UITableView *tblView;
@end
#endif /* rootViewController_h */
|
leohu2011/Phoice_Proper | experiment/AVUnit.h | <reponame>leohu2011/Phoice_Proper<filename>experiment/AVUnit.h
//
// AVUnit.h
// experiment
//
// Created by Sina on 16/6/17.
// Copyright © 2016年 <NAME>. All rights reserved.
//
#ifndef AVUnit_h
#define AVUnit_h
#import <UIKit/UIKit.h>
@interface AVUnit : NSObject
@property (nonatomic, copy) NSString *small_address;
@property (nonatomic, strong) NSData *small_data;
@property (nonatomic, copy) NSString *big_address;
@property (nonatomic, strong) NSData *big_data;
@property (nonatomic, copy) NSString *recording_address; //could be extended to an array of recordings
@property (nonatomic, copy) NSString *recording_unique_ID;
@property (nonatomic, copy) NSString *text_description;
@property (nonatomic, copy) NSString *detail_description;
@property (nonatomic, copy) NSString *parant_folder_ID;
@end
#endif /* AVUnit_h */
|
leohu2011/Phoice_Proper | Pods/Headers/Public/DZNPhotoPickerController/DZNPhotoServiceConstants.h | <gh_stars>1-10
//
// DZNPhotoServiceConstants.h
// DZNPhotoPickerController
// https://github.com/dzenbot/DZNPhotoPickerController
//
// Created by <NAME> on 2/14/14.
// Copyright (c) 2014 DZN Labs. All rights reserved.
// Licence: MIT-Licence
//
#import <Foundation/Foundation.h>
#import "DZNPhotoPickerControllerConstants.h"
/**
Returns an unique key for saving data to NSUserDefaults.
@param type An integer enum type (ie: DZNPhotoPickerControllerService500px)
@param key A constant string key (ie: DZNPhotoServiceClientSubscription)
@returns A unique key.
*/
UIKIT_EXTERN NSString *NSUserDefaultsUniqueKey(NSUInteger type, NSString *key);
/**
Returns a base URL for creating an HTTP client based on the specified service.
*/
UIKIT_EXTERN NSURL *baseURLForService(DZNPhotoPickerControllerServices service);
/**
Returns a key path for tags, to retrieve them from a JSON structure, for a specified service.
*/
UIKIT_EXTERN NSString *tagsResourceKeyPathForService(DZNPhotoPickerControllerServices service);
/**
Returns the url path for tag search, for a specified service.
*/
UIKIT_EXTERN NSString *tagSearchUrlPathForService(DZNPhotoPickerControllerServices service);
/**
Returns a key path for photos, to retrieve them from a JSON structure, for a specified service.
*/
UIKIT_EXTERN NSString *photosResourceKeyPathForService(DZNPhotoPickerControllerServices service);
/**
Returns the url path for photo search, for a specified service.
*/
UIKIT_EXTERN NSString *photoSearchUrlPathForService(DZNPhotoPickerControllerServices service);
/**
Returns the url path for authentication, for a specified service.
*/
UIKIT_EXTERN NSString *authUrlPathForService(DZNPhotoPickerControllerServices service);
/**
Returns a key to be used for setting a consumer identifier value, for a specified service.
*/
UIKIT_EXTERN NSString *keyForAPIConsumerKey(DZNPhotoPickerControllerServices service);
/**
Returns a key to be used for setting a consumer secret value, for a specified service.
*/
UIKIT_EXTERN NSString *keyForAPIConsumerSecret(DZNPhotoPickerControllerServices service);
/**
Returns a key to be used for setting a photo search term value, for a specified service.
*/
UIKIT_EXTERN NSString *keyForSearchTerm(DZNPhotoPickerControllerServices service);
/**
Returns a key to be used for setting a tag search term value, for a specified service.
*/
UIKIT_EXTERN NSString *keyForSearchTag(DZNPhotoPickerControllerServices service);
/**
Returns a key to be used for setting a search result value per page, for a specified service.
*/
UIKIT_EXTERN NSString *keyForSearchResultPerPage(DZNPhotoPickerControllerServices service);
/**
Returns a key to be used for retrieving search tag content, for a specified service.
*/
UIKIT_EXTERN NSString *keyForSearchTagContent(DZNPhotoPickerControllerServices service);
/**
Returns a key path for photos or tags, to retrieve them from a JSON structure, for a specified service and object name.
*/
UIKIT_EXTERN NSString *keyPathForObjectName(DZNPhotoPickerControllerServices service, NSString *objectName);
/**
Determines if the service requires a consumer secret.
*/
UIKIT_EXTERN BOOL isConsumerSecretRequiredForService(DZNPhotoPickerControllerServices services);
/**
Determines if the service requires the consumer key to be posted as part of the request parameters.
*/
UIKIT_EXTERN BOOL isConsumerKeyInParametersRequiredForService(DZNPhotoPickerControllerServices services);
/**
Determines if the service requires any sort of authentification (Only Auth2 is supported for now).
*/
UIKIT_EXTERN BOOL isAuthenticationRequiredForService(DZNPhotoPickerControllerServices services);
|
leohu2011/Phoice_Proper | Pods/Headers/Public/DZNPhotoPickerController/DZNPhotoSearchResultsController.h | //
// DZNPhotoSearchResultsController.h
// DZNPhotoPickerController
// https://github.com/dzenbot/DZNPhotoPickerController
//
// Created by <NAME> on 10/5/13.
// Copyright (c) 2014 DZN Labs. All rights reserved.
// Licence: MIT-Licence
//
#import <UIKit/UIKit.h>
@class DZNPhotoTag;
/** A view controller used to display auto-completion results. */
@interface DZNPhotoSearchResultsController : UITableViewController
/**
Returns a DZNPhotoTag at index path.
@param indexPath The index path locating the row in the table view.
@return A tag object.
*/
- (DZNPhotoTag *)tagAtIndexPath:(NSIndexPath *)indexPath;
/**
Appends auto-completion tah results.
@param results An array of DZNPhotoTag to be displayed in the list.
*/
- (void)setSearchResults:(NSArray *)result;
@end
|
leohu2011/Phoice_Proper | experiment/photoItem.h | <reponame>leohu2011/Phoice_Proper<gh_stars>1-10
//
// photoItem.h
// experiment
//
// Created by <NAME> on 16/5/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#ifndef photoItem_h
#define photoItem_h
#import <UIKit/UIKit.h>
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import "SCSiriWaveformView.h"
@interface photoItem : NSObject <AVAudioRecorderDelegate, AVAudioPlayerDelegate>{
}
@property (nonatomic, copy) NSString *photoAddress;
@property (nonatomic, strong) NSData *big_photo_data;
@property (nonatomic, strong) NSData *small_photo_data;
@property (nonatomic, copy) NSString *audioAddress;
@property (nonatomic, copy) NSString *audio_unique_ID;
@property (nonatomic, assign) NSInteger itemIndex;
@property (nonatomic, strong) AVAudioRecorder *audioRecorder;
@property (nonatomic, strong) AVAudioPlayer *audioPlayer;
//initialization
-(void) initializeRecorder;
-(void) initializePlayer;
-(void) validateMicrophoneAccess;
-(void) initializeAudioSession;
-(SCSiriWaveformView *) initializeWaveView;
-(UIVisualEffectView*) initializeVEViewWithFrame: (CGRect) rect;
-(void)startUpdatingMeter;
-(void)stopUpdatingMeter;
-(void)updateMeters;
//recorder
- (void)recordClick:(UIButton *)sender;
- (void)pauseClick:(UIButton *)sender;
- (void)resumeClick:(UIButton *)sender;
- (void)stopClick:(UIButton *)sender;
//player
-(void)playRecording:(UIButton*)sender;
-(void)pauseRecording : (UIButton*) sender;
-(void) stopRecording : (UIButton *) sender;
@end
#endif /* photoItem_h */
|
leohu2011/Phoice_Proper | experiment/networkRequest.h | <gh_stars>1-10
//
// networkRequest.h
// experiment
//
// Created by <NAME> on 5/7/16.
// Copyright © 2016 <NAME>. All rights reserved.
//
#ifndef networkRequest_h
#define networkRequest_h
#import <UIKit/UIKit.h>
#import "userInfo.h"
@interface networkRequest : NSObject
typedef void (^completionBlock)(BOOL result);
//typedef enum{
// case_register,
// case_login,
//}networkRequestType;
//@property (nonatomic, copy) NSString *destination;
//@property (nonatomic, strong) NSDictionary *parameter;
//@property (nonatomic, assign) networkRequestType *type;
//user login module
-(void)processRegisterRequestWithParameter: (userInfo*)user CompletionHandler:(completionBlock)returnResult;
-(void)processLoginRequestWithParameter:(userInfo *)user CompletionHandler:(completionBlock)returnResult;
-(void)checkForDuplicateUserName:(userInfo*) user CompletionHandler: (completionBlock)returnResult;
//user share/retrive info module
-(void)sendOverImage: (UIImage*) img CompletionHandler: (completionBlock)returnResult;
-(void)sendOverAudioDataWithAddress: (NSString*)address CompletionHandler: (completionBlock)returnResult;
-(UIImage*)retriveImageWithName: (NSString*)name CompletionHandler: (completionBlock)returnResult;
-(void) retriveVoiceDataWithName: (NSString*)name ToLocalDestination: (NSString*) destination CompletionHandler: ( completionBlock) returnResult;
@end
#endif /* networkRequest_h */
|
averov90/circular-buffer-Queue | Queue.h | <filename>Queue.h
#pragma once
#include <cstring>
#include <stdexcept>
template <typename T>
class Queue {
T *items, *itemse, *pick, *place;
unsigned int capacitance, stored_count;
public:
Queue(unsigned int capacity = 8):capacitance(capacity) {
if (!capacity) throw std::invalid_argument("Capacity must be at least 1!");
pick = place = items = reinterpret_cast<T *>(malloc(capacity * sizeof(T)));
if (!items) throw std::runtime_error("You don't have enough memory!");
stored_count = 0;
itemse = items + capacity;
}
Queue(const Queue &) = delete;
Queue operator=(const Queue &) = delete;
~Queue() {
free(items);
}
void emplace(const T &item) {
if (place != pick) { // Common case
new (place) T(item); //Assigning an item to a memory address.
++stored_count;
if (++place == itemse) {
place = items;
}
} else {
if (!stored_count) { // Ring is empty, all is ok
new (place) T(item); //Assigning an item to a memory address.
++stored_count;
if (++place == itemse) {
place = items;
}
} else { //Ring is full, expanding needed
unsigned int capacity_new = capacitance << 1;
if (capacitance > capacity_new) throw std::out_of_range("You have reached the UNSIGNED INT limit!");
T *new_pointer = reinterpret_cast<T *>(realloc(items, capacity_new * sizeof(T)));
if (!new_pointer) throw std::runtime_error("You don't have enough memory!");
unsigned int epic_offset = place - items;
items = new_pointer;
if (epic_offset) {
pick = new_pointer + capacity_new - capacitance + epic_offset;
memcpy(pick, new_pointer + epic_offset, (capacitance - epic_offset) * sizeof(T));
place = new_pointer + epic_offset;
} else {
place = new_pointer + capacitance;
pick = new_pointer;
}
capacitance = capacity_new;
itemse = items + capacitance;
new (place) T(item); //Assigning an item to a memory address.
++stored_count;
if (++place == itemse) {
place = items;
}
}
}
}
unsigned int capacity() const {
return capacitance;
}
void capacity(unsigned int new_capacity) {
if (!new_capacity) throw std::out_of_range("Capacity must be at least 1!");
if (stored_count > new_capacity) throw std::out_of_range("The capacity of the structure cannot be less than the number of elements in it!");
T *new_pointer = reinterpret_cast<T *>(malloc(new_capacity * sizeof(T)));
if (!new_pointer) throw std::runtime_error("You don't have enough memory!");
if (stored_count) {
if (place > pick || place == items) {
memcpy(new_pointer, pick, stored_count * sizeof(T));
} else {
memcpy(new_pointer, pick, (itemse - pick) * sizeof(T));
memcpy(new_pointer + (itemse - pick), items, (place - items) * sizeof(T));
}
}
pick = new_pointer;
if (new_capacity == stored_count)
place = new_pointer;
else
place = new_pointer + stored_count;
capacitance = new_capacity;
free(items); items = new_pointer;
itemse = items + new_capacity;
}
void push(T item) {
const T &ref = item;
emplace(item);
}
bool isNotEmpty() const {
return stored_count;
}
T peek() const {
if (!stored_count) throw std::underflow_error("Nothing to Peek!");
return *pick;
}
T pop() {
if (stored_count) {
T item = *pick;
pick->~T();
--stored_count;
if (++pick == itemse) {
pick = items;
}
return item;
} else
throw std::underflow_error("Nothing to Pop!");
}
unsigned int count() const {
return stored_count;
}
void reverse() {
if (stored_count > 1) {
T tmp;
T *pk = pick, *em = place - 1;
if (em < items) em = itemse - 1;
while (true) {
tmp = *pk; *pk = *em; *em = tmp;
if (++pk == itemse) pk = items;
if (pk == em) break;
if (--em < items) em = itemse - 1;
if (pk == em) break;
}
}
}
// Additional functionality for example
void removeInRange(T min, T max) {
if (stored_count) {
T *tbuff = reinterpret_cast<T *>(malloc(capacitance * sizeof(T))), *cpos = tbuff;
if (!tbuff) throw std::runtime_error("You don't have enough memory!");
T *pk = pick, *em = place;
do {
if (*pk < min || *pk > max) {
memcpy(cpos, pk, sizeof(T));
++cpos;
} else
pk->~T();
if (++pk == itemse) pk = items;
} while (pk != em);
pick = tbuff;
stored_count = cpos - tbuff;
if (stored_count == capacitance)
place = tbuff;
else
place = tbuff + stored_count;
free(items);
items = tbuff;
itemse = tbuff + capacitance;
}
}
bool operator==(const Queue &arg) const {
if (arg.stored_count != stored_count)
return false;
if (stored_count) {
T *pk = pick, *em = place;
T *pk2 = arg.pick;
do {
if (*pk != *pk2)
return false;
if (++pk == itemse)
pk = items;
if (++pk2 == arg.itemse)
pk2 = arg.items;
} while (pk != em);
}
return true;
}
bool operator>(const Queue &arg) const {
if (stored_count) {
if (arg.stored_count) {
T *pk = pick, *em = place;
T *pk2 = arg.pick, *em2 = arg.place;
while (true) {
if (*pk > *pk2)
return true;
else if (*pk < *pk2)
return false;
if (++pk == itemse)
pk = items;
if (pk == em) return false;
if (++pk2 == arg.itemse)
pk2 = arg.items;
if (pk2 == em2) return true;
}
} else
return true;
}
return false;
}
//Just to be short. If necessary, you can make a separate implementation for each operator (like for == and >), which will speed them up.
bool operator!=(const Queue &arg) const {
return !(*this == arg);
}
bool operator>=(const Queue &arg) const {
return *this > arg || *this == arg;
}
bool operator<=(const Queue &arg) const {
return !(*this > arg);
}
bool operator<(const Queue &arg) const {
return *this <= arg && *this != arg;
}
}; |
averov90/circular-buffer-Queue | CircularBuffer.h | <reponame>averov90/circular-buffer-Queue
#pragma once
#include <cstring>
#include <ostream>
#include <stdexcept>
#include <iterator>
template <typename T>
class CircularBuffer {
T *items, *itemse, *pick, *place;
unsigned int capacitance, stored_count;
public:
CircularBuffer(unsigned int capacity):capacitance(capacity) {
if (!capacity) throw std::invalid_argument("Capacity must be at least 1!");
pick = place = items = reinterpret_cast<T *>(malloc(capacity * sizeof(T)));
if (!items) throw std::runtime_error("You don't have enough memory!");
stored_count = 0;
itemse = items + capacity;
}
CircularBuffer(const std::initializer_list<T> &list): capacitance(list.size()) {
if (!capacitance) throw std::invalid_argument("Capacity must be at least 1!");
stored_count = capacitance;
pick = place = items = reinterpret_cast<T *>(malloc(capacitance * sizeof(T)));
if (!items) throw std::runtime_error("You don't have enough memory!");
itemse = items + capacitance;
{
const T *citem = list.begin();
for (T *cwpos = items; cwpos != itemse; ++cwpos, ++citem)
memcpy(cwpos, citem, sizeof(T));
}
}
CircularBuffer(const CircularBuffer &arg): capacitance(arg.capacitance), stored_count(arg.stored_count) {
items = reinterpret_cast<T *>(malloc(capacitance * sizeof(T)));
if (!items) throw std::runtime_error("You don't have enough memory!");
itemse = items + capacitance;
place = items + (arg.place - arg.items);
pick = items + (arg.pick - arg.items);
memcpy(items, arg.items, capacitance * sizeof(T));
}
CircularBuffer &operator=(const CircularBuffer &arg) {
if (this != &arg) {
capacitance = arg.capacitance;
stored_count = arg.stored_count;
items = std::unique_ptr<T[]>(new T[capacitance]);
itemse = items.get() + capacitance;
place = items.get() + (arg.place - arg.items.get());
pick = items.get() + (arg.pick - arg.items.get());
memcpy(items.get(), arg.items.get(), capacitance * sizeof(T));
}
return *this;
}
~CircularBuffer() {
free(items);
}
void emplace(const T &item) {
if (place == pick) { // Common case
if (stored_count) { //Ring is full, rewriting
place->~T();
new (place) T(item); //Assigning an item to a memory address.
if (++pick == itemse) {
pick = items;
}
place = pick;
} else { // Ring is empty, all is ok
new (place) T(item); //Assigning an item to a memory address.
++stored_count;
if (++place == itemse) {
place = items;
}
}
} else {
new (place) T(item); //Assigning an item to a memory address.
++stored_count;
if (++place == itemse) {
place = items;
}
}
}
void emplace(unsigned int index, const T &item) {
if (index >= stored_count) throw std::out_of_range("Index out of range!");
unsigned int must_steps = stored_count - index;
T *back = place, *front;
//Getting empty place
if (place == pick) {
if (++pick == itemse) {
pick = items;
}
--must_steps; //It is necessary to account for the change in index from the deletion of the oldest element
} else
++stored_count;
if (++place == itemse) {
place = items;
}
//Shifting items
for (unsigned int cstep = 0; cstep != must_steps; ++cstep) {
front = back;
if (--back < items) {
back = itemse - 1;
}
memcpy(front, back, sizeof(T));
}
back->~T();
//Emplacing
new (back) T(item);
}
void erase(unsigned int index) {
if (index >= stored_count) throw std::out_of_range("Index out of range!");
T *back, *front = pick;
--stored_count;
//Moving to needed item
for (unsigned int cstep = 0; cstep != index; ++cstep) {
if (++front == itemse) {
front = items;
}
}
if (--place < items) {
place = itemse - 1;
}
front->~T();
//Shifting items
while (front != place) {
back = front;
if (++front == itemse) {
front = items;
}
memcpy(back, front, sizeof(T));
}
}
unsigned int capacity() const {
return capacitance;
}
void capacity(unsigned int new_capacity) {
if (!new_capacity) throw std::out_of_range("Capacity must be at least 1!");
if (stored_count > new_capacity) throw std::out_of_range("The capacity of the structure cannot be less than the number of elements in it!");
T *new_pointer = reinterpret_cast<T *>(malloc(new_capacity * sizeof(T)));
if (!new_pointer) throw std::runtime_error("You don't have enough memory!");
if (stored_count) {
if (place > pick || place == items) {
memcpy(new_pointer, pick, stored_count * sizeof(T));
} else {
memcpy(new_pointer, pick, (itemse - pick) * sizeof(T));
memcpy(new_pointer + (itemse - pick), items, (place - items) * sizeof(T));
}
}
pick = new_pointer;
if (new_capacity == stored_count)
place = new_pointer;
else
place = new_pointer + stored_count;
capacitance = new_capacity;
free(items); items = new_pointer;
itemse = items + new_capacity;
}
void insert(unsigned int index, T item) {
const T &ref = item;
emplace(index, item);
}
void push(T item) {
const T &ref = item;
emplace(item);
}
T pop() {
if (stored_count) {
T item = *pick;
pick->~T();
--stored_count;
if (++pick == itemse) {
pick = items;
}
return item;
} else
throw std::underflow_error("Nothing to Pop!");
}
unsigned int count() const {
return stored_count;
}
bool operator==(const CircularBuffer &arg) const {
if (arg.stored_count != stored_count)
return false;
if (stored_count) {
T *pk = pick, *em = place;
T *pk2 = arg.pick;
do {
if (*pk != *pk2)
return false;
if (++pk == itemse)
pk = items;
if (++pk2 == arg.itemse)
pk2 = arg.items;
} while (pk != em);
}
return true;
}
bool operator>(const CircularBuffer &arg) const {
if (stored_count) {
if (arg.stored_count) {
T *pk = pick, *em = place;
T *pk2 = arg.pick, *em2 = arg.place;
while (true) {
if (*pk > *pk2)
return true;
else if (*pk < *pk2)
return false;
if (++pk == itemse)
pk = items.get();
if (pk == em) return false;
if (++pk2 == arg.itemse)
pk2 = arg.items.get();
if (pk2 == em2) return true;
}
} else
return true;
}
return false;
}
//Just to be short. If necessary, you can make a separate implementation for each operator (like for == and >), which will speed them up.
bool operator!=(const CircularBuffer &arg) const {
return !(*this == arg);
}
bool operator>=(const CircularBuffer &arg) const {
return *this > arg || *this == arg;
}
bool operator<=(const CircularBuffer &arg) const {
return !(*this > arg);
}
bool operator<(const CircularBuffer &arg) const {
return *this <= arg && *this != arg;
}
class iterator {
friend class CircularBuffer;
unsigned int index, err_index;
T *ptr, *base, *end;
iterator(T *current, T *base, T *end, unsigned int index, unsigned int err_index): ptr(current), base(base), end(end), index(index), err_index(err_index){ }
public:
using iterator_category = std::bidirectional_iterator_tag;
using value_type = T;
using difference_type = std::ptrdiff_t;
using pointer = T*;
using reference = T&;
//iterator(const iterator &it); //Not need
//iterator &operator=(iterator const &other);
unsigned int get_index() const {
return index;
}
bool operator!=(iterator const &other) const {
return index != other.index;
}
bool operator==(iterator const &other) const {
return index == other.index;
}
T &operator*() const {
if (index == err_index) throw std::logic_error("Can not dereference end iterator!");
return *ptr;
}
T *operator->() const {
if (index == err_index) throw std::logic_error("Can not dereference end iterator!");
return ptr;
}
iterator &operator++() {
if (index == err_index) throw std::out_of_range("Iterator out of range!");
++index;
if (++ptr == end) {
ptr = base;
}
return *this;
}
iterator operator++(int) {
if (index == err_index) throw std::out_of_range("Iterator out of range!");
iterator temp(*this);
++index;
if (++ptr == end) {
ptr = base;
}
return temp;
}
iterator &operator--() {
if (index == 0) throw std::out_of_range("Iterator out of range!");
--index;
if (--ptr < base) {
ptr = end - 1;
}
return *this;
}
iterator operator--(int) {
if (index == 0) throw std::out_of_range("Iterator out of range!");
iterator temp(*this);
--index;
if (--ptr < base) {
ptr = end - 1;
}
return temp;
}
};
iterator begin() const {
return iterator(pick, items, itemse, 0, stored_count);
}
iterator end() const {
return iterator(place, items, itemse, stored_count, stored_count);
}
};
template<typename T>
std::ostream &operator<<(std::ostream &out, const CircularBuffer<T> &buffer) {
for (auto item : buffer) {
out << item << std::endl;
}
return out;
} |
software-foundations/learning-c | 03_functions/04_maximum.c | <filename>03_functions/04_maximum.c
#include <stdio.h>
// Function prototype
int maximum(int, int, int);
int main(void)
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
printf("Greather: %d\n", maximum(a, b, c));
return 0;
}
// Function definition
int maximum(int x, int y, int z)
{
int max = x;
if (y > max)
max = y;
if (z > max)
max = z;
return z;
} |
software-foundations/learning-c | 01_basics/05_aritmetic_operators.c | #include <stdio.h>
#include <stdlib.h>
int main(void) {
float a = 5;
float b = 2;
int c = 5;
int d = 2;
printf("a + b -> %f\n", a + b);
printf("a - b -> %f\n", a - b);
printf("a * b -> %f\n", a * b);
printf("a / b -> %f\n", a / b);
printf("a module b -> %d\n", c % d);
return 0;
} |
software-foundations/learning-c | 03_functions/06_srand.c | #include <stdlib.h>
#include <stdio.h>
#include <time.h>
int generate_20_random_numbers(void);
int main(void)
{
unsigned int seed;
unsigned int timestamp;
printf("### seed: ");
scanf("%u", &seed);
generate_20_random_numbers();
srand(seed);
timestamp = time(NULL);
srand(timestamp);
printf("### Timestamp: %u\n", timestamp);
generate_20_random_numbers();
return 0;
}
int generate_20_random_numbers(void)
{
int i;
for (i = 1; i <= 20; i ++)
{
int random = rand();
printf("%d -> %d\n", i, random);
}
} |
software-foundations/learning-c | 02_flow_control/07_break.c | <reponame>software-foundations/learning-c<gh_stars>0
#include <stdio.h>
#include <stdlib.h>
// continue behavior in
// 1 - while
// 2 - for
// 3 - do while
int main(void) {
int i = 0;
int j = 0;
int k = 0;
printf("while\n");
while (i <= 5) {
printf("\ni == %d", i);
i++;
if (i == 3) {
printf("\ni == 3 mached");
break;
}
}
printf("\n\nfor\n");
for (j = 0; j <= 5; j++) {
printf("\nj == %d", j);
if (j == 3) {
printf("\nj == 3 mached");
break;
}
}
printf("\n\ndo_while\n");
do {
printf("\nk == %d", k);
k++;
if (k == 3) {
printf("\nk == 3 mached");
break;
}
} while (k <= 5);
return 0;
} |
software-foundations/learning-c | 01_basics/07_relational_operators.c | #include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("%d\n", 1 > 0);
printf("%d\n\n", 1 < 0);
printf("%d\n", 1 >> 0);
printf("%d\n\n", 1 << 0);
printf("%d\n", 1 >> 1);
printf("%d\n", 1 << 1);
return 0;
} |
software-foundations/learning-c | 03_functions/05_rand.c | <reponame>software-foundations/learning-c
#include <stdio.h>
#include <stdlib.h>
// Prototype
int module(int dividend, int divisor);
int main(void)
{
int i;
int j;
int k;
for (i = 1; i <= 5; i++)
{
printf("i %d -> %d\n", i, rand());
}
for (j = 1; j <= 20; j ++)
{
int random = rand();
int module = random % 6;
printf("j %d -> %d -> %d\n", j, random, module);
}
for (k = 1; k <= 20; k ++)
{
int random = rand();
int module = random % 6;
printf("%d ", module);
if ( module == 0 )
{
printf("\n");
}
}
return 0;
} |
software-foundations/learning-c | 02_flow_control/01_if.c | #include <stdio.h>
#include <stdlib.h>
int main(void) {
// true -> != 0
// false -> == 0
if (-1) {
printf("-1\n");
}
if (0) {
printf("if 0 -> true\n");
} else {
printf("if 0 -> false\n");
}
if (0.5) {
printf("0.5\n");
}
if (1) {
printf("1\n");
}
// if nested
if (1) {
if (2) {
printf("if 1 if 2\n");
// end if (2)
}
// end if (1)
}
if (0) {
printf(" if 0\n");
// end if (0)
} else {
if (1) {
printf("if 0 else if 1\n");
}
}
return 0;
} |
software-foundations/learning-c | 03_functions/01_statement_and_invocation.c | <filename>03_functions/01_statement_and_invocation.c
#include <stdio.h>
#include <stdlib.h>
int accumulate(int value) {
int accumulated = 0;
for (int i = 0; i <= value; i++) {
accumulated += i;
}
return accumulated;
}
int main(void) {
int result;
result = accumulate(10);
printf("accumulate(10) == %d", result);
return 0;
} |
software-foundations/learning-c | 01_basics/12_logical_operators.c | #include <stdio.h>
#include <stdlib.h>
int main(void) {
int a = 0;
int b = 10;
if (a == 0 && b == 10) {
printf("a == 0 && b == 10\n");
}
if (a == 0 || b == 0) {
printf("a == 0 or b == 0\n");
}
if (!(a == 10)) {
printf("!(a == 10)");
}
return 0;
} |
software-foundations/learning-c | 03_functions/03_square.c | #include <stdio.h>
int square(int);
int main(void)
{
int x;
for (x = 1; x <= 10 ; x ++)
{
printf("-> %d\n", square(x));
}
return 0;
}
int square(int number)
{
return number * number;
} |
software-foundations/learning-c | 01_basics/09_assignment_operators.c | #include <stdio.h>
#include <stdlib.h>
int main(void) {
int var_int = 0;
var_int += 3;
var_int -= 1;
var_int *= 5;
var_int /= 2;
var_int %= 4;
printf("var_int %d\n", var_int);
return 0;
} |
software-foundations/learning-c | 02_flow_control/05_switch.c | <gh_stars>0
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int var = 30;
switch (var) {
case 0:
printf("var == 0");
break;
case 10:
printf("var == 10");
break;
case 20:
printf("var == 20");
break;
default:
printf("var is not 0, 10, or 20!");
}
return 0;
} |
software-foundations/learning-c | 02_flow_control/02_conditional_operator.c | #include <stdio.h>
#include <stdlib.h>
int main(void) {
printf("%s", 1 > 0 ? "true\n" : "false\n");
1 > 0 ? printf("true\n") : printf("false\n");
return 0;
} |
software-foundations/learning-c | 01_basics/11_math.c | <reponame>software-foundations/learning-c
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
void srand_usage(void);
int main(void) {
printf("sqrt(25) == %f\n\n", sqrt(25));
printf("2 ^ 5 == %f\n\n", pow(2, 5));
printf("log(2.718282) == %f\n\n", log(2.718282));
printf("log10(1.0) == %f\n\n", log10(1));
printf("fabs(-3) == %f\n\n", fabs(-3));
printf("ceil(3.1) == %f\n\n", ceil(3.1));
printf("floor(3.8) == %f\n\n", floor(3.8));
printf("fmod(5.1/3) == %f\n\n", fmod(5.1, 3));
printf("rand() == %d\n\n", rand());
printf("rand() == %d\n\n", rand());
printf("rand() == %d\n\n", 1 + rand() % 6);
printf("rand() == %d\n\n", 1 + rand() % 6);
/*
* sin (x)
* cos (x)
* sin (x)
where x is in radians
*/
printf("sin(45) = %f\n\n", sin(45));
printf("cos(45) = %f\n\n", cos(45));
printf("tan(45) = %f\n\n", tan(45));
srand_usage();
return 0;
}
void srand_usage(void) {
// seed is the number used to generate a fix sequence of random numbers
unsigned seed;
printf("\nsrand_usage\n");
printf("srand(1)\n");
seed = 1;
srand(seed);
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n\n", rand());
printf("srand(1)\n");
// autocast int to unsigned
srand(1);
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n\n", rand());
printf("srand(2)\n");
seed = 2;
srand(seed);
printf("%d\n", rand());
printf("%d\n", rand());
printf("%d\n", rand());
return;
} |
software-foundations/learning-c | 02_flow_control/04_for.c | #include <stdio.h>
#include <stdlib.h>
int line_break() { printf("---------\n"); }
// counter-controled repetition
int main(void) {
int i;
int sum;
// ++i works the same
for (i = 1; i <= 5; i++) {
printf("%d\n", i);
}
line_break();
// --i works the same
for (i = 5; i > 0; i--) {
printf("%d\n", i);
}
line_break();
// for (expression 1; EXPRESSION 2; expression 3) {}
// we can declare variable inside loop
for (int j = 0; j <= 5 * 2; j++) {
printf("j %d\n", j);
}
line_break();
// AVOID THIS
sum = 0;
for (i = 0; i <= 3; sum += i, i++)
;
printf("sum %d\n", sum);
// PREFERE THIS APPROACH
sum = 0;
for (i = 0; i <= 3; i++) {
sum += i;
}
printf("sum %d\n", sum);
return 0;
} |
software-foundations/learning-c | 01_basics/02_input_user_and_math_operations.c | #include <stdio.h>
int main(void) {
int a;
float b;
int c = 3;
float d = 4;
float result_float;
int result_int;
printf("a: ");
scanf("%d", &a);
printf("b: ");
scanf("%f", &b);
result_float = a + b;
printf("a + b: %f\n", result_float);
result_int = a + c;
printf("a + c: %d\n", result_int);
result_float = c + d;
printf("c + d: %f\n", result_float);
return 0;
} |
software-foundations/learning-c | 03_functions/02_prototype.c | #include <stdio.h>
#include <stdlib.h>
// function prototypes
int sum_10(int value);
float multiply_by_1_5(int value);
void say_hello();
int main(void) {
printf("sum_10(5) == %d\n\n", sum_10(5));
printf("multiply_by_1_5(2) == %f\n\n", multiply_by_1_5(2));
say_hello();
return 0;
}
int sum_10(int value) { return value + 10; }
float multiply_by_1_5(int value) { return value * 1.5; }
void say_hello() {
printf("hello!");
return;
} |
software-foundations/learning-c | 01_basics/04_2_auto_casting.c | #include <stdio.h>
#include <stdlib.h>
int main(void) {
float a = 1;
int b = 2;
// with variables
printf("%f\n", a + b);
printf("%d\n", 1 + b);
// with values
printf("%f\n", 1.0 + 2);
printf("%d\n", 1 + 2);
} |
software-foundations/learning-c | 01_basics/04_1_casting_types.c | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void) {
char string_from_int[2];
char string_from_float[10];
printf("%d\n", (int)1.0);
printf("%f\n", (float)1);
printf("%.2f\n", (float)2);
sprintf(string_from_int, "%d", 3);
printf("%s\n", string_from_int);
sprintf(string_from_float, "%f", 4.0);
printf("%s\n", string_from_float);
return 0;
} |
software-foundations/learning-c | 02_flow_control/03_while.c | <reponame>software-foundations/learning-c<gh_stars>0
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int i = 0;
int j = 0;
int k = -1;
int l = 10;
// counter-controled repetition
while (i < 10) {
printf("%d\n", i);
i = i + 1;
}
printf("\n");
while (j < 10) {
printf("%d\n", j);
j++;
}
printf("\n");
// k++ works the same
while (++k < 10) {
printf("%d\n", k);
}
printf("\n");
// k-- works the same
while (--l >= 0) {
printf("%d\n", l);
}
return 0;
} |
software-foundations/learning-c | 01_basics/03_arithmetic.c | <reponame>software-foundations/learning-c
#include <stdio.h>
#include <stdlib.h>
int main(void) {
float a;
float b;
float c;
float d;
float result;
a = 1;
b = 2;
c = 3;
d = 4;
result = a + b + c + d;
printf("1: %f\n", result);
result = a - b - c - d;
printf("2: %f\n", result);
result = a * b + c;
printf("3: %f\n", result);
result = a * b + c / d;
printf("4: %f\n", result);
result = (a * b) + (c / d);
printf("5: %f\n", result);
return 0;
}
|
software-foundations/learning-c | 01_basics/06_equality_operators.c | #include <stdio.h>
#include <stdlib.h>
int main(void) {
// 1 if true
// 0 if false
printf("%d\n", 1 == 2);
printf("%d\n", 1 == 1);
printf("%d\n", 1 != 2);
printf("%d\n", 1 != 1);
return 0;
} |
software-foundations/learning-c | 01_basics/10_increment_decrement_operators.c | <gh_stars>0
#include <stdio.h>
#include <stdlib.h>
int main(void) {
int var = 0;
// pos increment
var++;
var--;
// pre increment
--var;
++var;
printf("var %d", var);
return 0;
} |
software-foundations/learning-c | 01_basics/08_types.c | #include <stdio.h>
#include <stdlib.h>
int main(void) {
int var_int = 0;
double var_double = 4.2;
long double var_long_double = 4.476;
float var_float = .846;
char var_char_3[3] = "one";
char var_char_4[4] = "zero";
unsigned long int var_unsigned_long_int = 12345678912345678;
long int var_long_int = -12345678912345678;
unsigned int var_unsigned_int = 123456789;
short var_short = -400;
short var_unsigned_short = 400;
printf("1-> %d\n", var_int);
printf("2-> %f\n", var_float);
printf("3-> %.2f\n", var_float);
printf("4-> %f\n", var_double);
printf("5-> %s\n", var_char_3);
printf("6-> %s\n", var_char_4);
printf("7-> %f\n", var_float);
printf("8-> %.3f\n", var_float);
printf("9-> %.2lf\n", var_float);
printf("10-> %5s\n", "hello");
printf("11-> %15.4f\n", 123456789123456.1234);
printf("12-> %Lf\n", var_long_double);
printf("13-> %1.2Lf\n", var_long_double);
printf("14-> %lu\n", var_unsigned_long_int);
printf("15-> %ld\n", var_long_int);
printf("16-> %u\n", var_unsigned_int);
printf("17-> %hd\n", var_short);
printf("17-> %hu\n", var_unsigned_short);
return 0;
} |
agegold/openpilot-7 | selfdrive/camerad/cameras/sensor2_i2c.h | <filename>selfdrive/camerad/cameras/sensor2_i2c.h
struct i2c_random_wr_payload start_reg_array_ar0231[] = {{0x301A, 0x91C}};
struct i2c_random_wr_payload stop_reg_array_ar0231[] = {{0x301A, 0x918}};
struct i2c_random_wr_payload start_reg_array_imx390[] = {{0x0, 0}};
struct i2c_random_wr_payload stop_reg_array_imx390[] = {{0x0, 1}};
struct i2c_random_wr_payload init_array_imx390[] = {
{0x2008, 0xd0}, {0x2009, 0x07}, {0x200a, 0x00}, // MODE_VMAX = time between frames
{0x200C, 0xe4}, {0x200D, 0x0c}, // MODE_HMAX
// crop
{0x3410, 0x88}, {0x3411, 0x7}, // CROP_H_SIZE
{0x3418, 0xb8}, {0x3419, 0x4}, // CROP_V_SIZE
{0x0078, 1}, {0x03c0, 1},
// external trigger (off)
// while images still come in, they are blank with this
{0x3650, 0}, // CU_MODE
// exposure
{0x000c, 0xc0}, {0x000d, 0x07},
{0x0010, 0xc0}, {0x0011, 0x07},
// WUXGA mode
// not in datasheet, from https://github.com/bogsen/STLinux-Kernel/blob/master/drivers/media/platform/tegra/imx185.c
{0x0086, 0xc4}, {0x0087, 0xff}, // WND_SHIFT_V = -60
{0x03c6, 0xc4}, {0x03c7, 0xff}, // SM_WND_SHIFT_V_APL = -60
{0x201c, 0xe1}, {0x201d, 0x12}, // image read amount
{0x21ee, 0xc4}, {0x21ef, 0x04}, // image send amount (1220 is the end)
{0x21f0, 0xc4}, {0x21f1, 0x04}, // image processing amount
// disable a bunch of errors causing blanking
{0x0390, 0x00}, {0x0391, 0x00}, {0x0392, 0x00},
// flip bayer
{0x2D64, 0x64 + 2},
// color correction
{0x0030, 0xf8}, {0x0031, 0x00}, // red gain
{0x0032, 0x9a}, {0x0033, 0x00}, // gr gain
{0x0034, 0x9a}, {0x0035, 0x00}, // gb gain
{0x0036, 0x22}, {0x0037, 0x01}, // blue gain
// hdr enable (noise with this on for now)
{0x00f9, 0}
};
struct i2c_random_wr_payload init_array_ar0231[] = {
{0x301A, 0x0018}, // RESET_REGISTER
// CLOCK Settings
{0x302A, 0x0006}, // VT_PIX_CLK_DIV
{0x302C, 0x0001}, // VT_SYS_CLK_DIV
{0x302E, 0x0002}, // PRE_PLL_CLK_DIV
{0x3030, 0x0032}, // PLL_MULTIPLIER
{0x3036, 0x000C}, // OP_WORD_CLK_DIV
{0x3038, 0x0001}, // OP_SYS_CLK_DIV
// FORMAT
{0x3040, 0xC000}, // READ_MODE
{0x3004, 0x0000}, // X_ADDR_START_ (A)
{0x308A, 0x0000}, // X_ADDR_START_ (B)
{0x3008, 0x0787}, // X_ADDR_END_ (A)
{0x308E, 0x0787}, // X_ADDR_END_ (B)
{0x3002, 0x0000}, // Y_ADDR_START_ (A)
{0x308C, 0x0000}, // Y_ADDR_START_ (B)
{0x3006, 0x04B7}, // Y_ADDR_END_ (A)
{0x3090, 0x04B7}, // Y_ADDR_END_ (B)
{0x3032, 0x0000}, // SCALING_MODE
{0x30A2, 0x0001}, // X_ODD_INC_ (A)
{0x30AE, 0x0001}, // X_ODD_INC_ (B)
{0x30A6, 0x0001}, // Y_ODD_INC_ (A)
{0x30A8, 0x0001}, // Y_ODD_INC_ (B)
{0x3402, 0x0F10}, // X_OUTPUT_CONTROL
{0x3404, 0x0970}, // Y_OUTPUT_CONTROL
{0x3064, 0x1802}, // SMIA_TEST
{0x30BA, 0x11F2}, // DIGITAL_CTRL
// SLAV* MODE
{0x30CE, 0x0120},
{0x340A, 0xE6}, // E6 // 0000 1110 0110
{0x340C, 0x802}, // 2 // 0000 0000 0010
// Readout timing
{0x300C, 0x07B9}, // LINE_LENGTH_PCK (A)
{0x303E, 0x07B9}, // LINE_LENGTH_PCK (B)
{0x300A, 0x07E7}, // FRAME_LENGTH_LINES (A)
{0x30AA, 0x07E7}, // FRAME_LENGTH_LINES (B)
{0x3042, 0x0000}, // EXTRA_DELAY
// Readout Settings
{0x31AE, 0x0204}, // SERIAL_FORMAT, 4-lane MIPI
{0x31AC, 0x0C0C}, // DATA_FORMAT_BITS, 12 -> 12
{0x3342, 0x122C}, // MIPI_F1_PDT_EDT
{0x3346, 0x122C}, // MIPI_F2_PDT_EDT
{0x334A, 0x122C}, // MIPI_F3_PDT_EDT
{0x334E, 0x122C}, // MIPI_F4_PDT_EDT
{0x3344, 0x0011}, // MIPI_F1_VDT_VC
{0x3348, 0x0111}, // MIPI_F2_VDT_VC
{0x334C, 0x0211}, // MIPI_F3_VDT_VC
{0x3350, 0x0311}, // MIPI_F4_VDT_VC
{0x31B0, 0x0053}, // FRAME_PREAMBLE
{0x31B2, 0x003B}, // LINE_PREAMBLE
{0x301A, 0x001C}, // RESET_REGISTER
// Noise Corrections
{0x3092, 0x0C24}, // ROW_NOISE_CONTROL
{0x337A, 0x0C80}, // DBLC_SCALE0
{0x3370, 0x03B1}, // DBLC
{0x3044, 0x0400}, // DARK_CONTROL
// Enable dead pixel correction using
// the 1D line correction scheme
{0x31E0, 0x0003},
// HDR Settings
{0x3082, 0x0004}, // OPERATION_MODE_CTRL (A)
{0x3084, 0x0004}, // OPERATION_MODE_CTRL (B)
{0x3238, 0x0004}, // EXPOSURE_RATIO (A)
{0x323A, 0x0004}, // EXPOSURE_RATIO (B)
{0x3014, 0x098E}, // FINE_INTEGRATION_TIME_ (A)
{0x3018, 0x098E}, // FINE_INTEGRATION_TIME_ (B)
{0x321E, 0x098E}, // FINE_INTEGRATION_TIME2 (A)
{0x3220, 0x098E}, // FINE_INTEGRATION_TIME2 (B)
{0x31D0, 0x0000}, // COMPANDING, no good in 10 bit?
{0x33DA, 0x0000}, // COMPANDING
{0x318E, 0x0200}, // PRE_HDR_GAIN_EN
// DLO Settings
{0x3100, 0x4000}, // DLO_CONTROL0
{0x3280, 0x0CCC}, // T1 G1
{0x3282, 0x0CCC}, // T1 R
{0x3284, 0x0CCC}, // T1 B
{0x3286, 0x0CCC}, // T1 G2
{0x3288, 0x0FA0}, // T2 G1
{0x328A, 0x0FA0}, // T2 R
{0x328C, 0x0FA0}, // T2 B
{0x328E, 0x0FA0}, // T2 G2
// Initial Gains
{0x3022, 0x0001}, // GROUPED_PARAMETER_HOLD_
{0x3366, 0xFF77}, // ANALOG_GAIN (1x) (A)
{0x3368, 0xFF77}, // ANALOG_GAIN (1x) (B)
{0x3060, 0x3333}, // ANALOG_COLOR_GAIN
{0x3362, 0x0000}, // DC GAIN (A & B)
{0x305A, 0x00F8}, // red gain (A)
{0x3058, 0x0122}, // blue gain (A)
{0x3056, 0x009A}, // g1 gain (A)
{0x305C, 0x009A}, // g2 gain (A)
{0x30C0, 0x00F8}, // red gain (B)
{0x30BE, 0x0122}, // blue gain (B)
{0x30BC, 0x009A}, // g1 gain (B)
{0x30C2, 0x009A}, // g2 gain (B)
{0x3022, 0x0000}, // GROUPED_PARAMETER_HOLD_
// Initial Integration Time
{0x3012, 0x0005}, // (A)
{0x3016, 0x0005}, // (B)
}; |
agegold/openpilot-7 | selfdrive/camerad/cameras/camera_qcom2.h | #pragma once
#include <cstdint>
#include <media/cam_req_mgr.h>
#include "selfdrive/camerad/cameras/camera_common.h"
#include "selfdrive/common/util.h"
#define FRAME_BUF_COUNT 4
class CameraState {
public:
MultiCameraState *multi_cam_state;
CameraInfo ci;
std::mutex exp_lock;
int exposure_time;
bool dc_gain_enabled;
float analog_gain_frac;
float cur_ev[3];
float min_ev, max_ev;
float measured_grey_fraction;
float target_grey_fraction;
int gain_idx;
unique_fd sensor_fd;
unique_fd csiphy_fd;
int camera_num;
void config_isp(int io_mem_handle, int fence, int request_id, int buf0_mem_handle, int buf0_offset);
void enqueue_req_multi(int start, int n, bool dp);
void enqueue_buffer(int i, bool dp);
void handle_camera_event(void *evdat);
void set_camera_exposure(float grey_frac);
void sensors_start();
void sensors_poke(int request_id);
void sensors_i2c(struct i2c_random_wr_payload* dat, int len, int op_code, bool data_word);
int sensors_init();
void camera_open();
void camera_init(MultiCameraState *multi_cam_state, VisionIpcServer * v, int camera_id, int camera_num, unsigned int fps, cl_device_id device_id, cl_context ctx, VisionStreamType rgb_type, VisionStreamType yuv_type);
void camera_close();
int32_t session_handle;
int32_t sensor_dev_handle;
int32_t isp_dev_handle;
int32_t csiphy_dev_handle;
int32_t link_handle;
int buf0_handle;
int buf_handle[FRAME_BUF_COUNT];
int sync_objs[FRAME_BUF_COUNT];
int request_ids[FRAME_BUF_COUNT];
int request_id_last;
int frame_id_last;
int idx_offset;
bool skipped;
int camera_id;
CameraBuf buf;
};
typedef struct MultiCameraState {
unique_fd video0_fd;
unique_fd video1_fd;
unique_fd isp_fd;
int device_iommu;
int cdm_iommu;
CameraState road_cam;
CameraState wide_road_cam;
CameraState driver_cam;
SubMaster *sm;
PubMaster *pm;
} MultiCameraState; |
chrispla/propacc | realtime/ddsp_tilde/signal_in_out_base.c | <reponame>chrispla/propacc<filename>realtime/ddsp_tilde/signal_in_out_base.c
#include "m_pd.h"
static t_class *pan_tilde_class;
typedef struct _pan_tilde
{
t_object x_obj;
t_sample f_pan;
t_sample f;
t_inlet *x_in2;
t_inlet *x_in3;
t_outlet *x_out;
} t_pan_tilde;
t_int *pan_tilde_perform(t_int *w)
{
t_pan_tilde *x = (t_pan_tilde *)(w[1]);
t_sample *in1 = (t_sample *)(w[2]);
t_sample *in2 = (t_sample *)(w[3]);
t_sample *out = (t_sample *)(w[4]);
int n = (int)(w[5]);
t_sample f_pan = (x->f_pan < 0) ? 0.0 : (x->f_pan > 1) ? 1.0 : x->f_pan;
while (n--)
*out++ = (*in1++) * (1 - f_pan) + (*in2++) * f_pan;
return (w + 6);
}
void pan_tilde_dsp(t_pan_tilde *x, t_signal **sp)
{
dsp_add(pan_tilde_perform, 5, x,
sp[0]->s_vec, sp[1]->s_vec, sp[2]->s_vec, sp[0]->s_n);
}
void pan_tilde_free(t_pan_tilde *x)
{
inlet_free(x->x_in2);
inlet_free(x->x_in3);
outlet_free(x->x_out);
}
void *pan_tilde_new(t_floatarg f)
{
t_pan_tilde *x = (t_pan_tilde *)pd_new(pan_tilde_class);
x->f_pan = f;
x->x_in2 = inlet_new(&x->x_obj, &x->x_obj.ob_pd, &s_signal, &s_signal);
x->x_in3 = floatinlet_new(&x->x_obj, &x->f_pan);
x->x_out = outlet_new(&x->x_obj, &s_signal);
return (void *)x;
}
void pan_tilde_setup(void)
{
pan_tilde_class = class_new(gensym("pan~"),
(t_newmethod)pan_tilde_new,
0, sizeof(t_pan_tilde),
CLASS_DEFAULT,
A_DEFFLOAT, 0);
class_addmethod(pan_tilde_class,
(t_method)pan_tilde_dsp, gensym("dsp"), A_CANT, 0);
CLASS_MAINSIGNALIN(pan_tilde_class, t_pan_tilde, f);
}
|
chrispla/propacc | realtime/ddsp_tilde/ddsp_model.h | #pragma once
#include <torch/script.h>
#include <torch/torch.h>
#include <string>
#define DEVICE torch::kCPU
#define CPU torch::kCPU
class DDSPModel
{
private:
torch::jit::script::Module m_scripted_model;
int m_loaded;
public:
DDSPModel();
int load(std::string path);
void perform(float *pitch, float *loudness, float *out_buffer, int buffer_size);
}; |
chrispla/propacc | realtime/ddsp_tilde/m_pd.h | /* Copyright (c) 1997-1999 <NAME>.
* For information on usage and redistribution, and for a DISCLAIMER OF ALL
* WARRANTIES, see the file, "LICENSE.txt," in this distribution. */
#ifndef __m_pd_h_
#if defined(_LANGUAGE_C_PLUS_PLUS) || defined(__cplusplus)
extern "C" {
#endif
#define PD_MAJOR_VERSION 0
#define PD_MINOR_VERSION 51
#define PD_BUGFIX_VERSION 4
#define PD_TEST_VERSION ""
extern int pd_compatibilitylevel; /* e.g., 43 for pd 0.43 compatibility */
/* old name for "MSW" flag -- we have to take it for the sake of many old
"nmakefiles" for externs, which will define NT and not MSW */
#if defined(NT) && !defined(MSW)
#define MSW
#endif
/* These pragmas are only used for MSVC, not MinGW or Cygwin <<EMAIL>> */
#ifdef _MSC_VER
/* #pragma warning( disable : 4091 ) */
#pragma warning( disable : 4305 ) /* uncast const double to float */
#pragma warning( disable : 4244 ) /* uncast float/int conversion etc. */
#pragma warning( disable : 4101 ) /* unused automatic variables */
#endif /* _MSC_VER */
/* the external storage class is "extern" in UNIX; in MSW it's ugly. */
#ifdef _WIN32
#ifdef PD_INTERNAL
#define EXTERN __declspec(dllexport) extern
#else
#define EXTERN __declspec(dllimport) extern
#endif /* PD_INTERNAL */
#else
#define EXTERN extern
#endif /* _WIN32 */
/* On most c compilers, you can just say "struct foo;" to declare a
structure whose elements are defined elsewhere. On MSVC, when compiling
C (but not C++) code, you have to say "extern struct foo;". So we make
a stupid macro: */
#if defined(_MSC_VER) && !defined(_LANGUAGE_C_PLUS_PLUS) \
&& !defined(__cplusplus)
#define EXTERN_STRUCT extern struct
#else
#define EXTERN_STRUCT struct
#endif
/* Define some attributes, specific to the compiler */
#if defined(__GNUC__)
#define ATTRIBUTE_FORMAT_PRINTF(a, b) __attribute__ ((format (printf, a, b)))
#else
#define ATTRIBUTE_FORMAT_PRINTF(a, b)
#endif
#if !defined(_SIZE_T) && !defined(_SIZE_T_)
#include <stddef.h> /* just for size_t -- how lame! */
#endif
/* Microsoft Visual Studio is not C99, but since VS2015 has included most C99 headers:
https://docs.microsoft.com/en-us/previous-versions/hh409293(v=vs.140)#c-runtime-library
These definitions recreate stdint.h types, but only in pre-2015 Visual Studio: */
#if defined(_MSC_VER) && _MSC_VER < 1900
typedef signed __int8 int8_t;
typedef signed __int16 int16_t;
typedef signed __int32 int32_t;
typedef signed __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#else
# include <stdint.h>
#endif
/* for FILE, needed by sys_fopen() and sys_fclose() only */
#include <stdio.h>
#define MAXPDSTRING 1000 /* use this for anything you want */
#define MAXPDARG 5 /* max number of args we can typecheck today */
/* signed and unsigned integer types the size of a pointer: */
#if !defined(PD_LONGINTTYPE)
#if defined(_WIN32) && defined(_WIN64)
#define PD_LONGINTTYPE long long
#else
#define PD_LONGINTTYPE long
#endif
#endif
#if !defined(PD_FLOATSIZE)
/* normally, our floats (t_float, t_sample,...) are 32bit */
# define PD_FLOATSIZE 32
#endif
#if PD_FLOATSIZE == 32
# define PD_FLOATTYPE float
/* an unsigned int of the same size as FLOATTYPE: */
# define PD_FLOATUINTTYPE uint32_t
#elif PD_FLOATSIZE == 64
# define PD_FLOATTYPE double
# define PD_FLOATUINTTYPE uint64_t
#else
# error invalid FLOATSIZE: must be 32 or 64
#endif
typedef PD_LONGINTTYPE t_int; /* pointer-size integer */
typedef PD_FLOATTYPE t_float; /* a float type at most the same size */
typedef PD_FLOATTYPE t_floatarg; /* float type for function calls */
typedef struct _symbol
{
const char *s_name;
struct _class **s_thing;
struct _symbol *s_next;
} t_symbol;
EXTERN_STRUCT _array;
#define t_array struct _array /* g_canvas.h */
/* pointers to glist and array elements go through a "stub" which sticks
around after the glist or array is freed. The stub itself is deleted when
both the glist/array is gone and the refcount is zero, ensuring that no
gpointers are pointing here. */
#define GP_NONE 0 /* the stub points nowhere (has been cut off) */
#define GP_GLIST 1 /* the stub points to a glist element */
#define GP_ARRAY 2 /* ... or array */
typedef struct _gstub
{
union
{
struct _glist *gs_glist; /* glist we're in */
struct _array *gs_array; /* array we're in */
} gs_un;
int gs_which; /* GP_GLIST/GP_ARRAY */
int gs_refcount; /* number of gpointers pointing here */
} t_gstub;
typedef struct _gpointer /* pointer to a gobj in a glist */
{
union
{
struct _scalar *gp_scalar; /* scalar we're in (if glist) */
union word *gp_w; /* raw data (if array) */
} gp_un;
int gp_valid; /* number which must match gpointee */
t_gstub *gp_stub; /* stub which points to glist/array */
} t_gpointer;
typedef union word
{
t_float w_float;
t_symbol *w_symbol;
t_gpointer *w_gpointer;
t_array *w_array;
struct _binbuf *w_binbuf;
int w_index;
} t_word;
typedef enum
{
A_NULL,
A_FLOAT,
A_SYMBOL,
A_POINTER,
A_SEMI,
A_COMMA,
A_DEFFLOAT,
A_DEFSYM,
A_DOLLAR,
A_DOLLSYM,
A_GIMME,
A_CANT
} t_atomtype;
#define A_DEFSYMBOL A_DEFSYM /* better name for this */
typedef struct _atom
{
t_atomtype a_type;
union word a_w;
} t_atom;
EXTERN_STRUCT _class;
#define t_class struct _class
EXTERN_STRUCT _outlet;
#define t_outlet struct _outlet
EXTERN_STRUCT _inlet;
#define t_inlet struct _inlet
EXTERN_STRUCT _binbuf;
#define t_binbuf struct _binbuf
EXTERN_STRUCT _clock;
#define t_clock struct _clock
EXTERN_STRUCT _outconnect;
#define t_outconnect struct _outconnect
EXTERN_STRUCT _glist;
#define t_glist struct _glist
#define t_canvas struct _glist /* LATER lose this */
EXTERN_STRUCT _template;
typedef t_class *t_pd; /* pure datum: nothing but a class pointer */
typedef struct _gobj /* a graphical object */
{
t_pd g_pd; /* pure datum header (class) */
struct _gobj *g_next; /* next in list */
} t_gobj;
typedef struct _scalar /* a graphical object holding data */
{
t_gobj sc_gobj; /* header for graphical object */
t_symbol *sc_template; /* template name (LATER replace with pointer) */
t_word sc_vec[1]; /* indeterminate-length array of words */
} t_scalar;
typedef struct _text /* patchable object - graphical, with text */
{
t_gobj te_g; /* header for graphical object */
t_binbuf *te_binbuf; /* holder for the text */
t_outlet *te_outlet; /* linked list of outlets */
t_inlet *te_inlet; /* linked list of inlets */
short te_xpix; /* x&y location (within the toplevel) */
short te_ypix;
short te_width; /* requested width in chars, 0 if auto */
unsigned int te_type:2; /* from defs below */
} t_text;
#define T_TEXT 0 /* just a textual comment */
#define T_OBJECT 1 /* a MAX style patchable object */
#define T_MESSAGE 2 /* a MAX type message */
#define T_ATOM 3 /* a cell to display a number or symbol */
#define te_pd te_g.g_pd
/* t_object is synonym for t_text (LATER unify them) */
typedef struct _text t_object;
#define ob_outlet te_outlet
#define ob_inlet te_inlet
#define ob_binbuf te_binbuf
#define ob_pd te_g.g_pd
#define ob_g te_g
typedef void (*t_method)(void);
typedef void *(*t_newmethod)(void);
/* in ARM 64 a varargs prototype generates a different function call sequence
from a fixed one, so in that special case we make a more restrictive
definition for t_gotfn. This will break some code in the "chaos" package
in Pd extended. (that code will run incorrectly anyhow so why not catch it
at compile time anyhow.) */
#if defined(__APPLE__) && defined(__aarch64__)
typedef void (*t_gotfn)(void *x);
#else
typedef void (*t_gotfn)(void *x, ...);
#endif
/* ---------------- pre-defined objects and symbols --------------*/
EXTERN t_pd pd_objectmaker; /* factory for creating "object" boxes */
EXTERN t_pd pd_canvasmaker; /* factory for creating canvases */
/* --------- prototypes from the central message system ----------- */
EXTERN void pd_typedmess(t_pd *x, t_symbol *s, int argc, t_atom *argv);
EXTERN void pd_forwardmess(t_pd *x, int argc, t_atom *argv);
EXTERN t_symbol *gensym(const char *s);
EXTERN t_gotfn getfn(const t_pd *x, t_symbol *s);
EXTERN t_gotfn zgetfn(const t_pd *x, t_symbol *s);
EXTERN void nullfn(void);
EXTERN void pd_vmess(t_pd *x, t_symbol *s, const char *fmt, ...);
/* the following macros are for sending non-type-checkable messages, i.e.,
using function lookup but circumventing type checking on arguments. Only
use for internal messaging protected by A_CANT so that the message can't
be generated at patch level. */
#define mess0(x, s) ((*getfn((x), (s)))((x)))
typedef void (*t_gotfn1)(void *x, void *arg1);
#define mess1(x, s, a) ((*(t_gotfn1)getfn((x), (s)))((x), (a)))
typedef void (*t_gotfn2)(void *x, void *arg1, void *arg2);
#define mess2(x, s, a,b) ((*(t_gotfn2)getfn((x), (s)))((x), (a),(b)))
typedef void (*t_gotfn3)(void *x, void *arg1, void *arg2, void *arg3);
#define mess3(x, s, a,b,c) ((*(t_gotfn3)getfn((x), (s)))((x), (a),(b),(c)))
typedef void (*t_gotfn4)(void *x,
void *arg1, void *arg2, void *arg3, void *arg4);
#define mess4(x, s, a,b,c,d) \
((*(t_gotfn4)getfn((x), (s)))((x), (a),(b),(c),(d)))
typedef void (*t_gotfn5)(void *x,
void *arg1, void *arg2, void *arg3, void *arg4, void *arg5);
#define mess5(x, s, a,b,c,d,e) \
((*(t_gotfn5)getfn((x), (s)))((x), (a),(b),(c),(d),(e)))
EXTERN void obj_list(t_object *x, t_symbol *s, int argc, t_atom *argv);
EXTERN t_pd *pd_newest(void);
/* --------------- memory management -------------------- */
EXTERN void *getbytes(size_t nbytes);
EXTERN void *getzbytes(size_t nbytes);
EXTERN void *copybytes(const void *src, size_t nbytes);
EXTERN void freebytes(void *x, size_t nbytes);
EXTERN void *resizebytes(void *x, size_t oldsize, size_t newsize);
/* -------------------- atoms ----------------------------- */
#define SETSEMI(atom) ((atom)->a_type = A_SEMI, (atom)->a_w.w_index = 0)
#define SETCOMMA(atom) ((atom)->a_type = A_COMMA, (atom)->a_w.w_index = 0)
#define SETPOINTER(atom, gp) ((atom)->a_type = A_POINTER, \
(atom)->a_w.w_gpointer = (gp))
#define SETFLOAT(atom, f) ((atom)->a_type = A_FLOAT, (atom)->a_w.w_float = (f))
#define SETSYMBOL(atom, s) ((atom)->a_type = A_SYMBOL, \
(atom)->a_w.w_symbol = (s))
#define SETDOLLAR(atom, n) ((atom)->a_type = A_DOLLAR, \
(atom)->a_w.w_index = (n))
#define SETDOLLSYM(atom, s) ((atom)->a_type = A_DOLLSYM, \
(atom)->a_w.w_symbol= (s))
EXTERN t_float atom_getfloat(const t_atom *a);
EXTERN t_int atom_getint(const t_atom *a);
EXTERN t_symbol *atom_getsymbol(const t_atom *a);
EXTERN t_symbol *atom_gensym(const t_atom *a);
EXTERN t_float atom_getfloatarg(int which, int argc, const t_atom *argv);
EXTERN t_int atom_getintarg(int which, int argc, const t_atom *argv);
EXTERN t_symbol *atom_getsymbolarg(int which, int argc, const t_atom *argv);
EXTERN void atom_string(const t_atom *a, char *buf, unsigned int bufsize);
/* ------------------ binbufs --------------- */
EXTERN t_binbuf *binbuf_new(void);
EXTERN void binbuf_free(t_binbuf *x);
EXTERN t_binbuf *binbuf_duplicate(const t_binbuf *y);
EXTERN void binbuf_text(t_binbuf *x, const char *text, size_t size);
EXTERN void binbuf_gettext(const t_binbuf *x, char **bufp, int *lengthp);
EXTERN void binbuf_clear(t_binbuf *x);
EXTERN void binbuf_add(t_binbuf *x, int argc, const t_atom *argv);
EXTERN void binbuf_addv(t_binbuf *x, const char *fmt, ...);
EXTERN void binbuf_addbinbuf(t_binbuf *x, const t_binbuf *y);
EXTERN void binbuf_addsemi(t_binbuf *x);
EXTERN void binbuf_restore(t_binbuf *x, int argc, const t_atom *argv);
EXTERN void binbuf_print(const t_binbuf *x);
EXTERN int binbuf_getnatom(const t_binbuf *x);
EXTERN t_atom *binbuf_getvec(const t_binbuf *x);
EXTERN int binbuf_resize(t_binbuf *x, int newsize);
EXTERN void binbuf_eval(const t_binbuf *x, t_pd *target, int argc, const t_atom *argv);
EXTERN int binbuf_read(t_binbuf *b, const char *filename, const char *dirname,
int crflag);
EXTERN int binbuf_read_via_canvas(t_binbuf *b, const char *filename, const t_canvas *canvas,
int crflag);
EXTERN int binbuf_read_via_path(t_binbuf *b, const char *filename, const char *dirname,
int crflag);
EXTERN int binbuf_write(const t_binbuf *x, const char *filename, const char *dir,
int crflag);
EXTERN void binbuf_evalfile(t_symbol *name, t_symbol *dir);
EXTERN t_symbol *binbuf_realizedollsym(t_symbol *s, int ac, const t_atom *av,
int tonew);
/* ------------------ clocks --------------- */
EXTERN t_clock *clock_new(void *owner, t_method fn);
EXTERN void clock_set(t_clock *x, double systime);
EXTERN void clock_delay(t_clock *x, double delaytime);
EXTERN void clock_unset(t_clock *x);
EXTERN void clock_setunit(t_clock *x, double timeunit, int sampflag);
EXTERN double clock_getlogicaltime(void);
EXTERN double clock_getsystime(void); /* OBSOLETE; use clock_getlogicaltime() */
EXTERN double clock_gettimesince(double prevsystime);
EXTERN double clock_gettimesincewithunits(double prevsystime,
double units, int sampflag);
EXTERN double clock_getsystimeafter(double delaytime);
EXTERN void clock_free(t_clock *x);
/* ----------------- pure data ---------------- */
EXTERN t_pd *pd_new(t_class *cls);
EXTERN void pd_free(t_pd *x);
EXTERN void pd_bind(t_pd *x, t_symbol *s);
EXTERN void pd_unbind(t_pd *x, t_symbol *s);
EXTERN t_pd *pd_findbyclass(t_symbol *s, const t_class *c);
EXTERN void pd_pushsym(t_pd *x);
EXTERN void pd_popsym(t_pd *x);
EXTERN void pd_bang(t_pd *x);
EXTERN void pd_pointer(t_pd *x, t_gpointer *gp);
EXTERN void pd_float(t_pd *x, t_float f);
EXTERN void pd_symbol(t_pd *x, t_symbol *s);
EXTERN void pd_list(t_pd *x, t_symbol *s, int argc, t_atom *argv);
EXTERN void pd_anything(t_pd *x, t_symbol *s, int argc, t_atom *argv);
#define pd_class(x) (*(x))
/* ----------------- pointers ---------------- */
EXTERN void gpointer_init(t_gpointer *gp);
EXTERN void gpointer_copy(const t_gpointer *gpfrom, t_gpointer *gpto);
EXTERN void gpointer_unset(t_gpointer *gp);
EXTERN int gpointer_check(const t_gpointer *gp, int headok);
/* ----------------- patchable "objects" -------------- */
EXTERN t_inlet *inlet_new(t_object *owner, t_pd *dest, t_symbol *s1,
t_symbol *s2);
EXTERN t_inlet *pointerinlet_new(t_object *owner, t_gpointer *gp);
EXTERN t_inlet *floatinlet_new(t_object *owner, t_float *fp);
EXTERN t_inlet *symbolinlet_new(t_object *owner, t_symbol **sp);
EXTERN t_inlet *signalinlet_new(t_object *owner, t_float f);
EXTERN void inlet_free(t_inlet *x);
EXTERN t_outlet *outlet_new(t_object *owner, t_symbol *s);
EXTERN void outlet_bang(t_outlet *x);
EXTERN void outlet_pointer(t_outlet *x, t_gpointer *gp);
EXTERN void outlet_float(t_outlet *x, t_float f);
EXTERN void outlet_symbol(t_outlet *x, t_symbol *s);
EXTERN void outlet_list(t_outlet *x, t_symbol *s, int argc, t_atom *argv);
EXTERN void outlet_anything(t_outlet *x, t_symbol *s, int argc, t_atom *argv);
EXTERN t_symbol *outlet_getsymbol(t_outlet *x);
EXTERN void outlet_free(t_outlet *x);
EXTERN t_object *pd_checkobject(t_pd *x);
/* -------------------- canvases -------------- */
EXTERN void glob_setfilename(void *dummy, t_symbol *name, t_symbol *dir);
EXTERN void canvas_setargs(int argc, const t_atom *argv);
EXTERN void canvas_getargs(int *argcp, t_atom **argvp);
EXTERN t_symbol *canvas_getcurrentdir(void);
EXTERN t_glist *canvas_getcurrent(void);
EXTERN void canvas_makefilename(const t_glist *c, const char *file,
char *result, int resultsize);
EXTERN t_symbol *canvas_getdir(const t_glist *x);
EXTERN char sys_font[]; /* default typeface set in s_main.c */
EXTERN char sys_fontweight[]; /* default font weight set in s_main.c */
EXTERN int sys_hostfontsize(int fontsize, int zoom);
EXTERN int sys_zoomfontwidth(int fontsize, int zoom, int worstcase);
EXTERN int sys_zoomfontheight(int fontsize, int zoom, int worstcase);
EXTERN int sys_fontwidth(int fontsize);
EXTERN int sys_fontheight(int fontsize);
EXTERN void canvas_dataproperties(t_glist *x, t_scalar *sc, t_binbuf *b);
EXTERN int canvas_open(const t_canvas *x, const char *name, const char *ext,
char *dirresult, char **nameresult, unsigned int size, int bin);
/* ---------------- widget behaviors ---------------------- */
EXTERN_STRUCT _widgetbehavior;
#define t_widgetbehavior struct _widgetbehavior
EXTERN_STRUCT _parentwidgetbehavior;
#define t_parentwidgetbehavior struct _parentwidgetbehavior
EXTERN const t_parentwidgetbehavior *pd_getparentwidget(t_pd *x);
/* -------------------- classes -------------- */
#define CLASS_DEFAULT 0 /* flags for new classes below */
#define CLASS_PD 1
#define CLASS_GOBJ 2
#define CLASS_PATCHABLE 3
#define CLASS_NOINLET 8
#define CLASS_TYPEMASK 3
EXTERN t_class *class_new(t_symbol *name, t_newmethod newmethod,
t_method freemethod, size_t size, int flags, t_atomtype arg1, ...);
EXTERN t_class *class_new64(t_symbol *name, t_newmethod newmethod,
t_method freemethod, size_t size, int flags, t_atomtype arg1, ...);
EXTERN void class_free(t_class *c);
#ifdef PDINSTANCE
EXTERN t_class *class_getfirst(void);
#endif
EXTERN void class_addcreator(t_newmethod newmethod, t_symbol *s,
t_atomtype type1, ...);
EXTERN void class_addmethod(t_class *c, t_method fn, t_symbol *sel,
t_atomtype arg1, ...);
EXTERN void class_addbang(t_class *c, t_method fn);
EXTERN void class_addpointer(t_class *c, t_method fn);
EXTERN void class_doaddfloat(t_class *c, t_method fn);
EXTERN void class_addsymbol(t_class *c, t_method fn);
EXTERN void class_addlist(t_class *c, t_method fn);
EXTERN void class_addanything(t_class *c, t_method fn);
EXTERN void class_sethelpsymbol(t_class *c, t_symbol *s);
EXTERN void class_setwidget(t_class *c, const t_widgetbehavior *w);
EXTERN void class_setparentwidget(t_class *c, const t_parentwidgetbehavior *w);
EXTERN const char *class_getname(const t_class *c);
EXTERN const char *class_gethelpname(const t_class *c);
EXTERN const char *class_gethelpdir(const t_class *c);
EXTERN void class_setdrawcommand(t_class *c);
EXTERN int class_isdrawcommand(const t_class *c);
EXTERN void class_domainsignalin(t_class *c, int onset);
EXTERN void class_set_extern_dir(t_symbol *s);
#define CLASS_MAINSIGNALIN(c, type, field) \
class_domainsignalin(c, (char *)(&((type *)0)->field) - (char *)0)
/* prototype for functions to save Pd's to a binbuf */
typedef void (*t_savefn)(t_gobj *x, t_binbuf *b);
EXTERN void class_setsavefn(t_class *c, t_savefn f);
EXTERN t_savefn class_getsavefn(const t_class *c);
EXTERN void obj_saveformat(const t_object *x, t_binbuf *bb); /* add format to bb */
/* prototype for functions to open properties dialogs */
typedef void (*t_propertiesfn)(t_gobj *x, struct _glist *glist);
EXTERN void class_setpropertiesfn(t_class *c, t_propertiesfn f);
EXTERN t_propertiesfn class_getpropertiesfn(const t_class *c);
typedef void (*t_classfreefn)(t_class *);
EXTERN void class_setfreefn(t_class *c, t_classfreefn fn);
#ifndef PD_CLASS_DEF
#define class_addbang(x, y) class_addbang((x), (t_method)(y))
#define class_addpointer(x, y) class_addpointer((x), (t_method)(y))
#define class_addfloat(x, y) class_doaddfloat((x), (t_method)(y))
#define class_addsymbol(x, y) class_addsymbol((x), (t_method)(y))
#define class_addlist(x, y) class_addlist((x), (t_method)(y))
#define class_addanything(x, y) class_addanything((x), (t_method)(y))
#endif
#if PD_FLOATSIZE == 64
# define class_new class_new64
#endif
/* ------------ printing --------------------------------- */
EXTERN void post(const char *fmt, ...);
EXTERN void startpost(const char *fmt, ...);
EXTERN void poststring(const char *s);
EXTERN void postfloat(t_floatarg f);
EXTERN void postatom(int argc, const t_atom *argv);
EXTERN void endpost(void);
EXTERN void error(const char *fmt, ...) ATTRIBUTE_FORMAT_PRINTF(1, 2);
EXTERN void verbose(int level, const char *fmt, ...) ATTRIBUTE_FORMAT_PRINTF(2, 3);
EXTERN void bug(const char *fmt, ...) ATTRIBUTE_FORMAT_PRINTF(1, 2);
EXTERN void pd_error(const void *object, const char *fmt, ...) ATTRIBUTE_FORMAT_PRINTF(2, 3);
EXTERN void logpost(const void *object, const int level, const char *fmt, ...)
ATTRIBUTE_FORMAT_PRINTF(3, 4);
/* ------------ system interface routines ------------------- */
EXTERN int sys_isabsolutepath(const char *dir);
EXTERN void sys_bashfilename(const char *from, char *to);
EXTERN void sys_unbashfilename(const char *from, char *to);
EXTERN int open_via_path(const char *dir, const char *name, const char *ext,
char *dirresult, char **nameresult, unsigned int size, int bin);
EXTERN int sched_geteventno(void);
EXTERN double sys_getrealtime(void);
EXTERN int (*sys_idlehook)(void); /* hook to add idle time computation */
/* Win32's open()/fopen() do not handle UTF-8 filenames so we need
* these internal versions that handle UTF-8 filenames the same across
* all platforms. They are recommended for use in external
* objectclasses as well so they work with Unicode filenames on Windows */
EXTERN int sys_open(const char *path, int oflag, ...);
EXTERN int sys_close(int fd);
EXTERN FILE *sys_fopen(const char *filename, const char *mode);
EXTERN int sys_fclose(FILE *stream);
/* ------------ threading ------------------- */
EXTERN void sys_lock(void);
EXTERN void sys_unlock(void);
EXTERN int sys_trylock(void);
/* --------------- signals ----------------------------------- */
typedef PD_FLOATTYPE t_sample;
typedef union _sampleint_union {
t_sample f;
PD_FLOATUINTTYPE i;
} t_sampleint_union;
#define MAXLOGSIG 32
#define MAXSIGSIZE (1 << MAXLOGSIG)
typedef struct _signal
{
int s_n; /* number of points in the array */
t_sample *s_vec; /* the array */
t_float s_sr; /* sample rate */
int s_refcount; /* number of times used */
int s_isborrowed; /* whether we're going to borrow our array */
struct _signal *s_borrowedfrom; /* signal to borrow it from */
struct _signal *s_nextfree; /* next in freelist */
struct _signal *s_nextused; /* next in used list */
int s_vecsize; /* allocated size of array in points */
} t_signal;
typedef t_int *(*t_perfroutine)(t_int *args);
EXTERN t_int *plus_perform(t_int *args);
EXTERN t_int *zero_perform(t_int *args);
EXTERN t_int *copy_perform(t_int *args);
EXTERN void dsp_add_plus(t_sample *in1, t_sample *in2, t_sample *out, int n);
EXTERN void dsp_add_copy(t_sample *in, t_sample *out, int n);
EXTERN void dsp_add_scalarcopy(t_float *in, t_sample *out, int n);
EXTERN void dsp_add_zero(t_sample *out, int n);
EXTERN int sys_getblksize(void);
EXTERN t_float sys_getsr(void);
EXTERN int sys_get_inchannels(void);
EXTERN int sys_get_outchannels(void);
EXTERN void dsp_add(t_perfroutine f, int n, ...);
EXTERN void dsp_addv(t_perfroutine f, int n, t_int *vec);
EXTERN void pd_fft(t_float *buf, int npoints, int inverse);
EXTERN int ilog2(int n);
EXTERN void mayer_fht(t_sample *fz, int n);
EXTERN void mayer_fft(int n, t_sample *real, t_sample *imag);
EXTERN void mayer_ifft(int n, t_sample *real, t_sample *imag);
EXTERN void mayer_realfft(int n, t_sample *real);
EXTERN void mayer_realifft(int n, t_sample *real);
EXTERN float *cos_table;
#define LOGCOSTABSIZE 9
#define COSTABSIZE (1<<LOGCOSTABSIZE)
EXTERN int canvas_suspend_dsp(void);
EXTERN void canvas_resume_dsp(int oldstate);
EXTERN void canvas_update_dsp(void);
EXTERN int canvas_dspstate;
/* up/downsampling */
typedef struct _resample
{
int method; /* up/downsampling method ID */
int downsample; /* downsampling factor */
int upsample; /* upsampling factor */
t_sample *s_vec; /* here we hold the resampled data */
int s_n;
t_sample *coeffs; /* coefficients for filtering... */
int coefsize;
t_sample *buffer; /* buffer for filtering */
int bufsize;
} t_resample;
EXTERN void resample_init(t_resample *x);
EXTERN void resample_free(t_resample *x);
EXTERN void resample_dsp(t_resample *x, t_sample *in, int insize, t_sample *out, int outsize, int method);
EXTERN void resamplefrom_dsp(t_resample *x, t_sample *in, int insize, int outsize, int method);
EXTERN void resampleto_dsp(t_resample *x, t_sample *out, int insize, int outsize, int method);
/* ----------------------- utility functions for signals -------------- */
EXTERN t_float mtof(t_float);
EXTERN t_float ftom(t_float);
EXTERN t_float rmstodb(t_float);
EXTERN t_float powtodb(t_float);
EXTERN t_float dbtorms(t_float);
EXTERN t_float dbtopow(t_float);
EXTERN t_float q8_sqrt(t_float);
EXTERN t_float q8_rsqrt(t_float);
#ifndef N32
EXTERN t_float qsqrt(t_float); /* old names kept for extern compatibility */
EXTERN t_float qrsqrt(t_float);
#endif
/* --------------------- data --------------------------------- */
/* graphical arrays */
EXTERN_STRUCT _garray;
#define t_garray struct _garray
EXTERN t_class *garray_class;
EXTERN int garray_getfloatarray(t_garray *x, int *size, t_float **vec);
EXTERN int garray_getfloatwords(t_garray *x, int *size, t_word **vec);
EXTERN void garray_redraw(t_garray *x);
EXTERN int garray_npoints(t_garray *x);
EXTERN char *garray_vec(t_garray *x);
EXTERN void garray_resize(t_garray *x, t_floatarg f); /* avoid; use this: */
EXTERN void garray_resize_long(t_garray *x, long n); /* better version */
EXTERN void garray_usedindsp(t_garray *x);
EXTERN void garray_setsaveit(t_garray *x, int saveit);
EXTERN t_glist *garray_getglist(t_garray *x);
EXTERN t_array *garray_getarray(t_garray *x);
EXTERN t_class *scalar_class;
EXTERN t_float *value_get(t_symbol *s);
EXTERN void value_release(t_symbol *s);
EXTERN int value_getfloat(t_symbol *s, t_float *f);
EXTERN int value_setfloat(t_symbol *s, t_float f);
/* ------- GUI interface - functions to send strings to TK --------- */
typedef void (*t_guicallbackfn)(t_gobj *client, t_glist *glist);
EXTERN void sys_vgui(const char *fmt, ...);
EXTERN void sys_gui(const char *s);
EXTERN void sys_pretendguibytes(int n);
EXTERN void sys_queuegui(void *client, t_glist *glist, t_guicallbackfn f);
EXTERN void sys_unqueuegui(void *client);
/* dialog window creation and destruction */
EXTERN void gfxstub_new(t_pd *owner, void *key, const char *cmd);
EXTERN void gfxstub_deleteforkey(void *key);
extern t_class *glob_pdobject; /* object to send "pd" messages */
/*------------- Max 0.26 compatibility --------------------*/
/* the following reflects the new way classes are laid out, with the class
pointing to the messlist and not vice versa. Externs shouldn't feel it. */
typedef t_class *t_externclass;
EXTERN void c_extern(t_externclass *cls, t_newmethod newroutine,
t_method freeroutine, t_symbol *name, size_t size, int tiny, \
t_atomtype arg1, ...);
EXTERN void c_addmess(t_method fn, t_symbol *sel, t_atomtype arg1, ...);
#define t_getbytes getbytes
#define t_freebytes freebytes
#define t_resizebytes resizebytes
#define typedmess pd_typedmess
#define vmess pd_vmess
/* A definition to help gui objects straddle 0.34-0.35 changes. If this is
defined, there is a "te_xpix" field in objects, not a "te_xpos" as before: */
#define PD_USE_TE_XPIX
#ifndef _MSC_VER /* Microoft compiler can't handle "inline" function/macros */
#if defined(__i386__) || defined(__x86_64__) || defined(__arm__)
/* a test for NANs and denormals. Should only be necessary on i386. */
#if PD_FLOATSIZE == 32
typedef union
{
t_float f;
unsigned int ui;
}t_bigorsmall32;
static inline int PD_BADFLOAT(t_float f) /* malformed float */
{
t_bigorsmall32 pun;
pun.f = f;
pun.ui &= 0x7f800000;
return((pun.ui == 0) | (pun.ui == 0x7f800000));
}
static inline int PD_BIGORSMALL(t_float f) /* exponent outside (-64,64) */
{
t_bigorsmall32 pun;
pun.f = f;
return((pun.ui & 0x20000000) == ((pun.ui >> 1) & 0x20000000));
}
#elif PD_FLOATSIZE == 64
typedef union
{
t_float f;
unsigned int ui[2];
}t_bigorsmall64;
static inline int PD_BADFLOAT(t_float f) /* malformed double */
{
t_bigorsmall64 pun;
pun.f = f;
pun.ui[1] &= 0x7ff00000;
return((pun.ui[1] == 0) | (pun.ui[1] == 0x7ff00000));
}
static inline int PD_BIGORSMALL(t_float f) /* exponent outside (-512,512) */
{
t_bigorsmall64 pun;
pun.f = f;
return((pun.ui[1] & 0x20000000) == ((pun.ui[1] >> 1) & 0x20000000));
}
#endif /* PD_FLOATSIZE */
#else /* not INTEL or ARM */
#define PD_BADFLOAT(f) 0
#define PD_BIGORSMALL(f) 0
#endif
#else /* _MSC_VER */
#if PD_FLOATSIZE == 32
#define PD_BADFLOAT(f) ((((*(unsigned int*)&(f))&0x7f800000)==0) || \
(((*(unsigned int*)&(f))&0x7f800000)==0x7f800000))
/* more stringent test: anything not between 1e-19 and 1e19 in absolute val */
#define PD_BIGORSMALL(f) ((((*(unsigned int*)&(f))&0x60000000)==0) || \
(((*(unsigned int*)&(f))&0x60000000)==0x60000000))
#else /* 64 bits... don't know what to do here */
#define PD_BADFLOAT(f) (!(((f) >= 0) || ((f) <= 0)))
#define PD_BIGORSMALL(f) ((f) > 1e150 || (f) < -1e150 \
|| (f) > -1e-150 && (f) < 1e-150 )
#endif
#endif /* _MSC_VER */
/* get version number at run time */
EXTERN void sys_getversion(int *major, int *minor, int *bugfix);
EXTERN_STRUCT _instancemidi;
#define t_instancemidi struct _instancemidi
EXTERN_STRUCT _instanceinter;
#define t_instanceinter struct _instanceinter
EXTERN_STRUCT _instancecanvas;
#define t_instancecanvas struct _instancecanvas
EXTERN_STRUCT _instanceugen;
#define t_instanceugen struct _instanceugen
EXTERN_STRUCT _instancestuff;
#define t_instancestuff struct _instancestuff
#ifndef PDTHREADS
#define PDTHREADS 1
#endif
struct _pdinstance
{
double pd_systime; /* global time in Pd ticks */
t_clock *pd_clock_setlist; /* list of set clocks */
t_canvas *pd_canvaslist; /* list of all root canvases */
struct _template *pd_templatelist; /* list of all templates */
int pd_instanceno; /* ordinal number of this instance */
t_symbol **pd_symhash; /* symbol table hash table */
t_instancemidi *pd_midi; /* private stuff for x_midi.c */
t_instanceinter *pd_inter; /* private stuff for s_inter.c */
t_instanceugen *pd_ugen; /* private stuff for d_ugen.c */
t_instancecanvas *pd_gui; /* semi-private stuff in g_canvas.h */
t_instancestuff *pd_stuff; /* semi-private stuff in s_stuff.h */
t_pd *pd_newest; /* most recently created object */
#ifdef PDINSTANCE
t_symbol pd_s_pointer;
t_symbol pd_s_float;
t_symbol pd_s_symbol;
t_symbol pd_s_bang;
t_symbol pd_s_list;
t_symbol pd_s_anything;
t_symbol pd_s_signal;
t_symbol pd_s__N;
t_symbol pd_s__X;
t_symbol pd_s_x;
t_symbol pd_s_y;
t_symbol pd_s_;
#endif
#if PDTHREADS
int pd_islocked;
#endif
};
#define t_pdinstance struct _pdinstance
EXTERN t_pdinstance pd_maininstance;
/* m_pd.c */
#ifdef PDINSTANCE
EXTERN t_pdinstance *pdinstance_new(void);
EXTERN void pd_setinstance(t_pdinstance *x);
EXTERN void pdinstance_free(t_pdinstance *x);
#endif /* PDINSTANCE */
#if defined(PDTHREADS) && defined(PDINSTANCE)
#ifdef _MSC_VER
#define PERTHREAD __declspec(thread)
#else
#define PERTHREAD __thread
#endif /* _MSC_VER */
#else
#define PERTHREAD
#endif
#ifdef PDINSTANCE
extern PERTHREAD t_pdinstance *pd_this;
EXTERN t_pdinstance **pd_instances;
EXTERN int pd_ninstances;
#else
#define pd_this (&pd_maininstance)
#endif /* PDINSTANCE */
#ifdef PDINSTANCE
#define s_pointer (pd_this->pd_s_pointer)
#define s_float (pd_this->pd_s_float)
#define s_symbol (pd_this->pd_s_symbol)
#define s_bang (pd_this->pd_s_bang)
#define s_list (pd_this->pd_s_list)
#define s_anything (pd_this->pd_s_anything)
#define s_signal (pd_this->pd_s_signal)
#define s__N (pd_this->pd_s__N)
#define s__X (pd_this->pd_s__X)
#define s_x (pd_this->pd_s_x)
#define s_y (pd_this->pd_s_y)
#define s_ (pd_this->pd_s_)
#else
EXTERN t_symbol s_pointer, s_float, s_symbol, s_bang, s_list, s_anything,
s_signal, s__N, s__X, s_x, s_y, s_;
#endif
EXTERN t_canvas *pd_getcanvaslist(void);
EXTERN int pd_getdspstate(void);
/* x_text.c */
EXTERN t_binbuf *text_getbufbyname(t_symbol *s); /* get binbuf from text obj */
EXTERN void text_notifybyname(t_symbol *s); /* notify it was modified */
#if defined(_LANGUAGE_C_PLUS_PLUS) || defined(__cplusplus)
}
#endif
#define __m_pd_h_
#endif /* __m_pd_h_ */ |
borguss2014/Arduino-Snake-Game | Data_Structs.h | #ifndef Data_Structs_h
#define Data_Structs_h
#include "Arduino.h"
enum GameState
{
PLAYING,
STOP
};
enum Direction
{
UP,
DOWN,
LEFT,
RIGHT,
MIDDLE
};
struct Position
{
unsigned int x = 0;
unsigned int y = 0;
};
struct Segment
{
unsigned int x = 0;
unsigned int y = 0;
};
#endif
|
borguss2014/Arduino-Snake-Game | Button.h | <filename>Button.h
#ifndef Button_h
#define Button_h
#include "Arduino.h"
class Button
{
public:
Button(int pin);
void checkStatus();
void update();
void onPress();
void onRelease();
void setOnClickListener(
void (*clickFunction)(int),
int direction
);
private:
bool _pressed;
bool _executed;
bool _clickListenerSet;
int _lastState;
unsigned int _debounceDelay;
unsigned long _lastPressed;
int _buttonState;
int _pin;
int _direction;
void (*_callback)(int);
};
#endif
|
borguss2014/Arduino-Snake-Game | Food.h | #ifndef Food_h
#define Food_h
#include "Arduino.h"
#include "LedControl.h"
#include "Data_Structs.h"
class Food
{
public:
Food(LedControl* lc, int rows, int columns);
void generateNewLocation();
Position getPosition();
void draw();
void clearImage();
void setDrawn(bool status);
void reset();
private:
Position _currentPos;
int _rows;
int _columns;
bool _drawn;
LedControl* _lc;
};
#endif
|
borguss2014/Arduino-Snake-Game | Snake.h | <filename>Snake.h
#ifndef Snake_h
#define Snake_h
#include "Arduino.h"
#include "Food.h"
#include "LedControl.h"
#include "Data_Structs.h"
class Snake
{
public:
Snake(LedControl* lc, int rows, int columns);
bool checkCollision(Food* food);
bool checkSelfCollision();
void eat(Food* food);
void setDirection(int dir);
int getDirection();
void draw();
int getLength();
void updateBody();
void moveNewLocation();
void clearImage();
void setDrawn(bool status);
void reset();
Segment addHead();
Segment getHeadPos();
private:
int _length;
int _direction;
int _columns;
int _rows;
bool _drawn;
Segment* _body;
LedControl* _lc;
};
#endif
|
Beehivenetwork/lightningcash-gold | src/chainparamsseeds.h | #ifndef BITCOIN_CHAINPARAMSSEEDS_H
#define BITCOIN_CHAINPARAMSSEEDS_H
/**
* List of fixed seed nodes for the lightningcash network
* AUTOGENERATED by contrib/seeds/generate-seeds.py
*
* Each line contains a 16-byte IPv6 address and a port.
* IPv4 as well as onion addresses are wrapped inside a IPv6 address accordingly.
*/
static SeedSpec6 pnSeed6_main[] = {
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x9f,0x59,0xec,0x77}, 9111},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x76,0x19,0x85,0x1e}, 9111},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0xc2,0x13,0xeb,0x47}, 9111},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x44,0x77,0x2a,0x86}, 9111},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x55,0x0f,0x77,0x41}, 9111},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x61,0x5e,0xb7,0x88}, 9111},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x8b,0xbe,0xe9,0x9e}, 9111},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x4f,0x64,0xb8,0x49}, 9111}
};
static SeedSpec6 pnSeed6_test[] = {
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x60,0x7f,0xc0,0x1e}, 59111},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x22,0x49,0x0a,0x88}, 59111},
{{0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xff,0xff,0x23,0xf7,0x1b,0x69}, 59111}
};
#endif // BITCOIN_CHAINPARAMSSEEDS_H
|
Mogassam/qxtglobalshortcut | src/xcbkeyboard.h | <reponame>Mogassam/qxtglobalshortcut<gh_stars>10-100
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 3 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL3 included in the
** packaging of this file. Please review the following information to
** ensure the GNU Lesser General Public License version 3 requirements
** will be met: https://www.gnu.org/licenses/lgpl-3.0.html.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 2.0 or (at your option) the GNU General
** Public license version 3 or any later version approved by the KDE Free
** Qt Foundation. The licenses are as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL2 and LICENSE.GPL3
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-2.0.html and
** https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/
// Following definitions and table are taken from
// "qt5/qtbase/src/plugins/platforms/xcb/qxcbkeyboard.cpp".
#include <Qt>
#include <X11/keysym.h>
#ifndef XK_ISO_Left_Tab
#define XK_ISO_Left_Tab 0xFE20
#endif
#ifndef XK_dead_hook
#define XK_dead_hook 0xFE61
#endif
#ifndef XK_dead_horn
#define XK_dead_horn 0xFE62
#endif
#ifndef XK_Codeinput
#define XK_Codeinput 0xFF37
#endif
#ifndef XK_Kanji_Bangou
#define XK_Kanji_Bangou 0xFF37 /* same as codeinput */
#endif
// Fix old X libraries
#ifndef XK_KP_Home
#define XK_KP_Home 0xFF95
#endif
#ifndef XK_KP_Left
#define XK_KP_Left 0xFF96
#endif
#ifndef XK_KP_Up
#define XK_KP_Up 0xFF97
#endif
#ifndef XK_KP_Right
#define XK_KP_Right 0xFF98
#endif
#ifndef XK_KP_Down
#define XK_KP_Down 0xFF99
#endif
#ifndef XK_KP_Prior
#define XK_KP_Prior 0xFF9A
#endif
#ifndef XK_KP_Next
#define XK_KP_Next 0xFF9B
#endif
#ifndef XK_KP_End
#define XK_KP_End 0xFF9C
#endif
#ifndef XK_KP_Insert
#define XK_KP_Insert 0xFF9E
#endif
#ifndef XK_KP_Delete
#define XK_KP_Delete 0xFF9F
#endif
// the next lines are taken on 10/2009 from X.org (X11/XF86keysym.h), defining some special
// multimedia keys. They are included here as not every system has them.
#define XF86XK_MonBrightnessUp 0x1008FF02
#define XF86XK_MonBrightnessDown 0x1008FF03
#define XF86XK_KbdLightOnOff 0x1008FF04
#define XF86XK_KbdBrightnessUp 0x1008FF05
#define XF86XK_KbdBrightnessDown 0x1008FF06
#define XF86XK_Standby 0x1008FF10
#define XF86XK_AudioLowerVolume 0x1008FF11
#define XF86XK_AudioMute 0x1008FF12
#define XF86XK_AudioRaiseVolume 0x1008FF13
#define XF86XK_AudioPlay 0x1008FF14
#define XF86XK_AudioStop 0x1008FF15
#define XF86XK_AudioPrev 0x1008FF16
#define XF86XK_AudioNext 0x1008FF17
#define XF86XK_HomePage 0x1008FF18
#define XF86XK_Mail 0x1008FF19
#define XF86XK_Start 0x1008FF1A
#define XF86XK_Search 0x1008FF1B
#define XF86XK_AudioRecord 0x1008FF1C
#define XF86XK_Calculator 0x1008FF1D
#define XF86XK_Memo 0x1008FF1E
#define XF86XK_ToDoList 0x1008FF1F
#define XF86XK_Calendar 0x1008FF20
#define XF86XK_PowerDown 0x1008FF21
#define XF86XK_ContrastAdjust 0x1008FF22
#define XF86XK_Back 0x1008FF26
#define XF86XK_Forward 0x1008FF27
#define XF86XK_Stop 0x1008FF28
#define XF86XK_Refresh 0x1008FF29
#define XF86XK_PowerOff 0x1008FF2A
#define XF86XK_WakeUp 0x1008FF2B
#define XF86XK_Eject 0x1008FF2C
#define XF86XK_ScreenSaver 0x1008FF2D
#define XF86XK_WWW 0x1008FF2E
#define XF86XK_Sleep 0x1008FF2F
#define XF86XK_Favorites 0x1008FF30
#define XF86XK_AudioPause 0x1008FF31
#define XF86XK_AudioMedia 0x1008FF32
#define XF86XK_MyComputer 0x1008FF33
#define XF86XK_LightBulb 0x1008FF35
#define XF86XK_Shop 0x1008FF36
#define XF86XK_History 0x1008FF37
#define XF86XK_OpenURL 0x1008FF38
#define XF86XK_AddFavorite 0x1008FF39
#define XF86XK_HotLinks 0x1008FF3A
#define XF86XK_BrightnessAdjust 0x1008FF3B
#define XF86XK_Finance 0x1008FF3C
#define XF86XK_Community 0x1008FF3D
#define XF86XK_AudioRewind 0x1008FF3E
#define XF86XK_BackForward 0x1008FF3F
#define XF86XK_Launch0 0x1008FF40
#define XF86XK_Launch1 0x1008FF41
#define XF86XK_Launch2 0x1008FF42
#define XF86XK_Launch3 0x1008FF43
#define XF86XK_Launch4 0x1008FF44
#define XF86XK_Launch5 0x1008FF45
#define XF86XK_Launch6 0x1008FF46
#define XF86XK_Launch7 0x1008FF47
#define XF86XK_Launch8 0x1008FF48
#define XF86XK_Launch9 0x1008FF49
#define XF86XK_LaunchA 0x1008FF4A
#define XF86XK_LaunchB 0x1008FF4B
#define XF86XK_LaunchC 0x1008FF4C
#define XF86XK_LaunchD 0x1008FF4D
#define XF86XK_LaunchE 0x1008FF4E
#define XF86XK_LaunchF 0x1008FF4F
#define XF86XK_ApplicationLeft 0x1008FF50
#define XF86XK_ApplicationRight 0x1008FF51
#define XF86XK_Book 0x1008FF52
#define XF86XK_CD 0x1008FF53
#define XF86XK_Calculater 0x1008FF54
#define XF86XK_Clear 0x1008FF55
#define XF86XK_ClearGrab 0x1008FE21
#define XF86XK_Close 0x1008FF56
#define XF86XK_Copy 0x1008FF57
#define XF86XK_Cut 0x1008FF58
#define XF86XK_Display 0x1008FF59
#define XF86XK_DOS 0x1008FF5A
#define XF86XK_Documents 0x1008FF5B
#define XF86XK_Excel 0x1008FF5C
#define XF86XK_Explorer 0x1008FF5D
#define XF86XK_Game 0x1008FF5E
#define XF86XK_Go 0x1008FF5F
#define XF86XK_iTouch 0x1008FF60
#define XF86XK_LogOff 0x1008FF61
#define XF86XK_Market 0x1008FF62
#define XF86XK_Meeting 0x1008FF63
#define XF86XK_MenuKB 0x1008FF65
#define XF86XK_MenuPB 0x1008FF66
#define XF86XK_MySites 0x1008FF67
#define XF86XK_New 0x1008FF68
#define XF86XK_News 0x1008FF69
#define XF86XK_OfficeHome 0x1008FF6A
#define XF86XK_Open 0x1008FF6B
#define XF86XK_Option 0x1008FF6C
#define XF86XK_Paste 0x1008FF6D
#define XF86XK_Phone 0x1008FF6E
#define XF86XK_Reply 0x1008FF72
#define XF86XK_Reload 0x1008FF73
#define XF86XK_RotateWindows 0x1008FF74
#define XF86XK_RotationPB 0x1008FF75
#define XF86XK_RotationKB 0x1008FF76
#define XF86XK_Save 0x1008FF77
#define XF86XK_Send 0x1008FF7B
#define XF86XK_Spell 0x1008FF7C
#define XF86XK_SplitScreen 0x1008FF7D
#define XF86XK_Support 0x1008FF7E
#define XF86XK_TaskPane 0x1008FF7F
#define XF86XK_Terminal 0x1008FF80
#define XF86XK_Tools 0x1008FF81
#define XF86XK_Travel 0x1008FF82
#define XF86XK_Video 0x1008FF87
#define XF86XK_Word 0x1008FF89
#define XF86XK_Xfer 0x1008FF8A
#define XF86XK_ZoomIn 0x1008FF8B
#define XF86XK_ZoomOut 0x1008FF8C
#define XF86XK_Away 0x1008FF8D
#define XF86XK_Messenger 0x1008FF8E
#define XF86XK_WebCam 0x1008FF8F
#define XF86XK_MailForward 0x1008FF90
#define XF86XK_Pictures 0x1008FF91
#define XF86XK_Music 0x1008FF92
#define XF86XK_Battery 0x1008FF93
#define XF86XK_Bluetooth 0x1008FF94
#define XF86XK_WLAN 0x1008FF95
#define XF86XK_UWB 0x1008FF96
#define XF86XK_AudioForward 0x1008FF97
#define XF86XK_AudioRepeat 0x1008FF98
#define XF86XK_AudioRandomPlay 0x1008FF99
#define XF86XK_Subtitle 0x1008FF9A
#define XF86XK_AudioCycleTrack 0x1008FF9B
#define XF86XK_Time 0x1008FF9F
#define XF86XK_Select 0x1008FFA0
#define XF86XK_View 0x1008FFA1
#define XF86XK_TopMenu 0x1008FFA2
#define XF86XK_Red 0x1008FFA3
#define XF86XK_Green 0x1008FFA4
#define XF86XK_Yellow 0x1008FFA5
#define XF86XK_Blue 0x1008FFA6
#define XF86XK_Suspend 0x1008FFA7
#define XF86XK_Hibernate 0x1008FFA8
#define XF86XK_TouchpadToggle 0x1008FFA9
#define XF86XK_TouchpadOn 0x1008FFB0
#define XF86XK_TouchpadOff 0x1008FFB1
#define XF86XK_AudioMicMute 0x1008FFB2
// end of XF86keysyms.h
// keyboard mapping table
static const unsigned int KeyTbl[] = {
// misc keys
XK_Escape, Qt::Key_Escape,
XK_Tab, Qt::Key_Tab,
XK_ISO_Left_Tab, Qt::Key_Backtab,
XK_BackSpace, Qt::Key_Backspace,
XK_Return, Qt::Key_Return,
XK_Insert, Qt::Key_Insert,
XK_Delete, Qt::Key_Delete,
XK_Clear, Qt::Key_Delete,
XK_Pause, Qt::Key_Pause,
XK_Print, Qt::Key_Print,
0x1005FF60, Qt::Key_SysReq, // hardcoded Sun SysReq
0x1007ff00, Qt::Key_SysReq, // hardcoded X386 SysReq
// cursor movement
XK_Home, Qt::Key_Home,
XK_End, Qt::Key_End,
XK_Left, Qt::Key_Left,
XK_Up, Qt::Key_Up,
XK_Right, Qt::Key_Right,
XK_Down, Qt::Key_Down,
XK_Prior, Qt::Key_PageUp,
XK_Next, Qt::Key_PageDown,
// modifiers
XK_Shift_L, Qt::Key_Shift,
XK_Shift_R, Qt::Key_Shift,
XK_Shift_Lock, Qt::Key_Shift,
XK_Control_L, Qt::Key_Control,
XK_Control_R, Qt::Key_Control,
XK_Meta_L, Qt::Key_Meta,
XK_Meta_R, Qt::Key_Meta,
XK_Alt_L, Qt::Key_Alt,
XK_Alt_R, Qt::Key_Alt,
XK_Caps_Lock, Qt::Key_CapsLock,
XK_Num_Lock, Qt::Key_NumLock,
XK_Scroll_Lock, Qt::Key_ScrollLock,
XK_Super_L, Qt::Key_Super_L,
XK_Super_R, Qt::Key_Super_R,
XK_Menu, Qt::Key_Menu,
XK_Hyper_L, Qt::Key_Hyper_L,
XK_Hyper_R, Qt::Key_Hyper_R,
XK_Help, Qt::Key_Help,
0x1000FF74, Qt::Key_Backtab, // hardcoded HP backtab
0x1005FF10, Qt::Key_F11, // hardcoded Sun F36 (labeled F11)
0x1005FF11, Qt::Key_F12, // hardcoded Sun F37 (labeled F12)
// numeric and function keypad keys
XK_KP_Space, Qt::Key_Space,
XK_KP_Tab, Qt::Key_Tab,
XK_KP_Enter, Qt::Key_Enter,
//XK_KP_F1, Qt::Key_F1,
//XK_KP_F2, Qt::Key_F2,
//XK_KP_F3, Qt::Key_F3,
//XK_KP_F4, Qt::Key_F4,
XK_KP_Home, Qt::Key_Home,
XK_KP_Left, Qt::Key_Left,
XK_KP_Up, Qt::Key_Up,
XK_KP_Right, Qt::Key_Right,
XK_KP_Down, Qt::Key_Down,
XK_KP_Prior, Qt::Key_PageUp,
XK_KP_Next, Qt::Key_PageDown,
XK_KP_End, Qt::Key_End,
XK_KP_Begin, Qt::Key_Clear,
XK_KP_Insert, Qt::Key_Insert,
XK_KP_Delete, Qt::Key_Delete,
XK_KP_Equal, Qt::Key_Equal,
XK_KP_Multiply, Qt::Key_Asterisk,
XK_KP_Add, Qt::Key_Plus,
XK_KP_Separator, Qt::Key_Comma,
XK_KP_Subtract, Qt::Key_Minus,
XK_KP_Decimal, Qt::Key_Period,
XK_KP_Divide, Qt::Key_Slash,
// International input method support keys
// International & multi-key character composition
XK_ISO_Level3_Shift, Qt::Key_AltGr,
XK_Multi_key, Qt::Key_Multi_key,
XK_Codeinput, Qt::Key_Codeinput,
XK_SingleCandidate, Qt::Key_SingleCandidate,
XK_MultipleCandidate, Qt::Key_MultipleCandidate,
XK_PreviousCandidate, Qt::Key_PreviousCandidate,
// Misc Functions
XK_Mode_switch, Qt::Key_Mode_switch,
XK_script_switch, Qt::Key_Mode_switch,
// Japanese keyboard support
XK_Kanji, Qt::Key_Kanji,
XK_Muhenkan, Qt::Key_Muhenkan,
//XK_Henkan_Mode, Qt::Key_Henkan_Mode,
XK_Henkan_Mode, Qt::Key_Henkan,
XK_Henkan, Qt::Key_Henkan,
XK_Romaji, Qt::Key_Romaji,
XK_Hiragana, Qt::Key_Hiragana,
XK_Katakana, Qt::Key_Katakana,
XK_Hiragana_Katakana, Qt::Key_Hiragana_Katakana,
XK_Zenkaku, Qt::Key_Zenkaku,
XK_Hankaku, Qt::Key_Hankaku,
XK_Zenkaku_Hankaku, Qt::Key_Zenkaku_Hankaku,
XK_Touroku, Qt::Key_Touroku,
XK_Massyo, Qt::Key_Massyo,
XK_Kana_Lock, Qt::Key_Kana_Lock,
XK_Kana_Shift, Qt::Key_Kana_Shift,
XK_Eisu_Shift, Qt::Key_Eisu_Shift,
XK_Eisu_toggle, Qt::Key_Eisu_toggle,
//XK_Kanji_Bangou, Qt::Key_Kanji_Bangou,
//XK_Zen_Koho, Qt::Key_Zen_Koho,
//XK_Mae_Koho, Qt::Key_Mae_Koho,
XK_Kanji_Bangou, Qt::Key_Codeinput,
XK_Zen_Koho, Qt::Key_MultipleCandidate,
XK_Mae_Koho, Qt::Key_PreviousCandidate,
#ifdef XK_KOREAN
// Korean keyboard support
XK_Hangul, Qt::Key_Hangul,
XK_Hangul_Start, Qt::Key_Hangul_Start,
XK_Hangul_End, Qt::Key_Hangul_End,
XK_Hangul_Hanja, Qt::Key_Hangul_Hanja,
XK_Hangul_Jamo, Qt::Key_Hangul_Jamo,
XK_Hangul_Romaja, Qt::Key_Hangul_Romaja,
//XK_Hangul_Codeinput, Qt::Key_Hangul_Codeinput,
XK_Hangul_Codeinput, Qt::Key_Codeinput,
XK_Hangul_Jeonja, Qt::Key_Hangul_Jeonja,
XK_Hangul_Banja, Qt::Key_Hangul_Banja,
XK_Hangul_PreHanja, Qt::Key_Hangul_PreHanja,
XK_Hangul_PostHanja, Qt::Key_Hangul_PostHanja,
//XK_Hangul_SingleCandidate,Qt::Key_Hangul_SingleCandidate,
//XK_Hangul_MultipleCandidate,Qt::Key_Hangul_MultipleCandidate,
//XK_Hangul_PreviousCandidate,Qt::Key_Hangul_PreviousCandidate,
XK_Hangul_SingleCandidate, Qt::Key_SingleCandidate,
XK_Hangul_MultipleCandidate,Qt::Key_MultipleCandidate,
XK_Hangul_PreviousCandidate,Qt::Key_PreviousCandidate,
XK_Hangul_Special, Qt::Key_Hangul_Special,
//XK_Hangul_switch, Qt::Key_Hangul_switch,
XK_Hangul_switch, Qt::Key_Mode_switch,
#endif // XK_KOREAN
// dead keys
XK_dead_grave, Qt::Key_Dead_Grave,
XK_dead_acute, Qt::Key_Dead_Acute,
XK_dead_circumflex, Qt::Key_Dead_Circumflex,
XK_dead_tilde, Qt::Key_Dead_Tilde,
XK_dead_macron, Qt::Key_Dead_Macron,
XK_dead_breve, Qt::Key_Dead_Breve,
XK_dead_abovedot, Qt::Key_Dead_Abovedot,
XK_dead_diaeresis, Qt::Key_Dead_Diaeresis,
XK_dead_abovering, Qt::Key_Dead_Abovering,
XK_dead_doubleacute, Qt::Key_Dead_Doubleacute,
XK_dead_caron, Qt::Key_Dead_Caron,
XK_dead_cedilla, Qt::Key_Dead_Cedilla,
XK_dead_ogonek, Qt::Key_Dead_Ogonek,
XK_dead_iota, Qt::Key_Dead_Iota,
XK_dead_voiced_sound, Qt::Key_Dead_Voiced_Sound,
XK_dead_semivoiced_sound, Qt::Key_Dead_Semivoiced_Sound,
XK_dead_belowdot, Qt::Key_Dead_Belowdot,
XK_dead_hook, Qt::Key_Dead_Hook,
XK_dead_horn, Qt::Key_Dead_Horn,
// Special keys from X.org - This include multimedia keys,
// wireless/bluetooth/uwb keys, special launcher keys, etc.
XF86XK_Back, Qt::Key_Back,
XF86XK_Forward, Qt::Key_Forward,
XF86XK_Stop, Qt::Key_Stop,
XF86XK_Refresh, Qt::Key_Refresh,
XF86XK_Favorites, Qt::Key_Favorites,
XF86XK_AudioMedia, Qt::Key_LaunchMedia,
XF86XK_OpenURL, Qt::Key_OpenUrl,
XF86XK_HomePage, Qt::Key_HomePage,
XF86XK_Search, Qt::Key_Search,
XF86XK_AudioLowerVolume, Qt::Key_VolumeDown,
XF86XK_AudioMute, Qt::Key_VolumeMute,
XF86XK_AudioRaiseVolume, Qt::Key_VolumeUp,
XF86XK_AudioPlay, Qt::Key_MediaPlay,
XF86XK_AudioStop, Qt::Key_MediaStop,
XF86XK_AudioPrev, Qt::Key_MediaPrevious,
XF86XK_AudioNext, Qt::Key_MediaNext,
XF86XK_AudioRecord, Qt::Key_MediaRecord,
XF86XK_AudioPause, Qt::Key_MediaPause,
XF86XK_Mail, Qt::Key_LaunchMail,
XF86XK_MyComputer, Qt::Key_Launch0, // ### Qt 6: remap properly
XF86XK_Calculator, Qt::Key_Launch1,
XF86XK_Memo, Qt::Key_Memo,
XF86XK_ToDoList, Qt::Key_ToDoList,
XF86XK_Calendar, Qt::Key_Calendar,
XF86XK_PowerDown, Qt::Key_PowerDown,
XF86XK_ContrastAdjust, Qt::Key_ContrastAdjust,
XF86XK_Standby, Qt::Key_Standby,
XF86XK_MonBrightnessUp, Qt::Key_MonBrightnessUp,
XF86XK_MonBrightnessDown, Qt::Key_MonBrightnessDown,
XF86XK_KbdLightOnOff, Qt::Key_KeyboardLightOnOff,
XF86XK_KbdBrightnessUp, Qt::Key_KeyboardBrightnessUp,
XF86XK_KbdBrightnessDown, Qt::Key_KeyboardBrightnessDown,
XF86XK_PowerOff, Qt::Key_PowerOff,
XF86XK_WakeUp, Qt::Key_WakeUp,
XF86XK_Eject, Qt::Key_Eject,
XF86XK_ScreenSaver, Qt::Key_ScreenSaver,
XF86XK_WWW, Qt::Key_WWW,
XF86XK_Sleep, Qt::Key_Sleep,
XF86XK_LightBulb, Qt::Key_LightBulb,
XF86XK_Shop, Qt::Key_Shop,
XF86XK_History, Qt::Key_History,
XF86XK_AddFavorite, Qt::Key_AddFavorite,
XF86XK_HotLinks, Qt::Key_HotLinks,
XF86XK_BrightnessAdjust, Qt::Key_BrightnessAdjust,
XF86XK_Finance, Qt::Key_Finance,
XF86XK_Community, Qt::Key_Community,
XF86XK_AudioRewind, Qt::Key_AudioRewind,
XF86XK_BackForward, Qt::Key_BackForward,
XF86XK_ApplicationLeft, Qt::Key_ApplicationLeft,
XF86XK_ApplicationRight, Qt::Key_ApplicationRight,
XF86XK_Book, Qt::Key_Book,
XF86XK_CD, Qt::Key_CD,
XF86XK_Calculater, Qt::Key_Calculator,
XF86XK_Clear, Qt::Key_Clear,
XF86XK_ClearGrab, Qt::Key_ClearGrab,
XF86XK_Close, Qt::Key_Close,
XF86XK_Copy, Qt::Key_Copy,
XF86XK_Cut, Qt::Key_Cut,
XF86XK_Display, Qt::Key_Display,
XF86XK_DOS, Qt::Key_DOS,
XF86XK_Documents, Qt::Key_Documents,
XF86XK_Excel, Qt::Key_Excel,
XF86XK_Explorer, Qt::Key_Explorer,
XF86XK_Game, Qt::Key_Game,
XF86XK_Go, Qt::Key_Go,
XF86XK_iTouch, Qt::Key_iTouch,
XF86XK_LogOff, Qt::Key_LogOff,
XF86XK_Market, Qt::Key_Market,
XF86XK_Meeting, Qt::Key_Meeting,
XF86XK_MenuKB, Qt::Key_MenuKB,
XF86XK_MenuPB, Qt::Key_MenuPB,
XF86XK_MySites, Qt::Key_MySites,
#if QT_VERSION >= 0x050400
XF86XK_New, Qt::Key_New,
#endif
XF86XK_News, Qt::Key_News,
XF86XK_OfficeHome, Qt::Key_OfficeHome,
#if QT_VERSION >= 0x050400
XF86XK_Open, Qt::Key_Open,
#endif
XF86XK_Option, Qt::Key_Option,
XF86XK_Paste, Qt::Key_Paste,
XF86XK_Phone, Qt::Key_Phone,
XF86XK_Reply, Qt::Key_Reply,
XF86XK_Reload, Qt::Key_Reload,
XF86XK_RotateWindows, Qt::Key_RotateWindows,
XF86XK_RotationPB, Qt::Key_RotationPB,
XF86XK_RotationKB, Qt::Key_RotationKB,
XF86XK_Save, Qt::Key_Save,
XF86XK_Send, Qt::Key_Send,
XF86XK_Spell, Qt::Key_Spell,
XF86XK_SplitScreen, Qt::Key_SplitScreen,
XF86XK_Support, Qt::Key_Support,
XF86XK_TaskPane, Qt::Key_TaskPane,
XF86XK_Terminal, Qt::Key_Terminal,
XF86XK_Tools, Qt::Key_Tools,
XF86XK_Travel, Qt::Key_Travel,
XF86XK_Video, Qt::Key_Video,
XF86XK_Word, Qt::Key_Word,
XF86XK_Xfer, Qt::Key_Xfer,
XF86XK_ZoomIn, Qt::Key_ZoomIn,
XF86XK_ZoomOut, Qt::Key_ZoomOut,
XF86XK_Away, Qt::Key_Away,
XF86XK_Messenger, Qt::Key_Messenger,
XF86XK_WebCam, Qt::Key_WebCam,
XF86XK_MailForward, Qt::Key_MailForward,
XF86XK_Pictures, Qt::Key_Pictures,
XF86XK_Music, Qt::Key_Music,
XF86XK_Battery, Qt::Key_Battery,
XF86XK_Bluetooth, Qt::Key_Bluetooth,
XF86XK_WLAN, Qt::Key_WLAN,
XF86XK_UWB, Qt::Key_UWB,
XF86XK_AudioForward, Qt::Key_AudioForward,
XF86XK_AudioRepeat, Qt::Key_AudioRepeat,
XF86XK_AudioRandomPlay, Qt::Key_AudioRandomPlay,
XF86XK_Subtitle, Qt::Key_Subtitle,
XF86XK_AudioCycleTrack, Qt::Key_AudioCycleTrack,
XF86XK_Time, Qt::Key_Time,
XF86XK_Select, Qt::Key_Select,
XF86XK_View, Qt::Key_View,
XF86XK_TopMenu, Qt::Key_TopMenu,
#if QT_VERSION >= 0x050400
XF86XK_Red, Qt::Key_Red,
XF86XK_Green, Qt::Key_Green,
XF86XK_Yellow, Qt::Key_Yellow,
XF86XK_Blue, Qt::Key_Blue,
#endif
XF86XK_Bluetooth, Qt::Key_Bluetooth,
XF86XK_Suspend, Qt::Key_Suspend,
XF86XK_Hibernate, Qt::Key_Hibernate,
#if QT_VERSION >= 0x050400
XF86XK_TouchpadToggle, Qt::Key_TouchpadToggle,
XF86XK_TouchpadOn, Qt::Key_TouchpadOn,
XF86XK_TouchpadOff, Qt::Key_TouchpadOff,
XF86XK_AudioMicMute, Qt::Key_MicMute,
#endif
XF86XK_Launch0, Qt::Key_Launch2, // ### Qt 6: remap properly
XF86XK_Launch1, Qt::Key_Launch3,
XF86XK_Launch2, Qt::Key_Launch4,
XF86XK_Launch3, Qt::Key_Launch5,
XF86XK_Launch4, Qt::Key_Launch6,
XF86XK_Launch5, Qt::Key_Launch7,
XF86XK_Launch6, Qt::Key_Launch8,
XF86XK_Launch7, Qt::Key_Launch9,
XF86XK_Launch8, Qt::Key_LaunchA,
XF86XK_Launch9, Qt::Key_LaunchB,
XF86XK_LaunchA, Qt::Key_LaunchC,
XF86XK_LaunchB, Qt::Key_LaunchD,
XF86XK_LaunchC, Qt::Key_LaunchE,
XF86XK_LaunchD, Qt::Key_LaunchF,
XF86XK_LaunchE, Qt::Key_LaunchG,
XF86XK_LaunchF, Qt::Key_LaunchH,
0, 0
};
|
JLouhela/jumpy-demo | Classes/TutorialScene.h | /// Copyright (c) 2019 <NAME>
///
/// 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 __TUTORIAL_SCENE_H__
#define __TUTORIAL_SCENE_H__
#include "BunnyController.h"
#include "ContactListener.h"
#include "PhysicsWorld.h"
#include "TutorialOverlay.h"
#include "cocos2d.h"
#include "InputHandler.h"
#include "TutorialInputHandler.h"
class b2World;
class TutorialScene : public cocos2d::Scene {
public:
static cocos2d::Scene* createScene();
~TutorialScene();
virtual bool init() final;
void update(float dt) final;
private:
void initTutorialLogic();
void jumpLeftTutorial();
void jumpRightTutorial();
void doubleJumpTutorial();
void doubleJumpPreparation();
void doubleJumpClosure();
void dashPreparation();
void dashTutorial();
void tutorialClosure();
void clearInteractions();
void delayedText(float delay, const std::string& text);
PhysicsWorld m_world;
ContactListener m_contactListener;
TutorialOverlay m_tutorialOverlay;
BunnyController m_bunnyController;
cocos2d::EventListenerKeyboard* m_keyListener{nullptr};
InputHandler m_inputHandler;
TutorialInputHandler m_tutorialInputHandler;
// implement the "static create()" method manually
CREATE_FUNC(TutorialScene);
};
#endif // __TUTORIAL_SCENE_H__
|
JLouhela/jumpy-demo | Classes/BeeCycles.h | <filename>Classes/BeeCycles.h
/// Copyright (c) 2019 <NAME>
///
/// 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 __BEE_CYCLES_H__
#define __BEE_CYCLES_H__
#include <vector>
#include "BeeCycle.h"
#include "Direction.h"
class BeeCycles {
public:
struct BeeCyclePair {
BeeCyclePair() = default;
BeeCyclePair(std::uint32_t asnareIndex, std::uint32_t abassIndex)
: snareIndex{asnareIndex}, bassIndex{abassIndex}
{
}
std::uint32_t snareIndex{99999};
std::uint32_t bassIndex{99999};
};
BeeCycles();
const BeeCycle& getSnare(std::uint32_t index) const;
const BeeCycle& getBass(std::uint32_t index) const;
BeeCyclePair getInitialCycles() const;
BeeCyclePair getRandomCycles() const;
BeeCyclePair getDevCycles() const;
private:
std::vector<BeeCycle> m_snareCycles;
std::vector<BeeCycle> m_bassCycles;
};
#endif // __BEE_CYCLES_H__
|
JLouhela/jumpy-demo | Classes/TutorialOverlay.h | <filename>Classes/TutorialOverlay.h
/// Copyright (c) 2019 <NAME>
///
/// 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 __TUTORIAL_OVERLAY_H__
#define __TUTORIAL_OVERLAY_H__
#include <cstdint>
#include <functional>
#include "cocos2d.h"
class TutorialOverlay {
public:
enum class FingerDirection : std::uint8_t { up, upup, updown };
bool init(cocos2d::Scene& scene);
void showText(const cocos2d::Vec2& pos, const std::string& text);
void showText(const std::string& text);
void showSecondaryText(const std::string& text);
void showLeftArea();
void showRightArea();
void showFinger(const cocos2d::Vec2& pos, FingerDirection dir);
void hide();
private:
void showLabel(cocos2d::Label* label, const cocos2d::Vec2& pos, const std::string& text);
cocos2d::Label* m_label{nullptr};
cocos2d::Label* m_secondaryLabel{nullptr};
cocos2d::RenderTexture* m_leftRect{nullptr};
cocos2d::RenderTexture* m_rightRect{nullptr};
cocos2d::Sprite* m_finger{nullptr};
cocos2d::Node* m_overlay{nullptr};
};
#endif // __TUTORIAL_OVERLAY_H__
|
JLouhela/jumpy-demo | Classes/AppDelegate.h | /// Copyright (c) 2019 <NAME>
///
/// 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 _APP_DELEGATE_H_
#define _APP_DELEGATE_H_
#include "cocos2d.h"
/**
@brief The cocos2d Application.
Private inheritance here hides part of interface from Director.
*/
class AppDelegate : private cocos2d::Application
{
public:
AppDelegate();
virtual ~AppDelegate();
virtual void initGLContextAttrs();
/**
@brief Implement Director and Scene init code here.
@return true Initialize success, app continue.
@return false Initialize failed, app terminate.
*/
virtual bool applicationDidFinishLaunching();
/**
@brief Called when the application moves to the background
@param the pointer of the application
*/
virtual void applicationDidEnterBackground();
/**
@brief Called when the application reenters the foreground
@param the pointer of the application
*/
virtual void applicationWillEnterForeground();
};
#endif // _APP_DELEGATE_H_
|
JLouhela/jumpy-demo | Classes/InputHandler.h | /// Copyright (c) 2019 <NAME>
///
/// 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 __INPUT_HANDLER_H__
#define __INPUT_HANDLER_H__
#include <array>
#include <utility>
#include "cocos2d.h"
class BunnyController;
class InputHandler {
public:
enum class Side : bool { left, right };
void init(BunnyController& bunnyController);
void disable();
void disable(Side side);
void enable()
{
m_enabled = {true, true};
}
void enable(Side side);
void update(float dt);
~InputHandler();
private:
enum class InputType : bool { jump, dive };
bool resolveTouch(Side side);
bool resolveInput(const cocos2d::Vec2& screenPos, InputType inputType);
void resetCurrentTouch(Side side);
void resetCurrentTouches();
bool isTouchActive();
cocos2d::EventListenerTouchAllAtOnce* m_touchListener{nullptr};
BunnyController* m_bunnyController{nullptr};
std::array<bool, 2> m_enabled{false, false};
std::array<std::pair<double, cocos2d::Vec2>, 2> m_touchBegins{
std::pair<double, cocos2d::Vec2>{-1.0, cocos2d::Vec2{}},
std::pair<double, cocos2d::Vec2>{-1.0, cocos2d::Vec2{}}};
std::array<std::pair<bool, cocos2d::Vec2>, 2> m_curTouches{
std::pair<double, cocos2d::Vec2>{false, cocos2d::Vec2{}},
std::pair<double, cocos2d::Vec2>{false, cocos2d::Vec2{}}};
};
#endif // __INPUT_HANDLER_H__
|
JLouhela/jumpy-demo | Classes/Bunny.h | <filename>Classes/Bunny.h<gh_stars>0
/// Copyright (c) 2019 <NAME>
///
/// 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 __BUNNY_H__
#define __BUNNY_H__
#include <cstdint>
#include "PhysicsObject.h"
#include "cocos2d.h"
class b2World;
class b2Body;
// Potential refactoring: bee and bunny follow the same pattern
// Base class extraction: "PooledEntity"
using Bunny_id = std::int8_t;
static constexpr Bunny_id invalidBunnyId{-1};
class Bunny {
public:
bool init(Bunny_id id, cocos2d::Scene& scene, b2World& world);
Bunny_id getId() const
{
return m_id;
}
void dispose();
void activate(const cocos2d::Vec2& pos);
void jump();
void dive();
const cocos2d::Rect getBoundingBox() const;
cocos2d::Sprite* getSprite() const
{
return m_sprite;
}
private:
enum class BunnyState : std::uint8_t {
grounded, // Landed on ground
jumped, // Has jumped once
doublejump, // Has jumped twice
dash // Dashing downwards
};
void land();
cocos2d::Sprite* m_sprite{nullptr};
b2Body* m_body{nullptr};
Bunny_id m_id{invalidBunnyId};
PhysicsObject m_physicsObject;
BunnyState m_state{BunnyState::doublejump}; // use doublejump as default to prevent jumping if
// bunny spawns in free fall
};
#endif // __BUNNY_H__
|
JLouhela/jumpy-demo | Classes/BeeCycle.h | /// Copyright (c) 2019 <NAME>
///
/// 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 __BEE_CYCLE_H__
#define __BEE_CYCLE_H__
#include <cstdint>
#include <utility>
#include <vector>
#include "Direction.h"
struct BeeSpawn {
BeeSpawn(float ay, float atime) : y{ay}, timeFromCycleStart{atime}
{
}
float y{0.0f};
float timeFromCycleStart{0.0f};
};
class BeeCycle {
public:
// TODO check
static constexpr float bpm{110.0f};
static constexpr float quarterNote{545.45f};
static constexpr float halfNote{quarterNote * 2.0f};
static constexpr float beatLength{quarterNote * 4.0f};
static constexpr float eightNote{quarterNote / 2.0f};
static constexpr float sixteenthNote{eightNote / 2.0f};
static constexpr float triplet{quarterNote * 0.6667f};
static constexpr float cycleLength{beatLength * 4.0f};
explicit BeeCycle(Direction dir) : m_dir{dir}
{
}
Direction getDirection() const
{
return m_dir;
}
const std::vector<BeeSpawn>& getCycle() const
{
return m_cycle;
}
bool addBeeSpawn(float y, float deltaTime);
bool addBreak(float breakTime);
private:
Direction m_dir{Direction::left};
float m_usedTime{0.0f};
std::vector<BeeSpawn> m_cycle;
};
#endif // _BEE_CYCLE_H__
|
JLouhela/jumpy-demo | Classes/Bee.h | /// Copyright (c) 2019 <NAME>
///
/// 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 __BEE_H__
#define __BEE_H__
#include <cstdint>
#include "Direction.h"
#include "PhysicsObject.h"
#include "cocos2d.h"
class b2World;
class b2Body;
using Bee_id = std::int8_t;
static constexpr Bee_id invalidBeeId{-1};
enum class BeeState : std::uint8_t { active, inactive };
class Bee {
public:
bool init(Bee_id id, b2World& world);
Bee_id getId() const
{
return m_id;
}
BeeState getState() const
{
return m_state;
}
void activate();
cocos2d::Sprite* getSprite() const
{
return m_sprite;
}
void dispose();
void spawn(const cocos2d::Vec2& pos, Direction dir);
private:
cocos2d::Sprite* m_sprite{nullptr};
b2Body* m_body{nullptr};
PhysicsObject m_physicsObject;
Bee_id m_id{invalidBeeId};
cocos2d::Vec2 m_pos{-500, -500};
BeeState m_state{BeeState::inactive};
};
#endif // __BEE_H__
|
JLouhela/jumpy-demo | Classes/JumpyScene.h | /// Copyright (c) 2019 <NAME>
///
/// 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 __JUMPY_SCENE_H__
#define __JUMPY_SCENE_H__
#include "GameLogic.h"
#include "PhysicsWorld.h"
#include "cocos2d.h"
class b2World;
class JumpyScene : public cocos2d::Scene {
public:
static cocos2d::Scene* createScene();
~JumpyScene();
virtual bool init() final;
void update(float dt) final;
void render(cocos2d::Renderer* renderer,
const cocos2d::Mat4& eyeTransform,
const cocos2d::Mat4* eyeProjection = nullptr) final;
private:
PhysicsWorld m_world;
GameLogic m_gameLogic;
cocos2d::EventListenerKeyboard* m_keyListener{nullptr};
// implement the "static create()" method manually
CREATE_FUNC(JumpyScene);
};
#endif // __JUMPYS_SCENE_H__
|
santiramos27/Flix | Flix/View Controllers/MoviesViewController.h | <gh_stars>0
//
// MoviesViewController.h
// Flix
//
// Created by <NAME> on 6/23/21.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface MoviesViewController : UIViewController
@end
NS_ASSUME_NONNULL_END
|
santiramos27/Flix | Flix/View Controllers/UpcomingInfoViewController.h | //
// UpcomingInfoViewController.h
// Flix
//
// Created by <NAME> on 6/25/21.
//
#import <UIKit/UIKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface UpcomingInfoViewController : UIViewController
@property (nonatomic, strong) NSDictionary *movie;
@end
NS_ASSUME_NONNULL_END
|
Jazz86/Group4 | src/Header/ResponseEncoder.h | <filename>src/Header/ResponseEncoder.h
// Copyright (c) 2021, 鍾淯丞, 周杰仕, 林仁鴻. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GROUP4_SRC_HEADER_RESPONSEENCODER_H_
#define GROUP4_SRC_HEADER_RESPONSEENCODER_H_
#include <memory>
#include <string>
#include "OperateData.h"
// Encode the response
class ResponseEncoder {
public:
// Singleton code convention method.
static ResponseEncoder* GetInstance();
// Encode head and body information
std::string Encode(const std::unique_ptr<OperateData>& data);
// Not copyable or movable
ResponseEncoder(const ResponseEncoder& copy) = delete;
ResponseEncoder& operator=(const ResponseEncoder& copy) = delete;
private:
// Singleton code convention method
ResponseEncoder();
};
#endif /* GROUP4_SRC_HEADER_RESPONSEENCODER_H_ */
|
Jazz86/Group4 | src/Header/UploadStream.h | // Copyright (c) 2021, 鍾淯丞, 周杰仕, 林仁鴻. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GROUP4_HEADER_UploadStream_H_
#define GROUP4_HEADER_UploadStream_H_
#include <fstream>
#include <string>
// write file to local may use a lock file or system call to signify that a
// certain file is currently in use.
class UploadStream {
public:
// filename will include file path,
UploadStream(const std::string& filename);
// This function will only append binary at the end of the file, so
// user should handle the order yourself. If it run successfully, it will
// return 1 else 0. If end is True, then it will close the file.
int AppendToFile(const std::string& binary, bool end);
// non copyable
UploadStream(const UploadStream&) = delete;
UploadStream& operator=(const UploadStream&) = delete;
private:
// will point to the same file
std::fstream fd;
// filename include file path
std::string filename;
};
#endif
|
Jazz86/Group4 | src/Header/FileOperator.h | // Copyright (c) 2021, 鍾淯丞, 周杰仕, 林仁鴻. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GROUP4_SRC_HEADER_FILEOPERATOR_H_
#define GROUP4_SRC_HEADER_FILEOPERATOR_H_
#include <string>
#include "APIHandler.h"
#include "OperateData.h"
#include "ResponseHandler.h"
// File management for client
class FileOperator : public APIHandler {
public:
// Constructor
FileOperator();
// Upload file to server.
int Upload(std::unique_ptr<OperateData> data);
// Down file to client.
int Download(std::unique_ptr<OperateData> data, std::string &file_content);
// Use key "Method" of OperateData to call API
void CallingAPI(std::unique_ptr<OperateData> data) override;
// Not copyable or movable
FileOperator(const FileOperator ©) = delete;
FileOperator &operator=(const FileOperator ©) = delete;
private:
// Use ResponseHandler to call corresponding service
ResponseHandler response_handler;
};
#endif // GROUP4_SRC_HEADER_FILEOPERATOR_H_
|
Jazz86/Group4 | src/Header/HttpListener.h | <reponame>Jazz86/Group4<filename>src/Header/HttpListener.h
// Copyright (c) 2021, 鍾淯丞, 周杰仕, 林仁鴻. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GROUP4_HEADER_HTTPLISTENER_H_
#define GROUP4_HEADER_HTTPLISTENER_H_
#include <memory.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <unistd.h>
#include <functional>
#include <thread>
// Listen specific port and will callback MainManager function when receive
// request
class HttpListener {
public:
// Init instance, callback should pass client file descriptor
void InitInstance(std::function<void(const int &fd)> callback,
const int &port_num);
// Singleton code convention, must bind callback for listening port and
// require listening port
static HttpListener *GetInstance();
// bind specific port to listen
void BindPort(const int &port_num);
// which contains waiting message and do the callback, called by StartListen
// with multithread
void ThreadListen();
// using multithread to listen
void StartListen();
// stop listening and turn off multithread.
void EndListen();
// stop listening
void StopListen();
~HttpListener(void);
// non copyable
HttpListener(HttpListener &cpy) = delete;
HttpListener &operator=(const HttpListener &cpy) = delete;
protected:
// Singleton code convention
HttpListener();
private:
// will be used when listen port accept connection, throwing file descriptor
// to new process. listened message must pass through callback.
std::function<void(const int &)> callback;
// record client
int client_fd;
int server_fd;
bool start_listen;
std::thread listen_thread;
static HttpListener *only_http_listener;
};
#endif
|
Jazz86/Group4 | src/Header/MainManager.h | // Copyright (c) 2021, 鍾淯丞, 周杰仕, 林仁鴻. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef Group4_Header_MainManager_H_
#define Group4_Header_MainManager_H_
#include <arpa/inet.h>
#include <netinet/in.h>
#include <signal.h>
#include <unistd.h>
#include <string>
#include <unordered_map>
#include <vector>
#include "HttpListener.h"
#include "RequestHandler.h"
// will initialize http listener, do multiprocess when listener callback
class MainManager {
public:
// httpListener callback, do fork and new requestHandler to call api, child
// process add to parents vector for managing.
void NewRequest(const int &request_fd);
// requestHandler callback, remove process from parents vector.
// won't be changed after forked.
void EndRequest();
// for managing all processes.
// socket file descripter => pid_t
std::unordered_map<int, pid_t> socket_map;
// get socket_map length
int GetSize();
// Initlize singleton instance
void InitInstance(const uint16_t &port_num);
// used for unit test, passing mock requestHandler
void SetRequestHandler(RequestHandler *request_handler);
// remove process from socket_map by socket
void RemoveBySocket(const int &socket_num);
// remove process from socket_map by pid
void RemoveByPid(const pid_t &p);
// get process by socket
pid_t GetProcess(int socket_num);
// stop listening
void StopListen();
// singleton code convention method, listen port number is required.
static MainManager *GetInstance();
~MainManager(void);
// Delete copy constructor
MainManager(const MainManager &cpy) = delete;
// Delete assignment operator
MainManager &operator=(const MainManager &cpy) = delete;
protected:
// singleton code convention method.
static MainManager *only_mainManager;
// used to record which port is listening, one process will listen one port
// will call httpListener.BindPort()
uint16_t port_num;
// use request_handler as factory pattern
RequestHandler *request_handler;
private:
// singleton code convention method.
MainManager();
};
#endif
|
Jazz86/Group4 | src/Header/OperateData.h | <filename>src/Header/OperateData.h
// Copyright (c) 2021, 鍾淯丞, 周杰仕, 林仁鴻. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GROUP4_SRC_OPERATEDATA_H_
#define GROUP4_SRC_OPERATEDATA_H_
#include <string>
#include <unordered_map>
// This class is a self-defined data structure containing header and body.
// User should choose to use only as request data or response data
// OperateData newData;
// new_data["key"] = "value";
class OperateData {
public:
OperateData();
OperateData(OperateData &right);
// Besides HTTP headers, HTTP request method, Request URL, Status Code
// would store in the header variable.
std::unordered_map<std::string, std::string> header;
// Only contain HTTP body.
std::unordered_map<std::string, std::string> body;
// only used to access body data
std::string &operator[](std::string body_key);
};
#endif
|
Jazz86/Group4 | src/Header/LogHandle.h | // Copyright (c) 2021, 鍾淯丞, 周杰仕, 林仁鴻. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GROUP4_HEADER_LogHandle_H_
#define GROUP4_HEADER_LogHandle_H_
#include <string>
// write error message to local file
class LogHandle {
public:
// singleton code convention method.
static LogHandle *GetInstance();
// record these information of error event to file. If it run successfully, it
// will return 1 else 0.
static int RecordLog(const std::string &time, const std::string &ip,
const std::string &user, const std::string &status_code,
const std::string &message);
// set log_path
void SetLogPath(std::string path);
// non copyable
LogHandle(LogHandle &cpy) = delete;
LogHandle &operator=(LogHandle &cpy) = delete;
private:
// singleton code convention method.
LogHandle();
static LogHandle *only_log_handle;
static std::string log_path;
};
#endif
|
Jazz86/Group4 | src/Header/ResponseHandler.h | // Copyright (c) 2021, 鍾淯丞, 周杰仕, 林仁鴻. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GROUP4_SRC_HEADER_RESPONSEHANDLER_H_
#define GROUP4_SRC_HEADER_RESPONSEHANDLER_H_
#include <memory>
#include <string>
#include "OperateData.h"
// Handle response and call corresponding service
class ResponseHandler {
public:
// Constructor
ResponseHandler();
// Send data and header to corresponding service
void Send(const std::string &for_client_fd,
std::unique_ptr<OperateData> data);
// Not copyable or movable
ResponseHandler(const ResponseHandler ©) = delete;
ResponseHandler &operator=(const ResponseHandler ©) = delete;
};
#endif /* GROUP4_SRC_HEADER_RESPONSEHANDLER_H_ */
|
Jazz86/Group4 | src/Header/RequestParser.h | <gh_stars>0
// Copyright (c) 2021, 鍾淯丞, 周杰仕, 林仁鴻. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GROUP4_SRC_REQUESTPARSER_H_
#define GROUP4_SRC_REQUESTPARSER_H_
#include <memory>
#include <string>
#include "OperateData.h"
// used to make request string to OperateData(JSON like) format.
// string requestStr = "GET /?token=<PASSWORD> HTTP/1.1\n"
// unique_ptr<OperateData> data = RequestParser::ParserHeader(requestStr)
// data will return header and body.
class RequestParser {
public:
// singleton code convention method.
static RequestParser* GetInstance();
// give request string return body / data
std::unique_ptr<OperateData> ParseData(const std::string& request);
protected:
// singleton code convention method.
RequestParser();
private:
static RequestParser* only_request_parser;
};
#endif
|
Jazz86/Group4 | src/Header/Authenticator.h | // Copyright (c) 2021, 鍾淯丞, 周杰仕, 林仁鴻. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef GROUP4_HEADER_AUTHENTICATOR_H_
#define GROUP4_HEADER_AUTHENTICATOR_H_
#include <string>
// used to check if request is send from valid user
// when getting request, requesthandler call
// authenticator::CheckAccount(account, password) check if it's valid. if return
// true then keep handle request, false will deny the request.
class Authenticator {
public:
// singleton code convention method.
static Authenticator* GetInstance();
// check if login is correct
bool CheckAccount(const std::string& account, const std::string& password);
// check if account exist
std::string SearchAccount(const std::string& account);
// non copyable
Authenticator(Authenticator& cpy) = delete;
Authenticator& operator=(Authenticator& cpy) = delete;
protected:
static Authenticator* only_authenticator;
private:
// singleton code convention method.
Authenticator();
};
#endif
|
ProgrammableMatter/particle-firmware | src/avr-common/utils/uc-core/communication-protocol/CommunicationProtocolPackageTypesCtors.h | /**
* Created by <NAME> on 05.07.16
*
* In buffer construction of protocol package related implementation.
*/
#pragma once
#include "./CommunicationProtocol.h"
#include "./CommunicationProtocolPackageTypes.h"
#include "uc-core/particle/Globals.h"
#include "uc-core/parity/Parity.h"
#include "uc-core/configuration/interrupts/LocalTime.h"
/**
* Constructor function: builds the protocol package at the given port's buffer.
* @param txPort the port reference where to buffer the package at
* @param localAddressRow the local address row
* @param localAddressColumn the local address column
*/
void constructEnumeratePackage(TxPort *const txPort,
const uint8_t localAddressRow,
const uint8_t localAddressColumn) {
clearTransmissionPortBuffer(txPort);
// clearBufferBytes(&txPort->buffer);
Package *package = (Package *) txPort->buffer.bytes;
package->asEnumerationPackage.header.startBit = 1;
package->asEnumerationPackage.header.id = PACKAGE_HEADER_ID_TYPE_ENUMERATE;
package->asEnumerationPackage.header.isRangeCommand = false;
package->asEnumerationPackage.header.enableBroadcast = false;
// on local bread crumb available or origin node
if (ParticleAttributes.protocol.hasNetworkGeometryDiscoveryBreadCrumb
|| ParticleAttributes.node.type == NODE_TYPE_ORIGIN) {
// on tx east or tx south and no east connectivity
if (txPort == &ParticleAttributes.communication.ports.tx.east
|| (txPort == &ParticleAttributes.communication.ports.tx.south
&& !ParticleAttributes.discoveryPulseCounters.east.isConnected)) {
package->asEnumerationPackage.hasNetworkGeometryDiscoveryBreadCrumb = true;
}
else {
package->asEnumerationPackage.hasNetworkGeometryDiscoveryBreadCrumb = false;
}
}
package->asEnumerationPackage.addressRow = localAddressRow;
package->asEnumerationPackage.addressColumn = localAddressColumn;
setBufferDataEndPointer(&txPort->dataEndPos, EnumerationPackageBufferPointerSize);
setEvenParityBit(txPort);
}
/**
* Constructor function: builds the protocol package at the given port's buffer.
* @param txPort the port reference where to buffer the package at
*/
void constructEnumerationACKPackage(TxPort *const txPort) {
clearTransmissionPortBuffer(txPort);
Package *package = (Package *) txPort->buffer.bytes;
package->asACKPackage.startBit = 1;
package->asACKPackage.enableBroadcast = false;
// package->asACKPackage.enableBroadcast = true;
package->asACKPackage.id = PACKAGE_HEADER_ID_TYPE_ACK;
package->asACKPackage.isRangeCommand = false;
setBufferDataEndPointer(&txPort->dataEndPos, AckPackagePointerSize);
setEvenParityBit(txPort);
}
/**
* Constructor function: builds the protocol package at north port's buffer.
*/
void constructEnumerationACKWithAddressToParentPackage(void) {
clearTransmissionPortBuffer(ParticleAttributes.directionOrientedPorts.north.txPort);
Package *package = (Package *) ParticleAttributes.directionOrientedPorts.north.txPort->buffer.bytes;
package->asACKWithLocalAddress.header.startBit = 1;
package->asACKWithLocalAddress.header.id = PACKAGE_HEADER_ID_TYPE_ACK_WITH_DATA;
package->asACKWithLocalAddress.header.isRangeCommand = false;
package->asACKWithLocalAddress.addressRow = ParticleAttributes.node.address.row;
package->asACKWithLocalAddress.addressColumn = ParticleAttributes.node.address.column;
setBufferDataEndPointer(&ParticleAttributes.communication.ports.tx.north.dataEndPos,
AckWithAddressPackageBufferPointerSize);
setEvenParityBit(&ParticleAttributes.communication.ports.tx.north);
}
/**
* Constructor function: builds the protocol package at the given port's buffer.
* @param txPort the port reference where to buffer the package at
*/
//void constructSyncTimePackage(TxPort *const txPort) {
void constructSyncTimePackage(TxPort *const txPort, bool forceTimePeriodUpdate) {
clearTransmissionPortBuffer(txPort);
Package *package = (Package *) txPort->buffer.bytes;
package->asSyncTimePackage.header.startBit = 1;
package->asSyncTimePackage.header.id = PACKAGE_HEADER_ID_TYPE_SYNC_TIME;
package->asSyncTimePackage.header.isRangeCommand = true;
package->asSyncTimePackage.header.enableBroadcast = false;
// package->asSyncTimePackage.header.enableBroadcast = true;
uint8_t sreg = SREG;
MEMORY_BARRIER;
CLI;
MEMORY_BARRIER;
const uint16_t now = TIMER_TX_RX_COUNTER_VALUE;
// const bool isNewTimerCounterShiftUpdateable = ParticleAttributes.localTime.isNewTimerCounterShiftUpdateable;
const uint16_t compareValue = LOCAL_TIME_INTERRUPT_COMPARE_VALUE;
package->asSyncTimePackage.timePeriod = ParticleAttributes.localTime.numTimePeriodsPassed;
package->asSyncTimePackage.localTimeTrackingPeriodInterruptDelay = ParticleAttributes.localTime.timePeriodInterruptDelay;
MEMORY_BARRIER;
SREG = sreg;
MEMORY_BARRIER;
// if (isNewTimerCounterShiftUpdateable) {
// compareValue += ParticleAttributes.localTime.newTimerCounterShift;
// }
// transmit the delay until the next local time tracking ISR triggers
package->asSyncTimePackage.delayUntilNextTimeTrackingIsr = compareValue - now;
// // TODO: evaluation code
// if (forceTimePeriodUpdate) {
// TEST_POINT3_HI;
// TEST_POINT3_LO;
// }
package->asSyncTimePackage.forceTimePeriodUpdate = forceTimePeriodUpdate;
package->asSyncTimePackage.stuffing = 42;
package->asSyncTimePackage.endBit = 0; // Must be UNset, do not change!
// for evaluation purpose
setBufferDataEndPointer(&txPort->dataEndPos, TimePackageBufferPointerSize);
setEvenParityBit(txPort);
// DEBUG_INT16_OUT(TIMER_TX_RX_COUNTER_VALUE);
}
/**
* Constructor function: builds the protocol package at the north port's buffer.
* @param row the network geometry rows
* @param column the network geometry columns
*/
void constructAnnounceNetworkGeometryPackage(uint8_t row, uint8_t column) {
clearTransmissionPortBuffer(ParticleAttributes.directionOrientedPorts.north.txPort);
Package *package = (Package *) ParticleAttributes.directionOrientedPorts.north.txPort->buffer.bytes;
package->asAnnounceNetworkGeometryPackage.header.startBit = 1;
package->asAnnounceNetworkGeometryPackage.header.id = PACKAGE_HEADER_ID_TYPE_NETWORK_GEOMETRY_RESPONSE;
package->asAnnounceNetworkGeometryPackage.header.isRangeCommand = false;
// package->asAnnounceNetworkGeometryPackage.header.enableBroadcast = true;
package->asAnnounceNetworkGeometryPackage.header.enableBroadcast = false;
package->asAnnounceNetworkGeometryPackage.rows = row;
package->asAnnounceNetworkGeometryPackage.columns = column;
setBufferDataEndPointer(&ParticleAttributes.communication.ports.tx.north.dataEndPos,
AnnounceNetworkGeometryPackageBufferPointerSize);
setEvenParityBit(&ParticleAttributes.communication.ports.tx.north);
}
/**
* Constructor function: builds the protocol package at the given port's buffer.
* @param txPort the port reference where to buffer the package at
* @param rows the new network geometry rows
* @param columns the new network geometry columns
*/
void constructSetNetworkGeometryPackage(TxPort *const txPort, const uint8_t rows,
const uint8_t columns) {
clearTransmissionPortBuffer(txPort);
Package *package = (Package *) txPort->buffer.bytes;
package->asSetNetworkGeometryPackage.header.startBit = 1;
package->asSetNetworkGeometryPackage.header.id = PACKAGE_HEADER_ID_TYPE_SET_NETWORK_GEOMETRY;
package->asSetNetworkGeometryPackage.header.isRangeCommand = false;
package->asSetNetworkGeometryPackage.header.enableBroadcast = false;
// package->asSetNetworkGeometryPackage.header.enableBroadcast = true;
package->asSetNetworkGeometryPackage.rows = rows;
package->asSetNetworkGeometryPackage.columns = columns;
setBufferDataEndPointer(&txPort->dataEndPos, SetNetworkGeometryPackageBufferPointerSize);
setEvenParityBit(txPort);
}
/**
* Constructor function: builds the protocol package at the given port's buffer.
* Time stamp and duration units can be deduced from the local time tracking implementation.
* For more details see {@link LocalTimeTracking} struct.
* @param txPort the port reference where to buffer the package at
* @param address the destination node address
* @param wires wire flags, note: just north wires are considered
* @param startTimeStamp the time stamp when heating starts, see also {@link LocalTimeTracking}
* @param duration the heating period duration, see also {@link LocalTimeTracking}
*/
void constructHeatWiresPackage(TxPort *const txPort,
const NodeAddress *const address,
const Actuators *const wires,
const uint16_t startTimeStamp,
const uint16_t duration) {
clearTransmissionPortBuffer(txPort);
Package *package = (Package *) txPort->buffer.bytes;
package->asHeatWiresPackage.header.startBit = 1;
package->asHeatWiresPackage.header.id = PACKAGE_HEADER_ID_TYPE_HEAT_WIRES;
package->asHeatWiresPackage.header.isRangeCommand = false;
package->asHeatWiresPackage.header.enableBroadcast = false;
package->asHeatWiresPackage.addressRow = address->row;
package->asHeatWiresPackage.addressColumn = address->column;
package->asHeatWiresPackage.startTimeStamp = startTimeStamp;
package->asHeatWiresPackage.durationLsb = duration & 0x00ff;
package->asHeatWiresPackage.durationMsb = (duration & 0x0300) >> 8;
package->asHeatWiresPackage.northLeft = wires->northLeft;
package->asHeatWiresPackage.northRight = wires->northRight;
setBufferDataEndPointer(&txPort->dataEndPos, HeatWiresPackageBufferPointerSize);
setEvenParityBit(txPort);
}
/**
* Constructor function: builds the protocol package at the given port's buffer.
* Time stamp and duration units can be deduced from the local time tracking implementation.
* For more details see {@link LocalTimeTracking} struct.
* @param txPort the port reference where to buffer the package at
* @param address the destination node address
* @param wires wire flags, note: just north wires are considered
* @param startTimeStamp the time stamp when heating starts, see also {@link LocalTimeTracking}
* @param duration the heating period duration, see also {@link LocalTimeTracking}
*/
void constructHeatWiresRangePackage(TxPort *const txPort,
const NodeAddress *const nodeAddressTopLeft,
const NodeAddress *const nodeAddressBottomRight,
const Actuators *const wires,
const uint16_t startTimeStamp,
const uint16_t duration) {
clearTransmissionPortBuffer(txPort);
Package *package = (Package *) txPort->buffer.bytes;
package->asHeatWiresRangePackage.header.startBit = 1;
package->asHeatWiresRangePackage.header.id = PACKAGE_HEADER_ID_TYPE_HEAT_WIRES;
package->asHeatWiresRangePackage.header.isRangeCommand = true;
package->asHeatWiresRangePackage.header.enableBroadcast = false;
package->asHeatWiresRangePackage.addressRow0 = nodeAddressTopLeft->row;
package->asHeatWiresRangePackage.addressColumn0 = nodeAddressTopLeft->column;
package->asHeatWiresRangePackage.addressRow1 = nodeAddressBottomRight->row;
package->asHeatWiresRangePackage.addressColumn1 = nodeAddressBottomRight->column;
package->asHeatWiresRangePackage.startTimeStamp = startTimeStamp;
package->asHeatWiresRangePackage.durationLsb = duration & 0x00ff;
package->asHeatWiresRangePackage.durationMsb = (duration & 0x0300) >> 8;
package->asHeatWiresRangePackage.northLeft = wires->northLeft;
package->asHeatWiresRangePackage.northRight = wires->northRight;
setBufferDataEndPointer(&txPort->dataEndPos, HeatWiresRangePackageBufferPointerSize);
setEvenParityBit(txPort);
}
/**
* Constructor function: builds the protocol package at the given port's buffer.
* @param txPort the port reference where to buffer the package at
*/
void constructHeaderPackage(TxPort *const txPort) {
clearTransmissionPortBuffer(txPort);
Package *package = (Package *) txPort->buffer.bytes;
package->asHeader.startBit = 1;
package->asHeader.id = PACKAGE_HEADER_ID_HEADER;
package->asHeader.isRangeCommand = false;
package->asHeader.enableBroadcast = false;
setBufferDataEndPointer(&txPort->dataEndPos, HeaderPackagePointerSize);
setEvenParityBit(txPort);
}
/**
* Constructor function: builds the protocol package at the given port's buffer.
* @param txPort the port reference where to buffer the package at
* @param heatingPowerLevel the power level applied to the actuators when actuating
*/
void constructHeatWiresModePackage(TxPort *const txPort,
const HeatingLevelType heatingPowerLevel) {
clearTransmissionPortBuffer(txPort);
Package *package = (Package *) txPort->buffer.bytes;
package->asHeatWiresModePackage.header.startBit = 1;
package->asHeatWiresModePackage.header.id = PACKAGE_HEADER_ID_TYPE_HEAT_WIRES_MODE;
package->asHeatWiresModePackage.header.enableBroadcast = false;
package->asHeatWiresModePackage.heatMode = heatingPowerLevel;
setBufferDataEndPointer(&txPort->dataEndPos, HeatWiresModePackageBufferPointerSize);
setEvenParityBit(txPort);
}
|
ProgrammableMatter/particle-firmware | src/avr-common/utils/uc-core/synchronization/SynchronizationTypesCtors.h | <reponame>ProgrammableMatter/particle-firmware
/**
* @author <NAME> 24.09.2016
*
* Synchronization types constructors.
*/
#pragma once
#include "uc-core/configuration/synchronization/SynchronizationTypesCtors.h"
#include "uc-core/configuration/synchronization/Synchronization.h"
#include "uc-core/configuration/communication/Communication.h"
#include "SynchronizationTypes.h"
#include "LeastSquareRegressionTypesCtors.h"
#include "SampleFifoTypesCtors.h"
//#if defined(SYNCHRONIZATION_ENABLE_ADAPTIVE_OUTLIER_REJECTION) || defined(SYNCHRONIZATION_ENABLE_SIGMA_DEPENDENT_OUTLIER_REJECTION)
void constructAdaptiveSampleRejection(AdaptiveSampleRejection *const o) {
o->rejected = 0;
o->accepted = 0;
o->currentAcceptedDeviation = 1000;
o->outlierLowerBound = 0;
o->outlierUpperBound = 0;
o->isOutlierRejectionBoundValid = false;
}
//#endif
/**
* constructor function
* @param o reference to the object to construct
*/
void constructTimeSynchronization(TimeSynchronization *const o) {
// constructSyncPackageTiming(&o->syncPackageTiming);
#if defined(SYNCHRONIZATION_ENABLE_ADAPTIVE_OUTLIER_REJECTION) || defined(SYNCHRONIZATION_ENABLE_SIGMA_DEPENDENT_OUTLIER_REJECTION)
constructAdaptiveSampleRejection(&o->adaptiveSampleRejection);
#endif
constructSamplesFifoBuffer(&o->timeIntervalSamples);
#ifdef SYNCHRONIZATION_STRATEGY_LEAST_SQUARE_LINEAR_FITTING
constructLeastSquareRegressionResult(&o->fittingFunction);
#endif
o->mean = 0;
o->meanWithoutOutlier = 0;
o->meanWithoutMarkedOutlier = 0;
#ifdef SYNCHRONIZATION_STRATEGY_MEAN_ENABLE_ONLINE_CALCULATION
o->__unnormalizedCumulativeMean = 0;
o->__unnormalizedCumulativeMeanWithoutMarkedOutlier = 0;
o->__numberCumulatedValuesWithoutMarkedOutlier = 0;
#endif
#ifdef SYNCHRONIZATION_STRATEGY_PROGRESSIVE_MEAN
// fake a default sample as start value
o->progressiveMean = (uint16_t) (roundf(SYNCHRONIZATION_PDU_NUMBER_CLOCKS_IN_MEASURED_INTERVAL *
COMMUNICATION_DEFAULT_TX_RX_CLOCK_DELAY))
- TIME_SYNCHRONIZATION_SAMPLE_OFFSET;
#endif
o->variance = 0;
o->stdDeviance = 0;
o->fastSyncPackageSeparation = SYNCHRONIZATION_TYPES_CTORS_FAST_SYNC_PACKAGE_SEPARATION;
o->syncPackageSeparation = SYNCHRONIZATION_TYPES_CTORS_SYNC_PACKAGE_SEPARATION;
o->totalFastSyncPackagesToTransmit = SYNCHRONIZATION_TYPES_CTORS_TOTAL_FAST_SYNC_PACKAGES;
o->isNextSyncPackageTransmissionEnabled = false;
o->isNextSyncPackageTimeUpdateRequest = false;
}
|
ProgrammableMatter/particle-firmware | src/avr-common/utils/uc-core/scheduler/SchedulerTypes.h | /*
* @author <NAME> 18.09.2016
*
* Scheduler state definition.
*/
#pragma once
#include <stdint.h>
#include "uc-core/particle/types/ParticleStateTypes.h"
#include "uc-core/configuration/Scheduler.h"
typedef struct SchedulerTask {
uint16_t startTimestamp;
uint16_t endTimestamp;
uint16_t reScheduleDelay;
uint16_t numCalls;
StateType state;
NodeType nodeType;
void (*startAction)(struct SchedulerTask *const);
void (*endAction)(struct SchedulerTask *const);
uint8_t isTimeLimited : 1;
uint8_t isStateLimited : 1;
uint8_t isEnabled : 1;
uint8_t isExecuted : 1;
uint8_t isStarted : 1;
uint8_t isStartActionExecuted : 1;
uint8_t isEndActionExecuted : 1;
uint8_t isCyclicTask: 1;
uint8_t __isExecutionRetained: 1;
uint8_t isNodeTypeLimited : 1;
uint8_t isCountLimitedTask : 1;
uint8_t isLastCall : 1;
uint8_t __pad : 4;
} SchedulerTask;
typedef struct Scheduler {
SchedulerTask tasks[SCHEDULER_MAX_TASKS];
uint16_t lastCallToScheduler;
} Scheduler;
|
ProgrammableMatter/particle-firmware | src/avr-common/utils/uc-core/configuration/interrupts/ActuationTimer.h | /**
* @author <NAME> 20.07.2016
*
* Actuator interrupt related configuration.
*/
#pragma once
#include "TimerCounter0.h"
#include "uc-core/configuration/Actuation.h"
/**
* actuation interrupt macros
*/
#if defined(__AVR_ATtiny1634__) || defined(__AVR_ATmega16__)
# define __ACTUATOR_COMPARE_VALUE_SETUP(compareValue) \
__TIMER0_INTERRUPT_COMPARE_VALUE_SETUP(compareValue)
# define __ACTUATOR_TIMER_VALUE_SETUP(compareValue) \
(__TIMER0_INTERRUPT_TIMER_VALUE_SETUP(compareValue))
# define __ACTUATOR_COUNTER_PRESCALER_VALUE \
__TIMER_COUNTER_PRESCALER_64
# define __ACTUATOR_COUNTER_PRESCALER_ENABLE \
__TIMER0_INTERRUPT_PRESCALER_ENABLE(__ACTUATOR_COUNTER_PRESCALER_VALUE)
# define __ACTUATOR_COUNTER_PRESCALER_DISABLE \
__TIMER0_INTERRUPT_PRESCALER_DISABLE
# define ACTUATOR_INTERRUPT_SET_PWM_DUTY_CYCLE_STRONG \
__ACTUATOR_COMPARE_VALUE_SETUP(ACTUATION_COMPARE_VALUE_POWER_STRONG)
# define ACTUATOR_INTERRUPT_SET_PWM_DUTY_CYCLE_MEDIUM \
__ACTUATOR_COMPARE_VALUE_SETUP(ACTUATION_COMPARE_VALUE_POWER_MEDIUM)
# define ACTUATOR_INTERRUPT_SET_PWM_DUTY_CYCLE_WEAK \
__ACTUATOR_COMPARE_VALUE_SETUP(ACTUATION_COMPARE_VALUE_POWER_WEAK)
# define ACTUATOR_INTERRUPT_ENABLE \
__ACTUATOR_TIMER_VALUE_SETUP(UINT8_MAX); \
__ACTUATOR_COUNTER_PRESCALER_ENABLE
# define ACTUATOR_INTERRUPT_DISABLE \
__ACTUATOR_COUNTER_PRESCALER_DISABLE
# define ACTUATOR_INTERRUPT_SETUP \
ACTUATOR_INTERRUPT_DISABLE; \
__TIMER0_OVERFLOW_INTERRUPT_DISABLE; \
__TIMER0_INTERRUPT_OUTPUT_MODE_DISCONNECTED_SETUP; \
__TIMER0_INTERRUPT_WAVE_GENERATION_MODE_PWM_PHASE_CORRECT_SETUP; \
__ACTUATOR_TIMER_VALUE_SETUP(0); \
__ACTUATOR_COMPARE_VALUE_SETUP(ACTUATION_COMPARE_VALUE_POWER_MEDIUM); \
__TIMER0_COMPARE_INTERRUPT_ENABLE
# else
# error
# endif
|
ProgrammableMatter/particle-firmware | src/avr-common/utils/uc-core/particle/types/DiscoveryPulseCountersCtors.h | /*
* @author <NAME> 09.10.2016
*
* Discovery types constructor implementation.
*/
#pragma once
#include "DiscoveryPulseCountersTypes.h"
#include "uc-core/discovery/DiscoveryTypesCtors.h"
/**
* constructor function
* @param o the object to construct
*/
void constructDiscoveryPulseCounters(DiscoveryPulseCounters *const o) {
constructDiscoveryPulseCounter(&o->north);
constructDiscoveryPulseCounter(&o->east);
constructDiscoveryPulseCounter(&o->south);
o->loopCount = 0;
}
|
ProgrammableMatter/particle-firmware | src/avr-common/utils/uc-core/particle/types/AlertsTypesCtors.h | <reponame>ProgrammableMatter/particle-firmware
/*
* @author <NAME> 09.10.2016
*
* Alerts types constructor implementation.
*/
#pragma once
#include "AlertsTypes.h"
/**
* constructor function
* @param o the object to construct
*/
void constructAlerts(Alerts *const o) {
o->isRxBufferOverflowEnabled = false;
o->isRxParityErrorEnabled = false;
o->isGenericErrorEnabled = false;
} |
ProgrammableMatter/particle-firmware | src/avr-common/utils/uc-core/evaluation/EvaluationTypesCtors.h | <gh_stars>1-10
/*
* @author <NAME> 15.10.2016
*
* Evaluation types constructor implementation.
*/
#pragma once
#include "EvaluationTypes.h"
#include "uc-core/configuration/Evaluation.h"
#ifdef EVALUATION_ENABLE_FLUCTUATE_CPU_FREQUENCY_ON_PURPOSE
/**
* constructor function
* @param o the object to construct
**/
void constructRuntimeOscCalibration(RuntimeOscCalibration *const o) {
o->initialOscCal = EVALUATION_OSC_CALIBRATION_REGISTER;
o->step = EVALUATION_OSCCAL_STEP;
o->minOscCal = o->initialOscCal;
o->maxOscCal = o->initialOscCal;
if (o->initialOscCal > EVALUATION_OSCCAL_MIN_OFFSET) {
o->minOscCal = o->initialOscCal - EVALUATION_OSCCAL_MIN_OFFSET;
}
if ((UINT8_MAX - EVALUATION_OSCCAL_MAX_OFFSET) > o->initialOscCal) {
o->maxOscCal = o->initialOscCal + EVALUATION_OSCCAL_MIN_OFFSET;
}
o->isDecrementing = false;
}
#endif
/**
* constructor function
* @param o the object to construct
**/
void constructEvaluation(Evaluation *const o) {
#if defined(EVALUATION_SIMPLE_SYNC_AND_ACTUATION) || defined(EVALUATION_SYNC_CYCLICALLY)
o->nextHeatWiresAddress.row = 1;
o->nextHeatWiresAddress.column = 1;
#endif
#ifdef EVALUATION_ENABLE_FLUCTUATE_CPU_FREQUENCY_ON_PURPOSE
constructRuntimeOscCalibration(&o->oscCalibration);
#endif
#ifdef EVALUATION_SYNC_WITH_CYCLIC_UPDATE_TIME_REQUEST_FLAG_THEN_ACTUATE_ONCE
o->totalSentSyncPackages = 0;
#endif
}
|
ProgrammableMatter/particle-firmware | src/avr-common/utils/common/common.h | <gh_stars>1-10
/**
* @author <NAME> 2011
*/
#pragma once
#include <inttypes.h>
#include "PortInteraction.h"
#include <stdbool.h>
#include <stddef.h>
#define forever while(1)
#define SEI SREG setBit bit(SREG_I)
#define CLI SREG unsetBit bit(SREG_I)
/**
* memory barrier to suppress code motion around the barrier
* http://blog.regehr.org/archives/28
*/
#define MEMORY_BARRIER asm volatile ("" : : : "memory")
/**
* Convenience macro for "no operation" instruction.
*/
#define NOOP asm ("nop") |
ProgrammableMatter/particle-firmware | src/avr-common/utils/uc-core/synchronization/SynchronizationTypes.h | <filename>src/avr-common/utils/uc-core/synchronization/SynchronizationTypes.h
/**
* @author <NAME> 24.09.2016
*
* Synchronization related types.
*/
#pragma once
#include <stdint.h>
#include "BasicCalculationTypes.h"
#include "uc-core/configuration/synchronization/Synchronization.h"
#include "LeastSquareRegressionTypes.h"
#include "SampleFifoTypes.h"
//#if defined(SYNCHRONIZATION_ENABLE_ADAPTIVE_OUTLIER_REJECTION) || defined(SYNCHRONIZATION_ENABLE_SIGMA_DEPENDENT_OUTLIER_REJECTION)
typedef struct AdaptiveSampleRejection {
uint16_t rejected;
uint16_t accepted;
int16_t currentAcceptedDeviation; // must be signed!
/**
* Lower bound for outlier to be rejected.
*/
SampleValueType outlierLowerBound;
/**
* Upper bound for outlier to be rejected.
*/
SampleValueType outlierUpperBound;
/**
* switch enabled when outlier rejection boundary is valid
*/
uint8_t isOutlierRejectionBoundValid : 1;
uint8_t __pad : 7;
} AdaptiveSampleRejection;
//#endif
typedef struct TimeSynchronization {
// SyncPackageTiming syncPackageTiming;
//#if defined(SYNCHRONIZATION_ENABLE_ADAPTIVE_OUTLIER_REJECTION) || defined(SYNCHRONIZATION_ENABLE_SIGMA_DEPENDENT_OUTLIER_REJECTION)
AdaptiveSampleRejection adaptiveSampleRejection;
//#endif
SamplesFifoBuffer timeIntervalSamples;
#ifdef SYNCHRONIZATION_STRATEGY_LEAST_SQUARE_LINEAR_FITTING
LeastSquareRegressionResult fittingFunction;
#endif
/**
* mean of all values in FiFo
*/
CalculationType mean;
/**
* mean of all values in FiFo within µ+/-f*σ
*/
CalculationType meanWithoutOutlier;
/**
* mean of all values in FiFo being within the current µ+/-f*σ when entered the FiFo
*/
CalculationType meanWithoutMarkedOutlier;
#ifdef SYNCHRONIZATION_STRATEGY_MEAN_ENABLE_ONLINE_CALCULATION
/**
* The cumulative unnormalized mean field is used to calculate a step-wise mean
* by just observing the incoming and outgoing FiFo values without
* the need for a complete FiFo iteration.
*/
CumulationType __unnormalizedCumulativeMean;
CumulationType __unnormalizedCumulativeMeanWithoutMarkedOutlier;
IndexType __numberCumulatedValuesWithoutMarkedOutlier;
#endif
#ifdef SYNCHRONIZATION_STRATEGY_PROGRESSIVE_MEAN
/**
* Very simple syn. implementation: The progressive mean has kind of knowledge of previous values.
*/
CalculationType progressiveMean;
#endif
/**
* samples' variance
*/
CalculationType variance;
/**
* samples' standard deviation
*/
CalculationType stdDeviance;
/**
* next local time stamp when transmission is to be initialized
*/
// uint16_t nextSyncPackageTransmissionStartTime;
/**
* default sync package delay in between packages
*/
uint16_t syncPackageSeparation;
/**
* sync. package separation during fast sync. phase; usually much lower than default sync package separation
*/
uint16_t fastSyncPackageSeparation;
/**
* number of packages to transmit for fast synchronization
*/
uint16_t totalFastSyncPackagesToTransmit;
/**
* barrier for sync package scheduling
*/
uint8_t isNextSyncPackageTransmissionEnabled : 1;
uint8_t isNextSyncPackageTimeUpdateRequest : 1;
uint8_t __pad : 6;
} TimeSynchronization; |
ProgrammableMatter/particle-firmware | src/avr-common/utils/uc-core/configuration/Scheduler.h | <reponame>ProgrammableMatter/particle-firmware<gh_stars>1-10
/**
* @author <NAME> 11.10.2016
*
* Scheduler related arguments.
*/
#pragma once
/**
* Size of the task array the scheduler keeps track of.
*/
#define SCHEDULER_MAX_TASKS 5
/**
* Task array id arguments:
*/
#define SCHEDULER_TASK_ID_ENABLE_ALERTS ((uint8_t)0)
#define SCHEDULER_TASK_ID_SETUP_LEDS ((uint8_t)1)
#define SCHEDULER_TASK_ID_SYNC_PACKAGE ((uint8_t)2)
#define SCHEDULER_TASK_ID_HEARTBEAT_LED_TOGGLE ((uint8_t)3)
#define SCHEDULER_TASK_ID_HEAT_WIRES ((uint8_t)4)
|
ProgrammableMatter/particle-firmware | src/avr-common/utils/uc-core/communication-protocol/Interpreter.h | /**
* Created by <NAME> on 25.05.2016
*
* Interpreter implementation.
*/
#pragma once
#include "CommunicationProtocolTypes.h"
#include "Commands.h"
#include "uc-core/parity/Parity.h"
#include "uc-core/time/Time.h"
/**
* Interprets reception in wait for being enumerate states.
* @param rxPort the port to interpret data from
* @param commPortState port's communication state
*/
static void __interpretWaitForBeingEnumeratedReception(RxPort *const rxPort,
CommunicationProtocolPortState *const commPortState) {
Package *package = (Package *) rxPort->buffer.bytes;
// interpret according to local reception protocol state
switch (commPortState->receptionistState) {
// on received address information
case COMMUNICATION_RECEPTIONIST_STATE_TYPE_RECEIVE:
// on address package
if (//isEvenParity(rxPort) &&
equalsPackageSize(&rxPort->buffer.pointer, EnumerationPackageBufferPointerSize) &&
package->asHeader.id == PACKAGE_HEADER_ID_TYPE_ENUMERATE) {
// TODO: evaluation code
if (!isEvenParity(rxPort)) {
clearReceptionPortBuffer(rxPort);
break;
}
executeSetLocalAddress(&package->asEnumerationPackage);
// send ack with local address back
// DEBUG_CHAR_OUT('a');
commPortState->receptionistState = COMMUNICATION_RECEPTIONIST_STATE_TYPE_TRANSMIT_ACK;
}
clearReceptionPortBuffer(rxPort);
break;
// on received ack
case COMMUNICATION_RECEPTIONIST_STATE_TYPE_WAIT_FOR_RESPONSE:
if (// isEvenParity(rxPort) &&
equalsPackageSize(&rxPort->buffer.pointer, AckPackagePointerSize) &&
package->asACKPackage.id == PACKAGE_HEADER_ID_TYPE_ACK) {
// TODO: evaluation code
if (!isEvenParity(rxPort)) {
clearReceptionPortBuffer(rxPort);
break;
}
// DEBUG_CHAR_OUT('d');
ParticleAttributes.protocol.isBroadcastEnabled = package->asACKPackage.enableBroadcast;
ParticleAttributes.node.state = STATE_TYPE_LOCALLY_ENUMERATED;
commPortState->receptionistState = COMMUNICATION_RECEPTIONIST_STATE_TYPE_IDLE;
}
clearReceptionPortBuffer(rxPort);
break;
case COMMUNICATION_RECEPTIONIST_STATE_TYPE_IDLE:
case COMMUNICATION_RECEPTIONIST_STATE_TYPE_TRANSMIT_ACK:
case COMMUNICATION_RECEPTIONIST_STATE_TYPE_TRANSMIT_ACK_WAIT_TX_FINISHED:
clearReceptionPortBuffer(rxPort);
break;
}
}
/**
* Interpret received packages in working state (idle state).
* @param rxPort the port to interpret data from
*/
static void __interpretReceivedPackage(const DirectionOrientedPort *const port) {
Package *package = (Package *) port->rxPort->buffer.bytes;
switch (package->asHeader.id) {
case PACKAGE_HEADER_ID_TYPE_SYNC_TIME:
if (isEvenParity(port->rxPort) &&
equalsPackageSize(&port->rxPort->buffer.pointer, TimePackageBufferPointerSize)) {
executeSynchronizeLocalTimePackage(&package->asSyncTimePackage, &port->rxPort->buffer);
}
break;
case PACKAGE_HEADER_ID_TYPE_NETWORK_GEOMETRY_RESPONSE:
if (isEvenParity(port->rxPort) &&
equalsPackageSize(&port->rxPort->buffer.pointer,
AnnounceNetworkGeometryPackageBufferPointerSize)) {
executeAnnounceNetworkGeometryPackage(&package->asAnnounceNetworkGeometryPackage);
}
break;
case PACKAGE_HEADER_ID_TYPE_SET_NETWORK_GEOMETRY:
if (isEvenParity(port->rxPort) &&
equalsPackageSize(&port->rxPort->buffer.pointer,
SetNetworkGeometryPackageBufferPointerSize)) {
executeSetNetworkGeometryPackage(&package->asSetNetworkGeometryPackage);
}
break;
case PACKAGE_HEADER_ID_TYPE_HEAT_WIRES:
if (isEvenParity(port->rxPort)) {
if (package->asHeader.isRangeCommand) {
if (equalsPackageSize(&port->rxPort->buffer.pointer,
HeatWiresRangePackageBufferPointerSize)) {
executeHeatWiresRangePackage(&package->asHeatWiresRangePackage);
}
} else {
if (equalsPackageSize(&port->rxPort->buffer.pointer, HeatWiresPackageBufferPointerSize)) {
executeHeatWiresPackage(&package->asHeatWiresPackage);
}
}
}
break;
case PACKAGE_HEADER_ID_HEADER:
if (isEvenParity(port->rxPort) &&
equalsPackageSize(&port->rxPort->buffer.pointer, HeaderPackagePointerSize)) {
executeHeaderPackage(&package->asHeader);
}
break;
case PACKAGE_HEADER_ID_TYPE_HEAT_WIRES_MODE:
if (isEvenParity(port->rxPort) &&
equalsPackageSize(&port->rxPort->buffer.pointer, HeatWiresModePackageBufferPointerSize)) {
executeHeatWiresModePackage(&package->asHeatWiresModePackage);
}
break;
default:
DEBUG_CHAR_OUT('u');
break;
}
clearReceptionPortBuffer(port->rxPort);
}
/**
* Interprets reception buffer in neighbour enumeration states.
* @param rxPort the port to interpret data from
* @param commPortState port's communication state
* @param expectedRemoteAddressRow the expected remote address row
* @param expectedRemoteAddressColumn the expected remote address column
*/
static void __interpretEnumerateNeighbourAckReception(RxPort *const rxPort,
CommunicationProtocolPortState *const commPortState,
const uint8_t expectedRemoteAddressRow,
const uint8_t expectedRemoteAddressColumn) {
// DEBUG_INT16_OUT(expectedRemoteAddressRow);
// DEBUG_INT16_OUT(ParticleAttributes.node.address.row);
// DEBUG_INT16_OUT(expectedRemoteAddressColumn);
// DEBUG_INT16_OUT(ParticleAttributes.node.address.column);
volatile Package *package = (Package *) rxPort->buffer.bytes;
switch (commPortState->initiatorState) {
// on ack wih remote address
case COMMUNICATION_INITIATOR_STATE_TYPE_WAIT_FOR_RESPONSE:
// on ack with data
if (isEvenParity(rxPort) &&
equalsPackageSize(&rxPort->buffer.pointer, AckWithAddressPackageBufferPointerSize) &&
package->asHeader.id == PACKAGE_HEADER_ID_TYPE_ACK_WITH_DATA) {
// on correct address
if (expectedRemoteAddressRow == package->asACKWithRemoteAddress.addressRow &&
expectedRemoteAddressColumn == package->asACKWithRemoteAddress.addressColumn) {
// DEBUG_CHAR_OUT('D');
commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK;
} else { // on wrong address, restart transmission
// DEBUG_CHAR_OUT('V');
// DEBUG_CHAR_OUT('T');
commPortState->initiatorState = COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT;
}
}
clearReceptionPortBuffer(rxPort);
break;
case COMMUNICATION_INITIATOR_STATE_TYPE_IDLE:
case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT:
case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_WAIT_FOR_TX_FINISHED:
case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK:
case COMMUNICATION_INITIATOR_STATE_TYPE_TRANSMIT_ACK_WAIT_FOR_TX_FINISHED:
break;
}
}
/**
* Interprets reception buffer in respect to the current particle state.
* @param rxPort the port to interpret data from
*/
static void interpretRxBuffer(DirectionOrientedPort *const port) {
DEBUG_CHAR_OUT('I');
ParticleAttributes.protocol.isLastReceptionInterpreted = false;
switch (ParticleAttributes.node.state) {
case STATE_TYPE_WAIT_FOR_BEING_ENUMERATED:
__interpretWaitForBeingEnumeratedReception(port->rxPort,
port->protocol);
break;
case STATE_TYPE_ENUMERATING_EAST_NEIGHBOUR:
__interpretEnumerateNeighbourAckReception(port->rxPort,
port->protocol,
ParticleAttributes.node.address.row,
ParticleAttributes.node.address.column + 1);
break;
case STATE_TYPE_ENUMERATING_SOUTH_NEIGHBOUR:
__interpretEnumerateNeighbourAckReception(port->rxPort,
port->protocol,
ParticleAttributes.node.address.row + 1,
ParticleAttributes.node.address.column);
break;
case STATE_TYPE_IDLE:
__interpretReceivedPackage(port);
break;
default:
break;
}
if (ParticleAttributes.protocol.isLastReceptionInterpreted) {
LED_STATUS4_TOGGLE;
ParticleAttributes.protocol.isLastReceptionInterpreted = false;
}
// DEBUG_CHAR_OUT('i');
}
|
ProgrammableMatter/particle-firmware | src/avr-common/utils/uc-core/actuation/ActuationTypesCtors.h | /**
* @author <NAME> 12.07.2016
*
* Actuation types constructor implementation.
*/
#pragma once
#include "ActuationTypes.h"
/**
* constructor function
* @param o reference to the object to construct
*/
void constructActuators(Actuators *const o) {
o->northLeft = false;
o->northRight = false;
o->eastLeft = false;
o->eastRight = false;
}
/**
* constructor function
* @param o reference to the object to construct
*/
void constructHeatingMode(HeatingMode *const o) {
// TODO: pwm driven pwer levels seems not to work correctly - don't see the pwm
// o->dutyCycleLevel = HEATING_LEVEL_TYPE_MEDIUM;
o->dutyCycleLevel = HEATING_LEVEL_TYPE_MAXIMUM;
// o->dutyCycleLevel = HEATING_LEVEL_TYPE_STRONG;
}
/**
* constructor function
* @param o reference to the object to construct
*/
void constructLocalTime(LocalTime *o) {
o->periodTimeStamp = 0;
};
/**
* constructor function
* @param o reference to the object to construct
*/
void constructActuationCommand(ActuationCommand *const o) {
constructActuators(&o->actuators);
constructHeatingMode(&o->actuationPower);
constructLocalTime(&o->actuationStart);
constructLocalTime(&o->actuationEnd);
o->isScheduled = false;
o->executionState = ACTUATION_STATE_TYPE_IDLE;
}
|
ProgrammableMatter/particle-firmware | src/avr-common/utils/uc-core/configuration/Actuation.h | /**
* @author <NAME> 20.07.2016
*
* Actuation related arguments.
*/
#pragma once
/**
* ~75% actuation duty cycle
*/
#define ACTUATION_COMPARE_VALUE_POWER_STRONG ((UINT8_MAX / 4) * 3)
/**
* ~50% actuation duty cycle
*/
#define ACTUATION_COMPARE_VALUE_POWER_MEDIUM (UINT8_MAX / 2)
/**
* ~25% actuation duty cycle
*/
#define ACTUATION_COMPARE_VALUE_POWER_WEAK (UINT8_MAX / 4)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.