<commit_before>/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "shellgenerator.h"
#include "reporthandler.h"

#include "metaqtscript.h"

bool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const
{
    uint cg = meta_class->typeEntry()->codeGeneration();
    if (meta_class->name().startsWith("QtScript")) return false;
    if (meta_class->name().startsWith("QFuture")) return false;
    if (meta_class->name().startsWith("Global")) return false;
    if (meta_class->name().startsWith("QStyleOptionComplex")) return false;
    if (meta_class->name().startsWith("QTextLayout")) return false;
    if (meta_class->name().startsWith("QPersistentModelIndex")) return false;
    return ((cg & TypeEntry::GenerateCode) != 0);
}

void ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options)
{
    if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) {
        s << type->originalTypeDescription();
        return;
    }

    if (type->isArray()) {
        writeTypeInfo(s, type->arrayElementType(), options);
        if (options & ArrayAsPointer) {
            s << "*";
        } else {
            s << "[" << type->arrayElementCount() << "]";
        }
        return;
    }

    const TypeEntry *te = type->typeEntry();

    if (type->isConstant() && !(options & ExcludeConst))
        s << "const ";

    if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) {
        s << "int";
    } else if (te->isFlags()) {
        s << ((FlagsTypeEntry *) te)->originalName();
    } else {
        s << fixCppTypeName(te->qualifiedCppName());
    }

    if (type->instantiations().size() > 0
        && (!type->isContainer()
            || (static_cast<const ContainerTypeEntry *>(te))->type() != ContainerTypeEntry::StringListContainer)) {
        s << '<';
        QList<AbstractMetaType *> args = type->instantiations();
        bool nested_template = false;
        for (int i=0; i<args.size(); ++i) {
            if (i != 0)
                s << ", ";
            nested_template |= args.at(i)->isContainer();
            writeTypeInfo(s, args.at(i));
        }
        if (nested_template)
            s << ' ';
        s << '>';
    }

    s << QString(type->indirections(), '*');

    if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr))
        s << "&";

    if (type->isReference() && (options & ConvertReferenceToPtr)) {
      s << "*";
    }

    if (!(options & SkipName))
        s << ' ';
}

void ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner,
                                          const AbstractMetaArgumentList &arguments,
                                          Option option,
                                          int numArguments)
{
    if (numArguments < 0) numArguments = arguments.size();

    for (int i=0; i<numArguments; ++i) {
        if (i != 0)
            s << ", ";
        AbstractMetaArgument *arg = arguments.at(i);
        writeTypeInfo(s, arg->type(), option);
        if (!(option & SkipName))
            s << " " << arg->argumentName();
        if ((option & IncludeDefaultExpression) && !arg->originalDefaultValueExpression().isEmpty()) {
            s << " = ";

            QString expr = arg->originalDefaultValueExpression();
          if (expr != "0") {
            QString qualifier;
            if (arg->type()->typeEntry()->isEnum() && expr.indexOf("::") < 0) {
              qualifier =  ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier();
            } else if (arg->type()->typeEntry()->isFlags() && expr.indexOf("::") < 0) {
              qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier();
            }
            if (!qualifier.isEmpty()) {
              s << qualifier << "::";
            }
          }
          if (expr.contains("defaultConnection")) {
            expr.replace("defaultConnection","QSqlDatabase::defaultConnection");
          }
          if (expr == "MediaSource()") {
            expr = "Phonon::MediaSource()";
          }
            s << expr;
        }
    }
}

/*!
 * Writes the function \a meta_function signature to the textstream \a s.
 *
 * The \a name_prefix can be used to give the function name a prefix,
 * like "__public_" or "__override_" and \a classname_prefix can
 * be used to give the class name a prefix.
 *
 * The \a option flags can be used to tweak various parameters, such as
 * showing static, original vs renamed name, underscores for space etc.
 *
 * The \a extra_arguments list is a list of extra arguments on the
 * form "bool static_call".
 */

void ShellGenerator::writeFunctionSignature(QTextStream &s,
                                          const AbstractMetaFunction *meta_function,
                                          const AbstractMetaClass *implementor,
                                          const QString &name_prefix,
                                          Option option,
                                          const QString &classname_prefix,
                                          const QStringList &extra_arguments,
                                          int numArguments)
{
// ### remove the implementor
    AbstractMetaType *function_type = meta_function->type();

    if ((option & SkipReturnType) == 0) {
        if (function_type) {
            writeTypeInfo(s, function_type, option);
            s << " ";
        } else if (!meta_function->isConstructor()) {
            s << "void ";
        }
    }

    if (implementor) {
        if (classname_prefix.isEmpty())
            s << wrapperClassName(implementor) << "::";
        else
            s << classname_prefix << implementor->name() << "::";
    }

    QString function_name;
    if (option & OriginalName)
        function_name = meta_function->originalName();
    else
        function_name = meta_function->name();

    if (option & UnderscoreSpaces)
        function_name = function_name.replace(' ', '_');

    if (meta_function->isConstructor())
        function_name = meta_function->ownerClass()->name();

    if (meta_function->isStatic() && (option & ShowStatic)) {
      function_name = "static_" + meta_function->ownerClass()->name() + "_" + function_name;
    }

    if (function_name.startsWith("operator")) {
      function_name = meta_function->name();
    }

    if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction)
    s << "py_set_";
    else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction)
    s << "py_get_";

  s << name_prefix << function_name;

    s << "(";

  if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) {
    s << meta_function->ownerClass()->qualifiedCppName() << "* theWrappedObject";
    if (meta_function->arguments().size() != 0) {
      s << ", ";
    }
  }

   writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments);

    // The extra arguments...
    for (int i=0; i<extra_arguments.size(); ++i) {
        if (i > 0 || meta_function->arguments().size() != 0)
            s << ", ";
        s << extra_arguments.at(i);
    }

    s << ")";
    if (meta_function->isConstant())
        s << " const";
    if (!meta_function->exception().isEmpty())
        s << " " << meta_function->exception();
}
bool function_sorter(AbstractMetaFunction *a, AbstractMetaFunction *b);

AbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class)
{
  AbstractMetaFunctionList functions = meta_class->queryFunctions(
    AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasPublic
    | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
    );
  AbstractMetaFunctionList functions2 = meta_class->queryFunctions(
    AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
    | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
    );
  QSet<AbstractMetaFunction*> set1 = QSet<AbstractMetaFunction*>::fromList(functions);
  foreach(AbstractMetaFunction* func, functions2) {
    set1.insert(func);
  }

  AbstractMetaFunctionList resultFunctions;

  foreach(AbstractMetaFunction* func, set1.toList()) {
    if (!func->isAbstract() && func->implementingClass()==meta_class) {
      resultFunctions << func;
    }
  }
  qSort(resultFunctions.begin(), resultFunctions.end(), function_sorter);
  return resultFunctions;
}

AbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class)
{
  AbstractMetaFunctionList functions = meta_class->queryFunctions(
    AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
//    | AbstractMetaClass::NotRemovedFromTargetLang
    );
  qSort(functions.begin(), functions.end(), function_sorter);
  return functions;
}

AbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class)
{
  AbstractMetaFunctionList functions;
  AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class);
  foreach(AbstractMetaFunction* func, functions1) {
    if (!func->isPublic() || func->isVirtual()) {
      functions << func;
    }
  }
  qSort(functions.begin(), functions.end(), function_sorter);
  return functions;
}

/*!
Writes the include defined by \a inc to \a stream.
*/
void ShellGenerator::writeInclude(QTextStream &stream, const Include &inc)
{
  if (inc.name.isEmpty())
    return;
  if (inc.type == Include::TargetLangImport)
    return;
  stream << "#include ";
  if (inc.type == Include::IncludePath)
    stream << "<";
  else
    stream << "\"";
  stream << inc.name;
  if (inc.type == Include::IncludePath)
    stream << ">";
  else
    stream << "\"";
  stream << endl;
}

/*!
Returns true if the given function \a fun is operator>>() or
operator<<() that streams from/to a Q{Data,Text}Stream, false
otherwise.
*/
bool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun)
{
  return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction)
    && (fun->arguments().size() == 1)
    && (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom"))
    || ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo"))));
}

bool ShellGenerator::isBuiltIn(const QString& name) {

  static QSet<QString> builtIn;
  if (builtIn.isEmpty()) {
    builtIn.insert("Qt");
    builtIn.insert("QFont");
    builtIn.insert("QPixmap");
    builtIn.insert("QBrush");
    builtIn.insert("QBitArray");
    builtIn.insert("QByteArray");
    builtIn.insert("QPalette");
    builtIn.insert("QPen");
    builtIn.insert("QIcon");
    builtIn.insert("QImage");
    builtIn.insert("QPolygon");
    builtIn.insert("QRegion");
    builtIn.insert("QBitmap");
    builtIn.insert("QCursor");
    builtIn.insert("QColor");
    builtIn.insert("QSizePolicy");
    builtIn.insert("QKeySequence");
    builtIn.insert("QTextLength");
    builtIn.insert("QTextFormat");
    builtIn.insert("QMatrix");
    builtIn.insert("QDate");
    builtIn.insert("QTime");
    builtIn.insert("QDateTime");
    builtIn.insert("QUrl");
    builtIn.insert("QLocale");
    builtIn.insert("QRect");
    builtIn.insert("QRectF");
    builtIn.insert("QSize");
    builtIn.insert("QSizeF");
    builtIn.insert("QLine");
    builtIn.insert("QLineF");
    builtIn.insert("QPoint");
    builtIn.insert("QPointF");
    builtIn.insert("QRegExp");
  }
  return builtIn.contains(name);
}
<commit_msg>added QPersistentModelIndex<commit_after>/****************************************************************************
**
** Copyright (C) 2008-2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Script Generator project on Qt Labs.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "shellgenerator.h"
#include "reporthandler.h"

#include "metaqtscript.h"

bool ShellGenerator::shouldGenerate(const AbstractMetaClass *meta_class) const
{
    uint cg = meta_class->typeEntry()->codeGeneration();
    if (meta_class->name().startsWith("QtScript")) return false;
    if (meta_class->name().startsWith("QFuture")) return false;
    if (meta_class->name().startsWith("Global")) return false;
    if (meta_class->name().startsWith("QStyleOptionComplex")) return false;
    // because of default arg of draw()...
    if (meta_class->name().startsWith("QTextLayout")) return false;
    return ((cg & TypeEntry::GenerateCode) != 0);
}

void ShellGenerator::writeTypeInfo(QTextStream &s, const AbstractMetaType *type, Option options)
{
    if ((options & OriginalTypeDescription) && !type->originalTypeDescription().isEmpty()) {
        s << type->originalTypeDescription();
        return;
    }

    if (type->isArray()) {
        writeTypeInfo(s, type->arrayElementType(), options);
        if (options & ArrayAsPointer) {
            s << "*";
        } else {
            s << "[" << type->arrayElementCount() << "]";
        }
        return;
    }

    const TypeEntry *te = type->typeEntry();

    if (type->isConstant() && !(options & ExcludeConst))
        s << "const ";

    if ((options & EnumAsInts) && (te->isEnum() || te->isFlags())) {
        s << "int";
    } else if (te->isFlags()) {
        s << ((FlagsTypeEntry *) te)->originalName();
    } else {
        s << fixCppTypeName(te->qualifiedCppName());
    }

    if (type->instantiations().size() > 0
        && (!type->isContainer()
            || (static_cast<const ContainerTypeEntry *>(te))->type() != ContainerTypeEntry::StringListContainer)) {
        s << '<';
        QList<AbstractMetaType *> args = type->instantiations();
        bool nested_template = false;
        for (int i=0; i<args.size(); ++i) {
            if (i != 0)
                s << ", ";
            nested_template |= args.at(i)->isContainer();
            writeTypeInfo(s, args.at(i));
        }
        if (nested_template)
            s << ' ';
        s << '>';
    }

    s << QString(type->indirections(), '*');

    if (type->isReference() && !(options & ExcludeReference) && !(options & ConvertReferenceToPtr))
        s << "&";

    if (type->isReference() && (options & ConvertReferenceToPtr)) {
      s << "*";
    }

    if (!(options & SkipName))
        s << ' ';
}

void ShellGenerator::writeFunctionArguments(QTextStream &s, const AbstractMetaClass* owner,
                                          const AbstractMetaArgumentList &arguments,
                                          Option option,
                                          int numArguments)
{
    if (numArguments < 0) numArguments = arguments.size();

    for (int i=0; i<numArguments; ++i) {
        if (i != 0)
            s << ", ";
        AbstractMetaArgument *arg = arguments.at(i);
        writeTypeInfo(s, arg->type(), option);
        if (!(option & SkipName))
            s << " " << arg->argumentName();
        if ((option & IncludeDefaultExpression) && !arg->originalDefaultValueExpression().isEmpty()) {
            s << " = ";

            QString expr = arg->originalDefaultValueExpression();
          if (expr != "0") {
            QString qualifier;
            if (arg->type()->typeEntry()->isEnum() && expr.indexOf("::") < 0) {
              qualifier =  ((EnumTypeEntry *)arg->type()->typeEntry())->qualifier();
            } else if (arg->type()->typeEntry()->isFlags() && expr.indexOf("::") < 0) {
              qualifier = ((FlagsTypeEntry *)arg->type()->typeEntry())->originator()->qualifier();
            }
            if (!qualifier.isEmpty()) {
              s << qualifier << "::";
            }
          }
          if (expr.contains("defaultConnection")) {
            expr.replace("defaultConnection","QSqlDatabase::defaultConnection");
          }
          if (expr == "MediaSource()") {
            expr = "Phonon::MediaSource()";
          }
            s << expr;
        }
    }
}

/*!
 * Writes the function \a meta_function signature to the textstream \a s.
 *
 * The \a name_prefix can be used to give the function name a prefix,
 * like "__public_" or "__override_" and \a classname_prefix can
 * be used to give the class name a prefix.
 *
 * The \a option flags can be used to tweak various parameters, such as
 * showing static, original vs renamed name, underscores for space etc.
 *
 * The \a extra_arguments list is a list of extra arguments on the
 * form "bool static_call".
 */

void ShellGenerator::writeFunctionSignature(QTextStream &s,
                                          const AbstractMetaFunction *meta_function,
                                          const AbstractMetaClass *implementor,
                                          const QString &name_prefix,
                                          Option option,
                                          const QString &classname_prefix,
                                          const QStringList &extra_arguments,
                                          int numArguments)
{
// ### remove the implementor
    AbstractMetaType *function_type = meta_function->type();

    if ((option & SkipReturnType) == 0) {
        if (function_type) {
            writeTypeInfo(s, function_type, option);
            s << " ";
        } else if (!meta_function->isConstructor()) {
            s << "void ";
        }
    }

    if (implementor) {
        if (classname_prefix.isEmpty())
            s << wrapperClassName(implementor) << "::";
        else
            s << classname_prefix << implementor->name() << "::";
    }

    QString function_name;
    if (option & OriginalName)
        function_name = meta_function->originalName();
    else
        function_name = meta_function->name();

    if (option & UnderscoreSpaces)
        function_name = function_name.replace(' ', '_');

    if (meta_function->isConstructor())
        function_name = meta_function->ownerClass()->name();

    if (meta_function->isStatic() && (option & ShowStatic)) {
      function_name = "static_" + meta_function->ownerClass()->name() + "_" + function_name;
    }

    if (function_name.startsWith("operator")) {
      function_name = meta_function->name();
    }

    if (meta_function->attributes() & AbstractMetaAttributes::SetterFunction)
    s << "py_set_";
    else if (meta_function->attributes() & AbstractMetaAttributes::GetterFunction)
    s << "py_get_";

  s << name_prefix << function_name;

    s << "(";

  if ((option & FirstArgIsWrappedObject) && meta_function->ownerClass() && !meta_function->isConstructor() && !meta_function->isStatic()) {
    s << meta_function->ownerClass()->qualifiedCppName() << "* theWrappedObject";
    if (meta_function->arguments().size() != 0) {
      s << ", ";
    }
  }

   writeFunctionArguments(s, meta_function->ownerClass(), meta_function->arguments(), Option(option & Option(~ConvertReferenceToPtr)), numArguments);

    // The extra arguments...
    for (int i=0; i<extra_arguments.size(); ++i) {
        if (i > 0 || meta_function->arguments().size() != 0)
            s << ", ";
        s << extra_arguments.at(i);
    }

    s << ")";
    if (meta_function->isConstant())
        s << " const";
    if (!meta_function->exception().isEmpty())
        s << " " << meta_function->exception();
}
bool function_sorter(AbstractMetaFunction *a, AbstractMetaFunction *b);

AbstractMetaFunctionList ShellGenerator::getFunctionsToWrap(const AbstractMetaClass* meta_class)
{
  AbstractMetaFunctionList functions = meta_class->queryFunctions(
    AbstractMetaClass::NormalFunctions | AbstractMetaClass::WasPublic
    | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
    );
  AbstractMetaFunctionList functions2 = meta_class->queryFunctions(
    AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
    | AbstractMetaClass::NotRemovedFromTargetLang | AbstractMetaClass::ClassImplements
    );
  QSet<AbstractMetaFunction*> set1 = QSet<AbstractMetaFunction*>::fromList(functions);
  foreach(AbstractMetaFunction* func, functions2) {
    set1.insert(func);
  }

  AbstractMetaFunctionList resultFunctions;

  foreach(AbstractMetaFunction* func, set1.toList()) {
    if (!func->isAbstract() && func->implementingClass()==meta_class) {
      resultFunctions << func;
    }
  }
  qSort(resultFunctions.begin(), resultFunctions.end(), function_sorter);
  return resultFunctions;
}

AbstractMetaFunctionList ShellGenerator::getVirtualFunctionsForShell(const AbstractMetaClass* meta_class)
{
  AbstractMetaFunctionList functions = meta_class->queryFunctions(
    AbstractMetaClass::VirtualFunctions | AbstractMetaClass::WasVisible
//    | AbstractMetaClass::NotRemovedFromTargetLang
    );
  qSort(functions.begin(), functions.end(), function_sorter);
  return functions;
}

AbstractMetaFunctionList ShellGenerator::getProtectedFunctionsThatNeedPromotion(const AbstractMetaClass* meta_class)
{
  AbstractMetaFunctionList functions;
  AbstractMetaFunctionList functions1 = getFunctionsToWrap(meta_class);
  foreach(AbstractMetaFunction* func, functions1) {
    if (!func->isPublic() || func->isVirtual()) {
      functions << func;
    }
  }
  qSort(functions.begin(), functions.end(), function_sorter);
  return functions;
}

/*!
Writes the include defined by \a inc to \a stream.
*/
void ShellGenerator::writeInclude(QTextStream &stream, const Include &inc)
{
  if (inc.name.isEmpty())
    return;
  if (inc.type == Include::TargetLangImport)
    return;
  stream << "#include ";
  if (inc.type == Include::IncludePath)
    stream << "<";
  else
    stream << "\"";
  stream << inc.name;
  if (inc.type == Include::IncludePath)
    stream << ">";
  else
    stream << "\"";
  stream << endl;
}

/*!
Returns true if the given function \a fun is operator>>() or
operator<<() that streams from/to a Q{Data,Text}Stream, false
otherwise.
*/
bool ShellGenerator::isSpecialStreamingOperator(const AbstractMetaFunction *fun)
{
  return ((fun->functionType() == AbstractMetaFunction::GlobalScopeFunction)
    && (fun->arguments().size() == 1)
    && (((fun->originalName() == "operator>>") && (fun->modifiedName() == "readFrom"))
    || ((fun->originalName() == "operator<<") && (fun->modifiedName() == "writeTo"))));
}

bool ShellGenerator::isBuiltIn(const QString& name) {

  static QSet<QString> builtIn;
  if (builtIn.isEmpty()) {
    builtIn.insert("Qt");
    builtIn.insert("QFont");
    builtIn.insert("QPixmap");
    builtIn.insert("QBrush");
    builtIn.insert("QBitArray");
    builtIn.insert("QByteArray");
    builtIn.insert("QPalette");
    builtIn.insert("QPen");
    builtIn.insert("QIcon");
    builtIn.insert("QImage");
    builtIn.insert("QPolygon");
    builtIn.insert("QRegion");
    builtIn.insert("QBitmap");
    builtIn.insert("QCursor");
    builtIn.insert("QColor");
    builtIn.insert("QSizePolicy");
    builtIn.insert("QKeySequence");
    builtIn.insert("QTextLength");
    builtIn.insert("QTextFormat");
    builtIn.insert("QMatrix");
    builtIn.insert("QDate");
    builtIn.insert("QTime");
    builtIn.insert("QDateTime");
    builtIn.insert("QUrl");
    builtIn.insert("QLocale");
    builtIn.insert("QRect");
    builtIn.insert("QRectF");
    builtIn.insert("QSize");
    builtIn.insert("QSizeF");
    builtIn.insert("QLine");
    builtIn.insert("QLineF");
    builtIn.insert("QPoint");
    builtIn.insert("QPointF");
    builtIn.insert("QRegExp");
  }
  return builtIn.contains(name);
}
<|endoftext|>


<commit_before>#include "../src/alm.h"
#include "alm_wrapper.h"
#include <cstdlib>
#include <string>
#include <iostream>

extern "C" {

    #define MAX_NUM_ALM 10

    static const std::string atom_name[] = {
        "X", "H", "He", "Li", "Be", "B", "C", "N", "O", "F",
        "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K",
        "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu",
        "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y",
        "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In",
        "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr",
        "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm",
        "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au",
        "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac",
        "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es",
        "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt",
        "Ds", "Rg", "Cn", "Uut", "Uuq", "Uup", "Uuh", "Uus", "Uuo"};

    static ALM_NS::ALM *alm[MAX_NUM_ALM];
    static int is_alm_used[MAX_NUM_ALM];
    static int is_alm_init = 0;

    void alm_init(void)
    {
        int id;
        for (id = 0; id < MAX_NUM_ALM; id++) {
            if (alm[id]) {
                delete alm[id];
            }
            alm[id] = NULL;
            is_alm_used[id] = 0;
        }
        is_alm_init = 1;
    }

    int alm_new(void)
    {
        int id;

        if (!is_alm_init) {
            alm_init();
        }

        for (id = 0; id < MAX_NUM_ALM; id++) {
            if (!is_alm_used[id]) {
                alm[id] = new ALM_NS::ALM();
                is_alm_used[id] = 1;
                break;
            }
        }

        if (id == MAX_NUM_ALM) {
            return -1;
        } else {
            return id;
        }
    }

    void alm_delete(const int id)
    {
        if (alm[id]) {
            delete alm[id];
            alm[id] = NULL;
            is_alm_used[id] = 0;
        }
    }

    // void set_output_filename_prefix(const std::string prefix);
    // void set_is_print_symmetry(const int is_printsymmetry);
    // void set_is_print_hessians(const bool print_hessian);
    // void set_symmetry_param(const int nsym);
    // void set_symmetry_tolerance(const double tolerance);
    // void set_displacement_param(const bool trim_dispsign_for_evenfunc);
    // void set_displacement_basis(const std::string str_disp_basis);
    // void set_periodicity(const int is_periodic[3]);

    void alm_set_cell(const int id,
                      const int nat,
                      const double lavec[3][3],
                      const double xcoord[][3],
                      const int kd[])
    {
        int i, j, nkd;
        int nkd_vals[nat], kd_new[nat];
        bool kd_exist;

        nkd_vals[0] = kd[0];
        kd_new[0] = 1;
        nkd = 1;
        for (i = 1; i < nat; ++i) {
            kd_exist = false;
            for (j = 0; j < nkd; ++j) {
                if (nkd_vals[j] == kd[i]) {
                    kd_exist = true;
                    kd_new[i] = j + 1;
                    break;
                }
            }
            if (!kd_exist) {
                nkd_vals[nkd] = kd[i];
                kd_new[i] = nkd + 1;
                ++nkd;
            }
        }
        std::string *kdname = new std::string[nkd];
        //std::string kdname[nkd];
        for (int i = 0; i < nkd; i++) {
            kdname[i] = atom_name[abs(nkd_vals[i]) % 118];
        }

        alm[id]->set_cell(nat, lavec, xcoord, kd_new, kdname);
        delete [] kdname;
    }

    // void set_magnetic_params(const double* magmom,
    //   		       const bool lspin,
    //   		       const int noncollinear,
    //   		       const int trev_sym_mag,
    //   		       const std::string str_magmom);

    void alm_set_displacement_and_force(const int id,
                                        const double* u_in,
                                        const double* f_in,
                                        const int nat,
                                        const int ndata_used)
    {
        alm[id]->set_displacement_and_force(u_in, f_in, nat, ndata_used);
    }

    int alm_get_ndata_used(const int id)
    {
        return alm[id]->get_ndata_used();
    }

    void alm_set_constraint_type(const int id,
                                         const int constraint_flag) // ICONST
    {
        alm[id]->set_constraint_type(constraint_flag);
    }

    // void set_fitting_constraint_rotation_axis(const std::string rotation_axis) // ROTAXIS
    // void set_fitting_filenames(const std::string dfile,
    //   			 const std::string ffile);

    void alm_set_norder(const int id,
                        const int maxorder)
    {
        alm[id]->set_norder(maxorder);
    }

    void alm_set_nbody_include(const int id,
                               const int *nbody_include)
    {
        alm[id]->set_nbody_include(nbody_include);
    }

    void alm_set_cutoff_radii(const int id,
                              const double * rcs)
    {
        alm[id]->set_cutoff_radii(rcs);
    }

    void alm_generate_force_constant(const int id)
    {
        alm[id]->generate_force_constant();
    }

    int alm_get_atom_mapping_by_pure_translations(const int id,
                                                  int *map_p2s)
    {
        return alm[id]->get_atom_mapping_by_pure_translations(map_p2s);
    }

    int alm_get_number_of_displacement_patterns(const int id,
                                                const int fc_order) // harmonic=1,
    {
        return alm[id]->get_number_of_displacement_patterns(fc_order);
    }

    void alm_get_numbers_of_displacements(const int id,
                                          int *numbers,
                                          const int fc_order) // harmonic=1,
    {
        alm[id]->get_numbers_of_displacements(numbers, fc_order);
    }

    int alm_get_displacement_patterns(const int id,
                                      int *atom_indices,
                                      double *disp_patterns,
                                      const int fc_order) // harmonic=1,
    {
        return alm[id]->get_displacement_patterns(atom_indices,
                                              disp_patterns,
                                              fc_order);
    }

    int alm_get_number_of_fc_elements(const int id,
                                      const int fc_order)  // harmonic=1, ...
    {
        return alm[id]->get_number_of_fc_elements(fc_order);
    }

    int alm_get_number_of_irred_fc_elements(const int id,
                                            const int fc_order)
    {
        return alm[id]->get_number_of_irred_fc_elements(fc_order);
    }

    void alm_get_fc_origin(const int id,
                    double *fc_values,
                    int *elem_indices, // (len(fc_values), fc_order + 1) is flatten.
                    const int fc_order)
    {
        alm[id]->get_fc_origin(fc_values, elem_indices, fc_order);
    }

    void alm_get_fc_irreducible(const int id,
                    double *fc_values,
                    int *elem_indices, // (len(fc_values), fc_order + 1) is flatten.
                    const int fc_order)
    {
        alm[id]->get_fc_irreducible(fc_values, elem_indices, fc_order);
    }

    void alm_get_fc_all(const int id,
                        double *fc_values,
                        int *elem_indices, // (len(fc_values), fc_order + 1) is flatten.
                       const int fc_order)
    {
        alm[id]->get_fc_all(fc_values, elem_indices, fc_order);
    }

    void alm_set_fc(const int id, double *fc_in)
    {
        alm[id]->set_fc(fc_in);
    }

    void alm_get_matrix_elements(const int id,
                                 const int nat,
                                 const int ndata_used,
                                 double *amat,
                                 double *bvec)
    {
        alm[id]->get_matrix_elements(nat, ndata_used, amat, bvec);
    }

    void alm_run_suggest(const int id)
    {
        alm[id]->set_run_mode("suggest");
        alm[id]->run_suggest();
    }

    int alm_optimize(const int id)
    {
        alm[id]->set_run_mode("fitting");
        int info = alm[id]->optimize();
        return info;
    }
}
<commit_msg>Minor format fix<commit_after>#include "../src/alm.h"
#include "alm_wrapper.h"
#include <cstdlib>
#include <string>
#include <iostream>

extern "C" {

    #define MAX_NUM_ALM 10

    static const std::string atom_name[] = {
        "X", "H", "He", "Li", "Be", "B", "C", "N", "O", "F",
        "Ne", "Na", "Mg", "Al", "Si", "P", "S", "Cl", "Ar", "K",
        "Ca", "Sc", "Ti", "V", "Cr", "Mn", "Fe", "Co", "Ni", "Cu",
        "Zn", "Ga", "Ge", "As", "Se", "Br", "Kr", "Rb", "Sr", "Y",
        "Zr", "Nb", "Mo", "Tc", "Ru", "Rh", "Pd", "Ag", "Cd", "In",
        "Sn", "Sb", "Te", "I", "Xe", "Cs", "Ba", "La", "Ce", "Pr",
        "Nd", "Pm", "Sm", "Eu", "Gd", "Tb", "Dy", "Ho", "Er", "Tm",
        "Yb", "Lu", "Hf", "Ta", "W", "Re", "Os", "Ir", "Pt", "Au",
        "Hg", "Tl", "Pb", "Bi", "Po", "At", "Rn", "Fr", "Ra", "Ac",
        "Th", "Pa", "U", "Np", "Pu", "Am", "Cm", "Bk", "Cf", "Es",
        "Fm", "Md", "No", "Lr", "Rf", "Db", "Sg", "Bh", "Hs", "Mt",
        "Ds", "Rg", "Cn", "Uut", "Uuq", "Uup", "Uuh", "Uus", "Uuo"};

    static ALM_NS::ALM *alm[MAX_NUM_ALM];
    static int is_alm_used[MAX_NUM_ALM];
    static int is_alm_init = 0;

    void alm_init(void)
    {
        int id;
        for (id = 0; id < MAX_NUM_ALM; id++) {
            if (alm[id]) {
                delete alm[id];
            }
            alm[id] = NULL;
            is_alm_used[id] = 0;
        }
        is_alm_init = 1;
    }

    int alm_new(void)
    {
        int id;

        if (!is_alm_init) {
            alm_init();
        }

        for (id = 0; id < MAX_NUM_ALM; id++) {
            if (!is_alm_used[id]) {
                alm[id] = new ALM_NS::ALM();
                is_alm_used[id] = 1;
                break;
            }
        }

        if (id == MAX_NUM_ALM) {
            return -1;
        } else {
            return id;
        }
    }

    void alm_delete(const int id)
    {
        if (alm[id]) {
            delete alm[id];
            alm[id] = NULL;
            is_alm_used[id] = 0;
        }
    }

    // void set_output_filename_prefix(const std::string prefix);
    // void set_is_print_symmetry(const int is_printsymmetry);
    // void set_is_print_hessians(const bool print_hessian);
    // void set_symmetry_param(const int nsym);
    // void set_symmetry_tolerance(const double tolerance);
    // void set_displacement_param(const bool trim_dispsign_for_evenfunc);
    // void set_displacement_basis(const std::string str_disp_basis);
    // void set_periodicity(const int is_periodic[3]);

    void alm_set_cell(const int id,
                      const int nat,
                      const double lavec[3][3],
                      const double xcoord[][3],
                      const int kd[])
    {
        int i, j, nkd;
        int nkd_vals[nat], kd_new[nat];
        bool kd_exist;

        nkd_vals[0] = kd[0];
        kd_new[0] = 1;
        nkd = 1;
        for (i = 1; i < nat; ++i) {
            kd_exist = false;
            for (j = 0; j < nkd; ++j) {
                if (nkd_vals[j] == kd[i]) {
                    kd_exist = true;
                    kd_new[i] = j + 1;
                    break;
                }
            }
            if (!kd_exist) {
                nkd_vals[nkd] = kd[i];
                kd_new[i] = nkd + 1;
                ++nkd;
            }
        }
        std::string *kdname = new std::string[nkd];
        //std::string kdname[nkd];
        for (int i = 0; i < nkd; i++) {
            kdname[i] = atom_name[abs(nkd_vals[i]) % 118];
        }

        alm[id]->set_cell(nat, lavec, xcoord, kd_new, kdname);
        delete [] kdname;
    }

    // void set_magnetic_params(const double* magmom,
    //   		       const bool lspin,
    //   		       const int noncollinear,
    //   		       const int trev_sym_mag,
    //   		       const std::string str_magmom);

    void alm_set_displacement_and_force(const int id,
                                        const double* u_in,
                                        const double* f_in,
                                        const int nat,
                                        const int ndata_used)
    {
        alm[id]->set_displacement_and_force(u_in, f_in, nat, ndata_used);
    }

    int alm_get_ndata_used(const int id)
    {
        return alm[id]->get_ndata_used();
    }

    void alm_set_constraint_type(const int id,
                                 const int constraint_flag) // ICONST
    {
        alm[id]->set_constraint_type(constraint_flag);
    }

    // void set_fitting_constraint_rotation_axis(const std::string rotation_axis) // ROTAXIS
    // void set_fitting_filenames(const std::string dfile,
    //   			 const std::string ffile);

    void alm_set_norder(const int id,
                        const int maxorder)
    {
        alm[id]->set_norder(maxorder);
    }

    void alm_set_nbody_include(const int id,
                               const int *nbody_include)
    {
        alm[id]->set_nbody_include(nbody_include);
    }

    void alm_set_cutoff_radii(const int id,
                              const double * rcs)
    {
        alm[id]->set_cutoff_radii(rcs);
    }

    void alm_generate_force_constant(const int id)
    {
        alm[id]->generate_force_constant();
    }

    int alm_get_atom_mapping_by_pure_translations(const int id,
                                                  int *map_p2s)
    {
        return alm[id]->get_atom_mapping_by_pure_translations(map_p2s);
    }

    int alm_get_number_of_displacement_patterns(const int id,
                                                const int fc_order) // harmonic=1,
    {
        return alm[id]->get_number_of_displacement_patterns(fc_order);
    }

    void alm_get_numbers_of_displacements(const int id,
                                          int *numbers,
                                          const int fc_order) // harmonic=1,
    {
        alm[id]->get_numbers_of_displacements(numbers, fc_order);
    }

    int alm_get_displacement_patterns(const int id,
                                      int *atom_indices,
                                      double *disp_patterns,
                                      const int fc_order) // harmonic=1,
    {
        return alm[id]->get_displacement_patterns(atom_indices,
                                              disp_patterns,
                                              fc_order);
    }

    int alm_get_number_of_fc_elements(const int id,
                                      const int fc_order)  // harmonic=1, ...
    {
        return alm[id]->get_number_of_fc_elements(fc_order);
    }

    int alm_get_number_of_irred_fc_elements(const int id,
                                            const int fc_order)
    {
        return alm[id]->get_number_of_irred_fc_elements(fc_order);
    }

    void alm_get_fc_origin(const int id,
                    double *fc_values,
                    int *elem_indices, // (len(fc_values), fc_order + 1) is flatten.
                    const int fc_order)
    {
        alm[id]->get_fc_origin(fc_values, elem_indices, fc_order);
    }

    void alm_get_fc_irreducible(const int id,
                    double *fc_values,
                    int *elem_indices, // (len(fc_values), fc_order + 1) is flatten.
                    const int fc_order)
    {
        alm[id]->get_fc_irreducible(fc_values, elem_indices, fc_order);
    }

    void alm_get_fc_all(const int id,
                        double *fc_values,
                        int *elem_indices, // (len(fc_values), fc_order + 1) is flatten.
                       const int fc_order)
    {
        alm[id]->get_fc_all(fc_values, elem_indices, fc_order);
    }

    void alm_set_fc(const int id, double *fc_in)
    {
        alm[id]->set_fc(fc_in);
    }

    void alm_get_matrix_elements(const int id,
                                 const int nat,
                                 const int ndata_used,
                                 double *amat,
                                 double *bvec)
    {
        alm[id]->get_matrix_elements(nat, ndata_used, amat, bvec);
    }

    void alm_run_suggest(const int id)
    {
        alm[id]->set_run_mode("suggest");
        alm[id]->run_suggest();
    }

    int alm_optimize(const int id)
    {
        alm[id]->set_run_mode("fitting");
        int info = alm[id]->optimize();
        return info;
    }
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: score.cxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: rt $ $Date: 2007-04-26 10:01:57 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_goodies.hxx"
#include "score.hxx"
#include "strings.hrc"
#include "invader.hxx"

ScoreWindow::ScoreWindow(Window* Parent, WinBits wBits, ResMgr* pP) :
                    Window(Parent, wBits),
                    nHero(-1),
                    nRockets(5),
                    nLives(3),
                    nScore(0L),
                    pRes(pP),
                    bPaintBack(FALSE)
{
    SetBackground(Wallpaper( Color( COL_GRAY ) ) );
}

ScoreWindow::~ScoreWindow()
{
}

void ScoreWindow::Paint(const Rectangle&)
{
    Font aFont = GetFont();
    aFont.SetColor(COL_WHITE);
    aFont.SetFillColor(COL_GRAY);
    SetFont(*&aFont);

    SetFillColor(COL_GRAY);

    if(bPaintBack)
    {
        Push( PUSH_LINECOLOR );
        SetLineColor();
        DrawRect(Rectangle(Point(0,0),GetOutputSizePixel()));
        Pop();
    }

    if(nHero)
        DrawText(Point(0,0),String(ResId(nHero, *pRes)));

    DrawText(Point(180,0),String(ResId(STR_ROCKETS, *pRes)));

    DrawText(Point(300,0),String(ResId(STR_FIGHTER, *pRes)));
    DrawText(Point(370,0),String::CreateFromInt32(nLives));

    DrawText(Point(400,0),String(ResId(STR_LEVEL, *pRes)));
    DrawText(Point(460,0),String::CreateFromInt32(nLevel));

    DrawText(Point(500,0),String(ResId(STR_SCORE, *pRes)));
    String aString = String::CreateFromInt32(nScore);
    if ( aString.Len() < 7 )
    {
        for ( xub_StrLen i = aString.Len(); i < 7; ++i )
            aString.Insert( '0', 0 );
    }
    DrawText(Point(560,0),aString);

    for(long i=0; i<5;i++)
    {
        if(nRockets > i)
        {
            SetLineColor(COL_GREEN);
            SetFillColor(COL_GREEN);
        }
        else
        {
            SetLineColor(COL_RED);
            SetFillColor(COL_RED);
        }

        DrawRect(Rectangle(Point(250+i*8,5),Point(256+i*8,12)));
    }
    SetBackground(Wallpaper( Color( COL_GRAY ) ) );

    bPaintBack = FALSE;
}

void ScoreWindow::SetHero(long nName)
{
    nHero = nName;

    SetBackground();
    Invalidate();
}

void ScoreWindow::SetRockets(USHORT nWert)
{
    nRockets = nWert;

    SetBackground();
    Invalidate();
}

void ScoreWindow::SetLives(USHORT nWert)
{
    nLives = nWert;

//  SetBackground();
    Invalidate();
}

void ScoreWindow::SetScore(long nWert)
{
    nScore = nWert;

    SetBackground();
    Invalidate();
}

void ScoreWindow::SetLevel(long nWert)
{
    nLevel = nWert;

//  SetBackground();
    Invalidate();
}

void ScoreWindow::ShowMe()
{
    bPaintBack = TRUE;

    Window::Show();
}
<commit_msg>INTEGRATION: CWS changefileheader (1.8.78); FILE MERGED 2008/03/31 13:39:44 rt 1.8.78.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: score.cxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_goodies.hxx"
#include "score.hxx"
#include "strings.hrc"
#include "invader.hxx"

ScoreWindow::ScoreWindow(Window* Parent, WinBits wBits, ResMgr* pP) :
                    Window(Parent, wBits),
                    nHero(-1),
                    nRockets(5),
                    nLives(3),
                    nScore(0L),
                    pRes(pP),
                    bPaintBack(FALSE)
{
    SetBackground(Wallpaper( Color( COL_GRAY ) ) );
}

ScoreWindow::~ScoreWindow()
{
}

void ScoreWindow::Paint(const Rectangle&)
{
    Font aFont = GetFont();
    aFont.SetColor(COL_WHITE);
    aFont.SetFillColor(COL_GRAY);
    SetFont(*&aFont);

    SetFillColor(COL_GRAY);

    if(bPaintBack)
    {
        Push( PUSH_LINECOLOR );
        SetLineColor();
        DrawRect(Rectangle(Point(0,0),GetOutputSizePixel()));
        Pop();
    }

    if(nHero)
        DrawText(Point(0,0),String(ResId(nHero, *pRes)));

    DrawText(Point(180,0),String(ResId(STR_ROCKETS, *pRes)));

    DrawText(Point(300,0),String(ResId(STR_FIGHTER, *pRes)));
    DrawText(Point(370,0),String::CreateFromInt32(nLives));

    DrawText(Point(400,0),String(ResId(STR_LEVEL, *pRes)));
    DrawText(Point(460,0),String::CreateFromInt32(nLevel));

    DrawText(Point(500,0),String(ResId(STR_SCORE, *pRes)));
    String aString = String::CreateFromInt32(nScore);
    if ( aString.Len() < 7 )
    {
        for ( xub_StrLen i = aString.Len(); i < 7; ++i )
            aString.Insert( '0', 0 );
    }
    DrawText(Point(560,0),aString);

    for(long i=0; i<5;i++)
    {
        if(nRockets > i)
        {
            SetLineColor(COL_GREEN);
            SetFillColor(COL_GREEN);
        }
        else
        {
            SetLineColor(COL_RED);
            SetFillColor(COL_RED);
        }

        DrawRect(Rectangle(Point(250+i*8,5),Point(256+i*8,12)));
    }
    SetBackground(Wallpaper( Color( COL_GRAY ) ) );

    bPaintBack = FALSE;
}

void ScoreWindow::SetHero(long nName)
{
    nHero = nName;

    SetBackground();
    Invalidate();
}

void ScoreWindow::SetRockets(USHORT nWert)
{
    nRockets = nWert;

    SetBackground();
    Invalidate();
}

void ScoreWindow::SetLives(USHORT nWert)
{
    nLives = nWert;

//  SetBackground();
    Invalidate();
}

void ScoreWindow::SetScore(long nWert)
{
    nScore = nWert;

    SetBackground();
    Invalidate();
}

void ScoreWindow::SetLevel(long nWert)
{
    nLevel = nWert;

//  SetBackground();
    Invalidate();
}

void ScoreWindow::ShowMe()
{
    bPaintBack = TRUE;

    Window::Show();
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: breakiterator_th.cxx,v $
 *
 *  $Revision: 1.9 $
 *
 *  last change: $Author: obo $ $Date: 2005-11-16 10:18:25 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/
#include <breakiterator_th.hxx>
#include <wtt.h>

#include <string.h> // for memset

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;

namespace com { namespace sun { namespace star { namespace i18n {

//  ----------------------------------------------------
//  class Breakiterator_th
//  ----------------------------------------------------;
BreakIterator_th::BreakIterator_th()
{
    cBreakIterator = "com.sun.star.i18n.BreakIterator_th";
    wordRule=lineRule=NULL;
}

BreakIterator_th::~BreakIterator_th()
{
}

#define SARA_AM 0x0E33

/*
 * cell composition states
 */

#define ST_COM  1   // Compose the following character with leading char and display in the same cell
#define ST_NXT  2   // display the following character in the next cell
#define ST_NDP  3   // non-display

static const sal_Int16 thaiCompRel[MAX_CT][MAX_CT] = {
    //  C  N  C  L  F  F  F  B  B  B  T  A  A  A  A  A  A
    //  T  O  O  V  V  V  V  V  V  D  O  D  D  D  V  V  V
    //  R  N  N     1  2  3  1  2     N  1  2  3  1  2  3
    //  L     S                       E
    //  0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // CTRL 0
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // NON  1
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_COM, ST_COM, ST_COM, ST_COM, ST_COM, ST_COM, ST_COM, ST_COM, ST_COM, ST_COM   }, // CONS 2
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // LV   3
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // FV1  4
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // FV2  5
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // FV3  6
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_COM, ST_COM, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // BV1  7
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_COM, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // BV2  8
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // BD   9
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // TONE 10
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // AD1  11
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // AD2  12
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // AD3  13
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_COM, ST_COM, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // AV1  14
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_COM, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // AV2  15
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_COM, ST_NXT, ST_COM, ST_NXT, ST_NXT, ST_NXT, ST_NXT   } // AV3  16

};

const sal_uInt32 is_ST_COM = (1<<CT_CTRL)|(1<<CT_NON)|(1<<CT_CONS)|(1<<CT_TONE);

static sal_uInt16 SAL_CALL getCombState(const sal_Unicode *text, sal_Int32 pos)
{
    sal_uInt16 ch1 = getCharType(text[pos]);
    sal_uInt16 ch2 = getCharType(text[pos+1]);

    if (text[pos+1] == SARA_AM) {
        if ((1 << ch1) & is_ST_COM)
        return  ST_COM;
        else
        ch2 = CT_AD1;
    }

    return thaiCompRel[ch1][ch2];
}

static sal_Int32 SAL_CALL getACell(const sal_Unicode *text, sal_Int32 pos, sal_Int32 len)
{
    sal_uInt32 curr = 1;
    for (; pos + 1 < len && getCombState(text, pos) == ST_COM; curr++, pos++) {}
    return curr;
}

#define is_Thai(c)  (0x0e00 <= c && c <= 0x0e7f) // Unicode definition for Thai

void SAL_CALL BreakIterator_th::makeIndex(const OUString& Text, sal_Int32 nStartPos)
    throw(RuntimeException)
{
    if (Text != cachedText) {
        cachedText = Text;
        if (cellIndexSize < cachedText.getLength()) {
        cellIndexSize = cachedText.getLength();
        free(nextCellIndex);
        free(previousCellIndex);
        nextCellIndex = (sal_Int32*) calloc(cellIndexSize, sizeof(sal_Int32));
        previousCellIndex = (sal_Int32*) calloc(cellIndexSize, sizeof(sal_Int32));
        }
        // reset nextCell for new Text
        memset(nextCellIndex, 0, cellIndexSize * sizeof(sal_Int32));
    }
    else if (nextCellIndex[nStartPos] > 0 || ! is_Thai(Text[nStartPos]))
        return;

    const sal_Unicode* str = cachedText.getStr();
    sal_Int32 len = cachedText.getLength(), startPos, endPos;

    startPos = nStartPos;
    while (startPos > 0 && is_Thai(str[startPos-1])) startPos--;
    endPos = nStartPos+1;
    while (endPos < len && is_Thai(str[endPos])) endPos++;

    sal_Int32 start, end, pos;
    pos = start = end = startPos;

    while (pos < endPos) {
        end += getACell(str, start, endPos);
        while (pos < end) {
        nextCellIndex[pos] = end;
        previousCellIndex[pos] = start;
        pos++;
        }
        start = end;
    }
}

} } } }
<commit_msg>INTEGRATION: CWS pchfix02 (1.9.56); FILE MERGED 2006/09/01 17:30:39 kaib 1.9.56.1: #i68856# Added header markers and pch files<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: breakiterator_th.cxx,v $
 *
 *  $Revision: 1.10 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 09:14:03 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"
#include <breakiterator_th.hxx>
#include <wtt.h>

#include <string.h> // for memset

using namespace ::com::sun::star::uno;
using namespace ::com::sun::star::lang;
using namespace ::rtl;

namespace com { namespace sun { namespace star { namespace i18n {

//  ----------------------------------------------------
//  class Breakiterator_th
//  ----------------------------------------------------;
BreakIterator_th::BreakIterator_th()
{
    cBreakIterator = "com.sun.star.i18n.BreakIterator_th";
    wordRule=lineRule=NULL;
}

BreakIterator_th::~BreakIterator_th()
{
}

#define SARA_AM 0x0E33

/*
 * cell composition states
 */

#define ST_COM  1   // Compose the following character with leading char and display in the same cell
#define ST_NXT  2   // display the following character in the next cell
#define ST_NDP  3   // non-display

static const sal_Int16 thaiCompRel[MAX_CT][MAX_CT] = {
    //  C  N  C  L  F  F  F  B  B  B  T  A  A  A  A  A  A
    //  T  O  O  V  V  V  V  V  V  D  O  D  D  D  V  V  V
    //  R  N  N     1  2  3  1  2     N  1  2  3  1  2  3
    //  L     S                       E
    //  0  1  2  3  4  5  6  7  8  9  10 11 12 13 14 15 16
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // CTRL 0
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // NON  1
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_COM, ST_COM, ST_COM, ST_COM, ST_COM, ST_COM, ST_COM, ST_COM, ST_COM, ST_COM   }, // CONS 2
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // LV   3
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // FV1  4
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // FV2  5
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // FV3  6
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_COM, ST_COM, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // BV1  7
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_COM, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // BV2  8
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // BD   9
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // TONE 10
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // AD1  11
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // AD2  12
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // AD3  13
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_COM, ST_COM, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // AV1  14
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_COM, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT   }, // AV2  15
    {   ST_NDP, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_NXT, ST_COM, ST_NXT, ST_COM, ST_NXT, ST_NXT, ST_NXT, ST_NXT   } // AV3  16

};

const sal_uInt32 is_ST_COM = (1<<CT_CTRL)|(1<<CT_NON)|(1<<CT_CONS)|(1<<CT_TONE);

static sal_uInt16 SAL_CALL getCombState(const sal_Unicode *text, sal_Int32 pos)
{
    sal_uInt16 ch1 = getCharType(text[pos]);
    sal_uInt16 ch2 = getCharType(text[pos+1]);

    if (text[pos+1] == SARA_AM) {
        if ((1 << ch1) & is_ST_COM)
        return  ST_COM;
        else
        ch2 = CT_AD1;
    }

    return thaiCompRel[ch1][ch2];
}

static sal_Int32 SAL_CALL getACell(const sal_Unicode *text, sal_Int32 pos, sal_Int32 len)
{
    sal_uInt32 curr = 1;
    for (; pos + 1 < len && getCombState(text, pos) == ST_COM; curr++, pos++) {}
    return curr;
}

#define is_Thai(c)  (0x0e00 <= c && c <= 0x0e7f) // Unicode definition for Thai

void SAL_CALL BreakIterator_th::makeIndex(const OUString& Text, sal_Int32 nStartPos)
    throw(RuntimeException)
{
    if (Text != cachedText) {
        cachedText = Text;
        if (cellIndexSize < cachedText.getLength()) {
        cellIndexSize = cachedText.getLength();
        free(nextCellIndex);
        free(previousCellIndex);
        nextCellIndex = (sal_Int32*) calloc(cellIndexSize, sizeof(sal_Int32));
        previousCellIndex = (sal_Int32*) calloc(cellIndexSize, sizeof(sal_Int32));
        }
        // reset nextCell for new Text
        memset(nextCellIndex, 0, cellIndexSize * sizeof(sal_Int32));
    }
    else if (nextCellIndex[nStartPos] > 0 || ! is_Thai(Text[nStartPos]))
        return;

    const sal_Unicode* str = cachedText.getStr();
    sal_Int32 len = cachedText.getLength(), startPos, endPos;

    startPos = nStartPos;
    while (startPos > 0 && is_Thai(str[startPos-1])) startPos--;
    endPos = nStartPos+1;
    while (endPos < len && is_Thai(str[endPos])) endPos++;

    sal_Int32 start, end, pos;
    pos = start = end = startPos;

    while (pos < endPos) {
        end += getACell(str, start, endPos);
        while (pos < end) {
        nextCellIndex[pos] = end;
        previousCellIndex[pos] = start;
        pos++;
        }
        start = end;
    }
}

} } } }
<|endoftext|>


<commit_before>//
//  LeveledTexturedMesh.cpp
//  G3MiOSSDK
//
//  Created by Diego Gomez Deck on 10/08/12.
//
//

#include "LeveledTexturedMesh.hpp"

#include "Vector3D.hpp"
#include "GL.hpp"
#include "TexturesHandler.hpp"

#include "GPUProgram.hpp"
#include "GPUProgramManager.hpp"
//#include "GPUProgramState.hpp"
#include "Camera.hpp"
#include "GLState.hpp"

void LazyTextureMapping::modifyGLState(GLState& state) const{
  if (!_initialized) {
    _initializer->initialize();

    _scale       = _initializer->getScale();
    _translation = _initializer->getTranslation();
    _texCoords   = _initializer->createTextCoords();

    delete _initializer;
    _initializer = NULL;

    _initialized = true;
  }

  if (_texCoords != NULL) {
    state.clearGLFeatureGroup(COLOR_GROUP);

    if (!_scale.isEquals(1.0, 1.0) || !_translation.isEquals(0.0, 0.0)) {

      state.addGLFeature(new TextureGLFeature(_glTextureId->getID(),
                                              _texCoords, 2, 0, false, 0,
                                              isTransparent(),
                                              GLBlendFactor::srcAlpha(),
                                              GLBlendFactor::oneMinusSrcAlpha(),    //BLEND
                                              true, _translation.asVector2D(), _scale.asVector2D()),
                         false); //TRANSFORM
    }
    else {
      state.addGLFeature(new TextureGLFeature(_glTextureId->getID(),
                                              _texCoords, 2, 0, false, 0,
                                              isTransparent(),
                                              GLBlendFactor::srcAlpha(),
                                              GLBlendFactor::oneMinusSrcAlpha(),    //BLEND
                                              false, Vector2D::zero(), Vector2D::zero() ),
                         false); //TRANSFORM
    }

  }
  else {
    ILogger::instance()->logError("LazyTextureMapping::bind() with _texCoords == NULL");
  }

}

void LazyTextureMapping::releaseGLTextureId() {
#ifdef C_CODE
  delete _glTextureId;
#endif
#ifdef JAVA_CODE
  _glTextureId.dispose();
#endif
  _glTextureId = NULL;
}

LeveledTexturedMesh::~LeveledTexturedMesh() {
#ifdef JAVA_CODE
  synchronized (this) {
#endif

    if (_ownedMesh) {
      delete _mesh;
    }

    if (_mappings != NULL) {
      for (int i = 0; i < _mappings->size(); i++) {
        LazyTextureMapping* mapping = _mappings->at(i);
        delete mapping;
      }

      delete _mappings;
      _mappings = NULL;
    }

    _glState->_release();

#ifdef JAVA_CODE
  }
#endif

#ifdef JAVA_CODE
  super.dispose();
#endif
}

int LeveledTexturedMesh::getVertexCount() const {
  return _mesh->getVertexCount();
}

const Vector3D LeveledTexturedMesh::getVertex(int i) const {
  return _mesh->getVertex(i);
}

BoundingVolume* LeveledTexturedMesh::getBoundingVolume() const {
  return (_mesh == NULL) ? NULL : _mesh->getBoundingVolume();
}

LazyTextureMapping* LeveledTexturedMesh::getCurrentTextureMapping() const {
  if (_currentLevel < 0) {
    int newCurrentLevel = -1;

    const int levelsCount = _mappings->size();

    for (int i = 0; i < levelsCount; i++) {
      const LazyTextureMapping* mapping = _mappings->at(i);
      if (mapping != NULL) {
        if (mapping->isValid()) {
          newCurrentLevel = i;
          break;
        }
      }
    }

    if (newCurrentLevel >= 0) {
      // ILogger::instance()->logInfo("LeveledTexturedMesh: changed from level %d to %d",
      //                              _currentLevel,
      //                              newCurrentLevel);
      _currentLevel = newCurrentLevel;

      _mappings->at(_currentLevel)->modifyGLState(*_glState);

      if (_currentLevel < levelsCount-1) {
        for (int i = levelsCount-1; i > _currentLevel; i--) {
          const LazyTextureMapping* mapping = _mappings->at(i);
          delete mapping;
#ifdef JAVA_CODE
          _mappings.remove(i);
#endif
        }
#ifdef C_CODE
        _mappings->erase(_mappings->begin() + _currentLevel + 1,
                         _mappings->end());
#endif
#ifdef JAVA_CODE
        _mappings.trimToSize();
#endif
      }
    }
  }

  return (_currentLevel >= 0) ? _mappings->at(_currentLevel) : NULL;
}

const TextureIDReference* LeveledTexturedMesh::getTopLevelTextureId() const {
  const LazyTextureMapping* mapping = getCurrentTextureMapping();
  if (mapping != NULL) {
    if (_currentLevel == 0) {
      return mapping->getGLTextureId();
    }
  }

  return NULL;
}

bool LeveledTexturedMesh::setGLTextureIdForLevel(int level,
                                                 const TextureIDReference* glTextureId) {

  if (_mappings->size() > 0) {
    if (glTextureId != NULL) {
      if ((_currentLevel < 0) || (level < _currentLevel)) {
        _mappings->at(level)->setGLTextureId(glTextureId);
        _currentLevel = -1;
        return true;
      }
    }
  }

  return false;
}

bool LeveledTexturedMesh::isTransparent(const G3MRenderContext* rc) const {
  if (_mesh->isTransparent(rc)) {
    return true;
  }

  LazyTextureMapping* mapping = getCurrentTextureMapping();

  return (mapping == NULL) ? false : mapping->isTransparent();
}

void LeveledTexturedMesh::render(const G3MRenderContext* rc,
                                 const GLState* parentGLState) const{
  LazyTextureMapping* mapping = getCurrentTextureMapping();
  if (mapping == NULL) {
    ILogger::instance()->logError("LeveledTexturedMesh: No Texture Mapping");
    _mesh->render(rc, parentGLState);
  }
  else {
    _glState->setParent(parentGLState);
    _mesh->render(rc, _glState);
  }
}
<commit_msg>Conversion<commit_after>//
//  LeveledTexturedMesh.cpp
//  G3MiOSSDK
//
//  Created by Diego Gomez Deck on 10/08/12.
//
//

#include "LeveledTexturedMesh.hpp"

#include "Vector3D.hpp"
#include "GL.hpp"
#include "TexturesHandler.hpp"

#include "GPUProgram.hpp"
#include "GPUProgramManager.hpp"
//#include "GPUProgramState.hpp"
#include "Camera.hpp"
#include "GLState.hpp"

void LazyTextureMapping::modifyGLState(GLState& state) const{
  if (!_initialized) {
    _initializer->initialize();

    _scale       = _initializer->getScale();
    _translation = _initializer->getTranslation();
    _texCoords   = _initializer->createTextCoords();

    delete _initializer;
    _initializer = NULL;

    _initialized = true;
  }

  if (_texCoords != NULL) {
    state.clearGLFeatureGroup(COLOR_GROUP);

    if (!_scale.isEquals(1.0, 1.0) || !_translation.isEquals(0.0, 0.0)) {

      state.addGLFeature(new TextureGLFeature(_glTextureId->getID(),
                                              _texCoords, 2, 0, false, 0,
                                              isTransparent(),
                                              GLBlendFactor::srcAlpha(),
                                              GLBlendFactor::oneMinusSrcAlpha(),    //BLEND
                                              true, _translation.asVector2D(), _scale.asVector2D()),
                         false); //TRANSFORM
    }
    else {
      state.addGLFeature(new TextureGLFeature(_glTextureId->getID(),
                                              _texCoords, 2, 0, false, 0,
                                              isTransparent(),
                                              GLBlendFactor::srcAlpha(),
                                              GLBlendFactor::oneMinusSrcAlpha(),    //BLEND
                                              false, Vector2D::zero(), Vector2D::zero() ),
                         false); //TRANSFORM
    }

  }
  else {
    ILogger::instance()->logError("LazyTextureMapping::bind() with _texCoords == NULL");
  }

}

void LazyTextureMapping::releaseGLTextureId() {
  if (_glTextureId != NULL){
#ifdef C_CODE
    delete _glTextureId;
#endif
#ifdef JAVA_CODE
    _glTextureId.dispose();
#endif
    _glTextureId = NULL;
  }
}

LeveledTexturedMesh::~LeveledTexturedMesh() {
#ifdef JAVA_CODE
  synchronized (this) {
#endif

    if (_ownedMesh) {
      delete _mesh;
    }

    if (_mappings != NULL) {
      for (int i = 0; i < _mappings->size(); i++) {
        LazyTextureMapping* mapping = _mappings->at(i);
        delete mapping;
      }

      delete _mappings;
      _mappings = NULL;
    }

    _glState->_release();

#ifdef JAVA_CODE
  }
#endif

#ifdef JAVA_CODE
  super.dispose();
#endif
}

int LeveledTexturedMesh::getVertexCount() const {
  return _mesh->getVertexCount();
}

const Vector3D LeveledTexturedMesh::getVertex(int i) const {
  return _mesh->getVertex(i);
}

BoundingVolume* LeveledTexturedMesh::getBoundingVolume() const {
  return (_mesh == NULL) ? NULL : _mesh->getBoundingVolume();
}

LazyTextureMapping* LeveledTexturedMesh::getCurrentTextureMapping() const {
  if (_currentLevel < 0) {
    int newCurrentLevel = -1;

    const int levelsCount = _mappings->size();

    for (int i = 0; i < levelsCount; i++) {
      const LazyTextureMapping* mapping = _mappings->at(i);
      if (mapping != NULL) {
        if (mapping->isValid()) {
          newCurrentLevel = i;
          break;
        }
      }
    }

    if (newCurrentLevel >= 0) {
      // ILogger::instance()->logInfo("LeveledTexturedMesh: changed from level %d to %d",
      //                              _currentLevel,
      //                              newCurrentLevel);
      _currentLevel = newCurrentLevel;

      _mappings->at(_currentLevel)->modifyGLState(*_glState);

      if (_currentLevel < levelsCount-1) {
        for (int i = levelsCount-1; i > _currentLevel; i--) {
          const LazyTextureMapping* mapping = _mappings->at(i);
          delete mapping;
#ifdef JAVA_CODE
          _mappings.remove(i);
#endif
        }
#ifdef C_CODE
        _mappings->erase(_mappings->begin() + _currentLevel + 1,
                         _mappings->end());
#endif
#ifdef JAVA_CODE
        _mappings.trimToSize();
#endif
      }
    }
  }

  return (_currentLevel >= 0) ? _mappings->at(_currentLevel) : NULL;
}

const TextureIDReference* LeveledTexturedMesh::getTopLevelTextureId() const {
  const LazyTextureMapping* mapping = getCurrentTextureMapping();
  if (mapping != NULL) {
    if (_currentLevel == 0) {
      return mapping->getGLTextureId();
    }
  }

  return NULL;
}

bool LeveledTexturedMesh::setGLTextureIdForLevel(int level,
                                                 const TextureIDReference* glTextureId) {

  if (_mappings->size() > 0) {
    if (glTextureId != NULL) {
      if ((_currentLevel < 0) || (level < _currentLevel)) {
        _mappings->at(level)->setGLTextureId(glTextureId);
        _currentLevel = -1;
        return true;
      }
    }
  }

  return false;
}

bool LeveledTexturedMesh::isTransparent(const G3MRenderContext* rc) const {
  if (_mesh->isTransparent(rc)) {
    return true;
  }

  LazyTextureMapping* mapping = getCurrentTextureMapping();

  return (mapping == NULL) ? false : mapping->isTransparent();
}

void LeveledTexturedMesh::render(const G3MRenderContext* rc,
                                 const GLState* parentGLState) const{
  LazyTextureMapping* mapping = getCurrentTextureMapping();
  if (mapping == NULL) {
    ILogger::instance()->logError("LeveledTexturedMesh: No Texture Mapping");
    _mesh->render(rc, parentGLState);
  }
  else {
    _glState->setParent(parentGLState);
    _mesh->render(rc, _glState);
  }
}
<|endoftext|>


<commit_before>//
//  TileRenderer.cpp
//  G3MiOSSDK
//
//  Created by Agustín Trujillo Pino on 12/06/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#include "TileRenderer.hpp"
#include "Tile.hpp"
#include "TileTessellator.hpp"
#include "TileTexturizer.hpp"
#include "Camera.hpp"
#include "ITimer.hpp"
#include "TilesRenderParameters.hpp"
#include "TouchEvent.hpp"
#include "LayerSet.hpp"
#include "VisibleSectorListener.hpp"
#include "IThreadUtils.hpp"

class VisibleSectorListenerEntry {
private:
  VisibleSectorListener* _listener;
  const long long        _stabilizationIntervalInMS;

  Sector* _lastSector;
  long long _whenNotifyInMS;

  ITimer*  _timer;

  ITimer* getTimer() {
    if (_timer == NULL) {
      _timer = IFactory::instance()->createTimer();
    }
    return _timer;
  }

public:
  VisibleSectorListenerEntry(VisibleSectorListener* listener,
                             const TimeInterval& stabilizationInterval) :
  _listener(listener),
  _stabilizationIntervalInMS(stabilizationInterval.milliseconds()),
  _lastSector(NULL),
  _timer(NULL),
  _whenNotifyInMS(0)
  {

  }

  void notifyListener(const Sector* visibleSector,
                      const G3MRenderContext* rc) const {
    const Geodetic3D cameraPosition = rc->getPlanet()->toGeodetic3D( rc->getCurrentCamera()->getCartesianPosition() );

    _listener->onVisibleSectorChange(*_lastSector, cameraPosition);
  }

  void tryToNotifyListener(const Sector* visibleSector,
                           const G3MRenderContext* rc) {
    if ( _stabilizationIntervalInMS == 0 ) {
      if ( (_lastSector == NULL) || (!_lastSector->isEqualsTo(*visibleSector)) ) {
        delete _lastSector;
        _lastSector = new Sector(*visibleSector);

        notifyListener(visibleSector, rc);
      }
    }
    else {
      const long long now = getTimer()->now().milliseconds();

      if ( (_lastSector == NULL) || (!_lastSector->isEqualsTo(*visibleSector)) ) {
        delete _lastSector;
        _lastSector = new Sector(*visibleSector);
        _whenNotifyInMS = now + _stabilizationIntervalInMS;
      }

      if (_whenNotifyInMS != 0) {
        if (now >= _whenNotifyInMS) {
          notifyListener(visibleSector, rc);

          _whenNotifyInMS = 0;
        }
      }
    }

  }

  ~VisibleSectorListenerEntry() {
    delete _listener;

    if (_timer != NULL) {
      IFactory::instance()->deleteTimer(_timer);
    }

    delete _lastSector;
  }
};

TileRenderer::TileRenderer(const TileTessellator* tessellator,
                           TileTexturizer*  texturizer,
                           LayerSet* layerSet,
                           const TilesRenderParameters* parameters,
                           bool showStatistics) :
_tessellator(tessellator),
_texturizer(texturizer),
_layerSet(layerSet),
_parameters(parameters),
_showStatistics(showStatistics),
_topTilesJustCreated(false),
_lastSplitTimer(NULL),
_lastCamera(NULL),
_firstRender(false),
_context(NULL),
_lastVisibleSector(NULL)
{
  _layerSet->setChangeListener(this);
}

void TileRenderer::recreateTiles() {
  pruneTopLevelTiles();
  clearTopLevelTiles();
  _firstRender = true;
  createTopLevelTiles(_context);
}

void TileRenderer::changed(const LayerSet* layerSet) {
  // recreateTiles();

  // recreateTiles() delete tiles, then meshes, and delete textures from the GPU so it has to be executed in the OpenGL thread
  class RecreateTilesTask : public GTask {
  private:
    TileRenderer* _tileRenderer;
  public:
    RecreateTilesTask(TileRenderer* tileRenderer) :
    _tileRenderer(tileRenderer)
    {
    }

    void run(const G3MContext* context) {
      _tileRenderer->recreateTiles();
    }
  };
  _context->getThreadUtils()->invokeInRendererThread(new RecreateTilesTask(this), true);

}

TileRenderer::~TileRenderer() {
  clearTopLevelTiles();

  delete _tessellator;
  delete _texturizer;
#ifdef C_CODE
  delete _parameters;
#endif

  delete _lastSplitTimer;

  delete _lastVisibleSector;

  const int visibleSectorListenersCount = _visibleSectorListeners.size();
  for (int i = 0; i < visibleSectorListenersCount; i++) {
    VisibleSectorListenerEntry* entry = _visibleSectorListeners[i];
    delete entry;
  }
}

void TileRenderer::clearTopLevelTiles() {
  for (int i = 0; i < _topLevelTiles.size(); i++) {
    Tile* tile = _topLevelTiles[i];
    delete tile;
  }

  _topLevelTiles.clear();
}

void TileRenderer::createTopLevelTiles(const G3MContext* context) {
  const Angle fromLatitude  = _parameters->_topSector.lower().latitude();
  const Angle fromLongitude = _parameters->_topSector.lower().longitude();

  const Angle deltaLan = _parameters->_topSector.getDeltaLatitude();
  const Angle deltaLon = _parameters->_topSector.getDeltaLongitude();

  const Angle tileHeight = deltaLan.div(_parameters->_splitsByLatitude);
  const Angle tileWidth = deltaLon.div(_parameters->_splitsByLongitude);

  for (int row = 0; row < _parameters->_splitsByLatitude; row++) {
    const Angle tileLatFrom = tileHeight.times(row).add(fromLatitude);
    const Angle tileLatTo = tileLatFrom.add(tileHeight);

    for (int col = 0; col < _parameters->_splitsByLongitude; col++) {
      const Angle tileLonFrom = tileWidth.times(col).add(fromLongitude);
      const Angle tileLonTo = tileLonFrom.add(tileWidth);

      const Geodetic2D tileLower(tileLatFrom, tileLonFrom);
      const Geodetic2D tileUpper(tileLatTo, tileLonTo);
      const Sector sector(tileLower, tileUpper);

      Tile* tile = new Tile(_texturizer, NULL, sector, _parameters->_topLevel, row, col);
      _topLevelTiles.push_back(tile);
    }
  }

  context->getLogger()->logInfo("Created %d top level tiles", _topLevelTiles.size());

  _topTilesJustCreated = true;
}

void TileRenderer::initialize(const G3MContext* context) {
  _context = context;

  clearTopLevelTiles();
  createTopLevelTiles(context);

  delete _lastSplitTimer;
  _lastSplitTimer = context->getFactory()->createTimer();

  _layerSet->initialize(context);
  _texturizer->initialize(context, _parameters);
}

bool TileRenderer::isReadyToRender(const G3MRenderContext *rc) {
  if (_topTilesJustCreated) {
    _topTilesJustCreated = false;

    const int topLevelTilesCount = _topLevelTiles.size();

    if (_parameters->_forceTopLevelTilesRenderOnStart) {
      TilesStatistics statistics;

      TileRenderContext trc(_tessellator,
                            _texturizer,
                            _layerSet,
                            _parameters,
                            &statistics,
                            _lastSplitTimer,
                            true);

      for (int i = 0; i < topLevelTilesCount; i++) {
        Tile* tile = _topLevelTiles[i];
        tile->prepareForFullRendering(rc, &trc);
      }
    }

    if (_texturizer != NULL) {
      for (int i = 0; i < topLevelTilesCount; i++) {
        Tile* tile = _topLevelTiles[i];
        _texturizer->justCreatedTopTile(rc, tile, _layerSet);
      }
    }
  }

  if (_parameters->_forceTopLevelTilesRenderOnStart) {
    const int topLevelTilesCount = _topLevelTiles.size();
    for (int i = 0; i < topLevelTilesCount; i++) {
      Tile* tile = _topLevelTiles[i];
      if (!tile->isTextureSolved()) {
        return false;
      }
    }

    if (_tessellator != NULL) {
      if (!_tessellator->isReady(rc)) {
        return false;
      }
    }

    if (_texturizer != NULL) {
      if (!_texturizer->isReady(rc, _layerSet)) {
        return false;
      }
    }
  }

  return true;
}

void TileRenderer::render(const G3MRenderContext* rc,
                          const GLState& parentState) {
  // Saving camera for use in onTouchEvent
  _lastCamera = rc->getCurrentCamera();

  TilesStatistics statistics;

  TileRenderContext trc(_tessellator,
                        _texturizer,
                        _layerSet,
                        _parameters,
                        &statistics,
                        _lastSplitTimer,
                        _firstRender /* if first render, force full render */);

  const int topLevelTilesCount = _topLevelTiles.size();

  if (_firstRender && _parameters->_forceTopLevelTilesRenderOnStart) {
    // force one render pass of the topLevel tiles to make the (toplevel) textures loaded
    // as they will be used as last-chance fallback texture for any tile.
    _firstRender = false;

    for (int i = 0; i < topLevelTilesCount; i++) {
      Tile* tile = _topLevelTiles[i];
      tile->render(rc,
                   &trc,
                   parentState,
                   NULL);
    }
  }
  else {
    std::list<Tile*> toVisit;
    for (int i = 0; i < topLevelTilesCount; i++) {
      toVisit.push_back(_topLevelTiles[i]);
    }

    while (toVisit.size() > 0) {
      std::list<Tile*> toVisitInNextIteration;

      for (std::list<Tile*>::iterator iter = toVisit.begin();
           iter != toVisit.end();
           iter++) {
        Tile* tile = *iter;

        tile->render(rc,
                     &trc,
                     parentState,
                     &toVisitInNextIteration);
      }

      toVisit = toVisitInNextIteration;
    }
  }

  if (_showStatistics) {
    statistics.log( rc->getLogger() );
  }

  const Sector* renderedSector = statistics.getRenderedSector();
  if (renderedSector != NULL) {
    if ( (_lastVisibleSector == NULL) || !renderedSector->isEqualsTo(*_lastVisibleSector) ) {
      delete _lastVisibleSector;
      _lastVisibleSector = new Sector(*renderedSector);
    }
  }

  if (_lastVisibleSector != NULL) {
    const int visibleSectorListenersCount = _visibleSectorListeners.size();
    for (int i = 0; i < visibleSectorListenersCount; i++) {
      VisibleSectorListenerEntry* entry = _visibleSectorListeners[i];

      entry->tryToNotifyListener(_lastVisibleSector, rc);
    }
  }

}

bool TileRenderer::onTouchEvent(const G3MEventContext* ec,
                                const TouchEvent* touchEvent) {
  bool handled = false;

  if (touchEvent->getType() == LongPress) {

    if (_lastCamera != NULL) {
      const Vector2I pixel = touchEvent->getTouch(0)->getPos();
      const Vector3D ray = _lastCamera->pixel2Ray(pixel);
      const Vector3D origin = _lastCamera->getCartesianPosition();

      const Planet* planet = ec->getPlanet();

      const Vector3D positionCartesian = planet->closestIntersection(origin, ray);
      if (positionCartesian.isNan()) {
        return false;
      }

      const Geodetic3D position = planet->toGeodetic3D(positionCartesian);

      for (int i = 0; i < _topLevelTiles.size(); i++) {
        const Tile* tile = _topLevelTiles[i]->getDeepestTileContaining(position);
        if (tile != NULL) {
          _texturizer->onTerrainTouchEvent(ec, position, tile, _layerSet);
          handled = true;
        }
      }
    }

  }

  return handled;
}

void TileRenderer::pruneTopLevelTiles() {
  for (int i = 0; i < _topLevelTiles.size(); i++) {
    Tile* tile = _topLevelTiles[i];
    tile->prune(_texturizer);
  }
}

void TileRenderer::addVisibleSectorListener(VisibleSectorListener* listener,
                                            const TimeInterval& stabilizationInterval) {
  _visibleSectorListeners.push_back( new VisibleSectorListenerEntry(listener,
                                                                    stabilizationInterval) );
}
<commit_msg>TileRenderer recreateTiles() now executed in the OpenGL Thread - Thank you Android for making my life harder<commit_after>//
//  TileRenderer.cpp
//  G3MiOSSDK
//
//  Created by Agustín Trujillo Pino on 12/06/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#include "TileRenderer.hpp"
#include "Tile.hpp"
#include "TileTessellator.hpp"
#include "TileTexturizer.hpp"
#include "Camera.hpp"
#include "ITimer.hpp"
#include "TilesRenderParameters.hpp"
#include "TouchEvent.hpp"
#include "LayerSet.hpp"
#include "VisibleSectorListener.hpp"
#include "IThreadUtils.hpp"

class VisibleSectorListenerEntry {
private:
  VisibleSectorListener* _listener;
  const long long        _stabilizationIntervalInMS;

  Sector* _lastSector;
  long long _whenNotifyInMS;

  ITimer*  _timer;

  ITimer* getTimer() {
    if (_timer == NULL) {
      _timer = IFactory::instance()->createTimer();
    }
    return _timer;
  }

public:
  VisibleSectorListenerEntry(VisibleSectorListener* listener,
                             const TimeInterval& stabilizationInterval) :
  _listener(listener),
  _stabilizationIntervalInMS(stabilizationInterval.milliseconds()),
  _lastSector(NULL),
  _timer(NULL),
  _whenNotifyInMS(0)
  {

  }

  void notifyListener(const Sector* visibleSector,
                      const G3MRenderContext* rc) const {
    const Geodetic3D cameraPosition = rc->getPlanet()->toGeodetic3D( rc->getCurrentCamera()->getCartesianPosition() );

    _listener->onVisibleSectorChange(*_lastSector, cameraPosition);
  }

  void tryToNotifyListener(const Sector* visibleSector,
                           const G3MRenderContext* rc) {
    if ( _stabilizationIntervalInMS == 0 ) {
      if ( (_lastSector == NULL) || (!_lastSector->isEqualsTo(*visibleSector)) ) {
        delete _lastSector;
        _lastSector = new Sector(*visibleSector);

        notifyListener(visibleSector, rc);
      }
    }
    else {
      const long long now = getTimer()->now().milliseconds();

      if ( (_lastSector == NULL) || (!_lastSector->isEqualsTo(*visibleSector)) ) {
        delete _lastSector;
        _lastSector = new Sector(*visibleSector);
        _whenNotifyInMS = now + _stabilizationIntervalInMS;
      }

      if (_whenNotifyInMS != 0) {
        if (now >= _whenNotifyInMS) {
          notifyListener(visibleSector, rc);

          _whenNotifyInMS = 0;
        }
      }
    }

  }

  ~VisibleSectorListenerEntry() {
    delete _listener;

    if (_timer != NULL) {
      IFactory::instance()->deleteTimer(_timer);
    }

    delete _lastSector;
  }
};

TileRenderer::TileRenderer(const TileTessellator* tessellator,
                           TileTexturizer*  texturizer,
                           LayerSet* layerSet,
                           const TilesRenderParameters* parameters,
                           bool showStatistics) :
_tessellator(tessellator),
_texturizer(texturizer),
_layerSet(layerSet),
_parameters(parameters),
_showStatistics(showStatistics),
_topTilesJustCreated(false),
_lastSplitTimer(NULL),
_lastCamera(NULL),
_firstRender(false),
_context(NULL),
_lastVisibleSector(NULL)
{
  _layerSet->setChangeListener(this);
}

void TileRenderer::recreateTiles() {
  pruneTopLevelTiles();
  clearTopLevelTiles();
  _firstRender = true;
  createTopLevelTiles(_context);
}

class RecreateTilesTask : public GTask {
private:
  TileRenderer* _tileRenderer;
public:
  RecreateTilesTask(TileRenderer* tileRenderer) :
  _tileRenderer(tileRenderer)
  {
  }

  void run(const G3MContext* context) {
    _tileRenderer->recreateTiles();
  }
};

void TileRenderer::changed(const LayerSet* layerSet) {
  // recreateTiles();

  // recreateTiles() delete tiles, then meshes, and delete textures from the GPU so it has to be executed in the OpenGL thread
  _context->getThreadUtils()->invokeInRendererThread(new RecreateTilesTask(this), true);
}

TileRenderer::~TileRenderer() {
  clearTopLevelTiles();

  delete _tessellator;
  delete _texturizer;
#ifdef C_CODE
  delete _parameters;
#endif

  delete _lastSplitTimer;

  delete _lastVisibleSector;

  const int visibleSectorListenersCount = _visibleSectorListeners.size();
  for (int i = 0; i < visibleSectorListenersCount; i++) {
    VisibleSectorListenerEntry* entry = _visibleSectorListeners[i];
    delete entry;
  }
}

void TileRenderer::clearTopLevelTiles() {
  for (int i = 0; i < _topLevelTiles.size(); i++) {
    Tile* tile = _topLevelTiles[i];
    delete tile;
  }

  _topLevelTiles.clear();
}

void TileRenderer::createTopLevelTiles(const G3MContext* context) {
  const Angle fromLatitude  = _parameters->_topSector.lower().latitude();
  const Angle fromLongitude = _parameters->_topSector.lower().longitude();

  const Angle deltaLan = _parameters->_topSector.getDeltaLatitude();
  const Angle deltaLon = _parameters->_topSector.getDeltaLongitude();

  const Angle tileHeight = deltaLan.div(_parameters->_splitsByLatitude);
  const Angle tileWidth = deltaLon.div(_parameters->_splitsByLongitude);

  for (int row = 0; row < _parameters->_splitsByLatitude; row++) {
    const Angle tileLatFrom = tileHeight.times(row).add(fromLatitude);
    const Angle tileLatTo = tileLatFrom.add(tileHeight);

    for (int col = 0; col < _parameters->_splitsByLongitude; col++) {
      const Angle tileLonFrom = tileWidth.times(col).add(fromLongitude);
      const Angle tileLonTo = tileLonFrom.add(tileWidth);

      const Geodetic2D tileLower(tileLatFrom, tileLonFrom);
      const Geodetic2D tileUpper(tileLatTo, tileLonTo);
      const Sector sector(tileLower, tileUpper);

      Tile* tile = new Tile(_texturizer, NULL, sector, _parameters->_topLevel, row, col);
      _topLevelTiles.push_back(tile);
    }
  }

  context->getLogger()->logInfo("Created %d top level tiles", _topLevelTiles.size());

  _topTilesJustCreated = true;
}

void TileRenderer::initialize(const G3MContext* context) {
  _context = context;

  clearTopLevelTiles();
  createTopLevelTiles(context);

  delete _lastSplitTimer;
  _lastSplitTimer = context->getFactory()->createTimer();

  _layerSet->initialize(context);
  _texturizer->initialize(context, _parameters);
}

bool TileRenderer::isReadyToRender(const G3MRenderContext *rc) {
  if (_topTilesJustCreated) {
    _topTilesJustCreated = false;

    const int topLevelTilesCount = _topLevelTiles.size();

    if (_parameters->_forceTopLevelTilesRenderOnStart) {
      TilesStatistics statistics;

      TileRenderContext trc(_tessellator,
                            _texturizer,
                            _layerSet,
                            _parameters,
                            &statistics,
                            _lastSplitTimer,
                            true);

      for (int i = 0; i < topLevelTilesCount; i++) {
        Tile* tile = _topLevelTiles[i];
        tile->prepareForFullRendering(rc, &trc);
      }
    }

    if (_texturizer != NULL) {
      for (int i = 0; i < topLevelTilesCount; i++) {
        Tile* tile = _topLevelTiles[i];
        _texturizer->justCreatedTopTile(rc, tile, _layerSet);
      }
    }
  }

  if (_parameters->_forceTopLevelTilesRenderOnStart) {
    const int topLevelTilesCount = _topLevelTiles.size();
    for (int i = 0; i < topLevelTilesCount; i++) {
      Tile* tile = _topLevelTiles[i];
      if (!tile->isTextureSolved()) {
        return false;
      }
    }

    if (_tessellator != NULL) {
      if (!_tessellator->isReady(rc)) {
        return false;
      }
    }

    if (_texturizer != NULL) {
      if (!_texturizer->isReady(rc, _layerSet)) {
        return false;
      }
    }
  }

  return true;
}

void TileRenderer::render(const G3MRenderContext* rc,
                          const GLState& parentState) {
  // Saving camera for use in onTouchEvent
  _lastCamera = rc->getCurrentCamera();

  TilesStatistics statistics;

  TileRenderContext trc(_tessellator,
                        _texturizer,
                        _layerSet,
                        _parameters,
                        &statistics,
                        _lastSplitTimer,
                        _firstRender /* if first render, force full render */);

  const int topLevelTilesCount = _topLevelTiles.size();

  if (_firstRender && _parameters->_forceTopLevelTilesRenderOnStart) {
    // force one render pass of the topLevel tiles to make the (toplevel) textures loaded
    // as they will be used as last-chance fallback texture for any tile.
    _firstRender = false;

    for (int i = 0; i < topLevelTilesCount; i++) {
      Tile* tile = _topLevelTiles[i];
      tile->render(rc,
                   &trc,
                   parentState,
                   NULL);
    }
  }
  else {
    std::list<Tile*> toVisit;
    for (int i = 0; i < topLevelTilesCount; i++) {
      toVisit.push_back(_topLevelTiles[i]);
    }

    while (toVisit.size() > 0) {
      std::list<Tile*> toVisitInNextIteration;

      for (std::list<Tile*>::iterator iter = toVisit.begin();
           iter != toVisit.end();
           iter++) {
        Tile* tile = *iter;

        tile->render(rc,
                     &trc,
                     parentState,
                     &toVisitInNextIteration);
      }

      toVisit = toVisitInNextIteration;
    }
  }

  if (_showStatistics) {
    statistics.log( rc->getLogger() );
  }

  const Sector* renderedSector = statistics.getRenderedSector();
  if (renderedSector != NULL) {
    if ( (_lastVisibleSector == NULL) || !renderedSector->isEqualsTo(*_lastVisibleSector) ) {
      delete _lastVisibleSector;
      _lastVisibleSector = new Sector(*renderedSector);
    }
  }

  if (_lastVisibleSector != NULL) {
    const int visibleSectorListenersCount = _visibleSectorListeners.size();
    for (int i = 0; i < visibleSectorListenersCount; i++) {
      VisibleSectorListenerEntry* entry = _visibleSectorListeners[i];

      entry->tryToNotifyListener(_lastVisibleSector, rc);
    }
  }

}

bool TileRenderer::onTouchEvent(const G3MEventContext* ec,
                                const TouchEvent* touchEvent) {
  bool handled = false;

  if (touchEvent->getType() == LongPress) {

    if (_lastCamera != NULL) {
      const Vector2I pixel = touchEvent->getTouch(0)->getPos();
      const Vector3D ray = _lastCamera->pixel2Ray(pixel);
      const Vector3D origin = _lastCamera->getCartesianPosition();

      const Planet* planet = ec->getPlanet();

      const Vector3D positionCartesian = planet->closestIntersection(origin, ray);
      if (positionCartesian.isNan()) {
        return false;
      }

      const Geodetic3D position = planet->toGeodetic3D(positionCartesian);

      for (int i = 0; i < _topLevelTiles.size(); i++) {
        const Tile* tile = _topLevelTiles[i]->getDeepestTileContaining(position);
        if (tile != NULL) {
          _texturizer->onTerrainTouchEvent(ec, position, tile, _layerSet);
          handled = true;
        }
      }
    }

  }

  return handled;
}

void TileRenderer::pruneTopLevelTiles() {
  for (int i = 0; i < _topLevelTiles.size(); i++) {
    Tile* tile = _topLevelTiles[i];
    tile->prune(_texturizer);
  }
}

void TileRenderer::addVisibleSectorListener(VisibleSectorListener* listener,
                                            const TimeInterval& stabilizationInterval) {
  _visibleSectorListeners.push_back( new VisibleSectorListenerEntry(listener,
                                                                    stabilizationInterval) );
}
<|endoftext|>