<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: fwkutil.cxx,v $
 *
 *  $Revision: 1.28 $
 *
 *  last change: $Author: ihi $ $Date: 2008-02-04 13:46:31 $
 *
 *  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_jvmfwk.hxx"

#if defined WNT
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#endif

#include <string>
#include <string.h>
#include "osl/mutex.hxx"
#include "osl/module.hxx"
#include "osl/thread.hxx"
#include "rtl/ustring.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/bootstrap.hxx"
#include "osl/file.hxx"
#include "osl/process.h"
#include "rtl/instance.hxx"
#include "rtl/uri.hxx"
#include "osl/getglobalmutex.hxx"
#include "com/sun/star/lang/IllegalArgumentException.hpp"
#include "cppuhelper/bootstrap.hxx"

#include "framework.hxx"
#include "fwkutil.hxx"

using namespace rtl;
using namespace osl;

namespace jfw
{

bool isAccessibilitySupportDesired()
{
    bool retVal = false;
#ifdef WNT
    HKEY    hKey = 0;
    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                     "Software\\OpenOffice.org\\Accessibility\\AtToolSupport",
                     0, KEY_READ, &hKey) == ERROR_SUCCESS)
    {
        DWORD   dwType = 0;
        DWORD   dwLen = 16;
        unsigned char arData[16];
        if( RegQueryValueEx(hKey, "SupportAssistiveTechnology", NULL, &dwType, arData,
                            & dwLen)== ERROR_SUCCESS)
        {
            if (dwType == REG_SZ)
            {
                if (strcmp((char*) arData, "true") == 0
                    || strcmp((char*) arData, "1") == 0)
                    retVal = true;
                else if (strcmp((char*) arData, "false") == 0
                         || strcmp((char*) arData, "0") == 0)
                    retVal = false;
#if OSL_DEBUG_LEVEL > 1
                else
                    OSL_ASSERT(0);
#endif
            }
            else if (dwType == REG_DWORD)
            {
                if (arData[0] == 1)
                    retVal = true;
                else if (arData[0] == 0)
                    retVal = false;
#if OSL_DEBUG_LEVEL > 1
                else
                    OSL_ASSERT(0);
#endif
            }
        }
    }
    RegCloseKey(hKey);

#elif UNX
    char buf[16];
    // use 2 shells to suppress the eventual "gcontool-2 not found" message
    // of the shell trying to execute the command
    FILE* fp = popen( "/bin/sh 2>/dev/null -c \"gconftool-2 -g /desktop/gnome/interface/accessibility\"", "r" );
    if( fp )
    {
        if( fgets( buf, sizeof(buf), fp ) )
        {
            int nCompare = strncasecmp( buf, "true", 4 );
            retVal = (nCompare == 0 ? true : false);
        }
        pclose( fp );
    }
#endif
    return retVal;
}

rtl::ByteSequence encodeBase16(const rtl::ByteSequence& rawData)
{
    static char EncodingTable[] =
        {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    sal_Int32 lenRaw = rawData.getLength();
    char* pBuf = new char[lenRaw * 2];
    const sal_Int8* arRaw = rawData.getConstArray();

    char* pCurBuf = pBuf;
    for (int i = 0; i < lenRaw; i++)
    {
        unsigned char curChar = arRaw[i];
        curChar >>= 4;

        *pCurBuf = EncodingTable[curChar];
        pCurBuf++;

        curChar = arRaw[i];
        curChar &= 0x0F;

        *pCurBuf = EncodingTable[curChar];
        pCurBuf++;
    }

    rtl::ByteSequence ret((sal_Int8*) pBuf, lenRaw * 2);
    delete [] pBuf;
    return ret;
}

rtl::ByteSequence decodeBase16(const rtl::ByteSequence& data)
{
    static char decodingTable[] =
        {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    sal_Int32 lenData = data.getLength();
    sal_Int32 lenBuf = lenData / 2; //always divisable by two
    unsigned char* pBuf = new unsigned char[lenBuf];
    const sal_Int8* pData = data.getConstArray();
    for (sal_Int32 i = 0; i < lenBuf; i++)
    {
        sal_Int8 curChar = *pData++;
        //find the index of the first 4bits
        //  TODO  What happens if text is not valid Hex characters?
        unsigned char nibble = 0;
        for (unsigned char j = 0; j < 16; j++)
        {
            if (curChar == decodingTable[j])
            {
                nibble = j;
                break;
            }
        }
        nibble <<= 4;
        curChar = *pData++;
        //find the index for the next 4bits
        for (unsigned char j = 0; j < 16; j++)
        {
            if (curChar == decodingTable[j])
            {
                nibble |= j;
                break;
            }
        }
        pBuf[i] = nibble;
    }
    rtl::ByteSequence ret((sal_Int8*) pBuf, lenBuf );
    delete [] pBuf;
    return ret;
}

rtl::OUString getDirFromFile(const rtl::OUString& usFilePath)
{
    sal_Int32 index= usFilePath.lastIndexOf('/');
    return rtl::OUString(usFilePath.getStr(), index);
}

rtl::OUString getFileFromURL(const rtl::OUString& sFileURL)
{
    sal_Int32 index= sFileURL.lastIndexOf('/');
    if (index == -1)
        return sFileURL;
    return sFileURL.copy(index + 1);
}

rtl::OUString getExecutableDirectory()
{
    rtl_uString* sExe = NULL;
    if (osl_getExecutableFile( & sExe) != osl_Process_E_None)
        throw FrameworkException(
            JFW_E_ERROR,
            "[Java framework] Error in function getApplicationBase (fwkutil.cxx)");

    rtl::OUString ouExe(sExe, SAL_NO_ACQUIRE);
    return getDirFromFile(ouExe);
}

rtl::OUString findPlugin(
    const rtl::OUString & baseUrl, const rtl::OUString & plugin)
{
    rtl::OUString expandedPlugin;
    try
    {
        expandedPlugin = cppu::bootstrap_expandUri(plugin);
    }
    catch (com::sun::star::lang::IllegalArgumentException & e)
    {
        throw FrameworkException(
            JFW_E_ERROR,
            (rtl::OString(
                RTL_CONSTASCII_STRINGPARAM(
                    "[Java framework] IllegalArgumentException in"
                    " findPlugin: "))
             + rtl::OUStringToOString(e.Message, osl_getThreadTextEncoding())));
    }
    rtl::OUString sUrl;
    try
    {
        sUrl = rtl::Uri::convertRelToAbs(baseUrl, expandedPlugin);
    }
    catch (rtl::MalformedUriException & e)
    {
        throw FrameworkException(
            JFW_E_ERROR,
            (rtl::OString(
                RTL_CONSTASCII_STRINGPARAM(
                    "[Java framework] rtl::MalformedUriException in"
                    " findPlugin: "))
             + rtl::OUStringToOString(
                 e.getMessage(), osl_getThreadTextEncoding())));
    }
    if (checkFileURL(sUrl) == jfw::FILE_OK)
    {
        return sUrl;
    }
    rtl::OUString retVal;
    rtl::OUString sProgDir = getExecutableDirectory();
    sUrl = sProgDir + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/"))
        + plugin;
    jfw::FileStatus s = checkFileURL(sUrl);
    if (s == jfw::FILE_INVALID || s == jfw::FILE_DOES_NOT_EXIST)
    {
        //If only the name of the library is given, then
        //use PATH, LD_LIBRARY_PATH etc. to locate the plugin
        if (plugin.indexOf('/') == -1)
        {
            rtl::OUString url;
#ifdef UNX
#ifdef MACOSX
            rtl::OUString path = rtl::OUString::createFromAscii("DYLD_LIBRARY_PATH");
#else
            rtl::OUString path = rtl::OUString::createFromAscii("LD_LIBRARY_PATH");
#endif
            rtl::OUString env_path;
            oslProcessError err = osl_getEnvironment(path.pData, &env_path.pData);
            if (err != osl_Process_E_None && err != osl_Process_E_NotFound)
                throw FrameworkException(
                    JFW_E_ERROR,
                    "[Java framework] Error in function findPlugin (fwkutil.cxx).");
            if (err == osl_Process_E_NotFound)
                return retVal;
            if (osl_searchFileURL(plugin.pData, env_path.pData, &url.pData)
                                == osl_File_E_None)
#else
            if (osl_searchFileURL(plugin.pData, NULL, &url.pData)
                == osl_File_E_None)
#endif
                retVal = url;
            else
                throw FrameworkException(
                    JFW_E_ERROR,
                    "[Java framework] Error in function findPlugin (fwkutil.cxx).");
        }
    }
    else
    {
        retVal = sUrl;
    }
    return retVal;
}

rtl::OUString getLibraryLocation()
{
    rtl::OString sExcMsg("[Java framework] Error in function getLibraryLocation "
                         "(fwkutil.cxx).");
    rtl::OUString libraryFileUrl;

    if (!osl::Module::getUrlFromAddress(
            reinterpret_cast< oslGenericFunction >(getLibraryLocation),
            libraryFileUrl))
        throw FrameworkException(JFW_E_ERROR, sExcMsg);

    return getDirFromFile(libraryFileUrl);
}

jfw::FileStatus checkFileURL(const rtl::OUString & sURL)
{
    jfw::FileStatus ret = jfw::FILE_OK;
    DirectoryItem item;
    File::RC rc_item = DirectoryItem::get(sURL, item);
    if (File::E_None == rc_item)
    {
        osl::FileStatus status(FileStatusMask_Validate);

        File::RC rc_stat = item.getFileStatus(status);
        if (File::E_None == rc_stat)
        {
            ret = FILE_OK;
        }
        else if (File::E_NOENT == rc_stat)
        {
            ret = FILE_DOES_NOT_EXIST;
        }
        else
        {
            ret = FILE_INVALID;
        }
    }
    else if (File::E_NOENT == rc_item)
    {
        ret = FILE_DOES_NOT_EXIST;
    }
    else
    {
        ret = FILE_INVALID;
    }
    return ret;
}

}
<commit_msg>INTEGRATION: CWS changefileheader (1.28.12); FILE MERGED 2008/03/31 07:24:51 rt 1.28.12.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: fwkutil.cxx,v $
 * $Revision: 1.29 $
 *
 * 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_jvmfwk.hxx"

#if defined WNT
#if defined _MSC_VER
#pragma warning(push, 1)
#endif
#include <windows.h>
#if defined _MSC_VER
#pragma warning(pop)
#endif
#endif

#include <string>
#include <string.h>
#include "osl/mutex.hxx"
#include "osl/module.hxx"
#include "osl/thread.hxx"
#include "rtl/ustring.hxx"
#include "rtl/ustrbuf.hxx"
#include "rtl/bootstrap.hxx"
#include "osl/file.hxx"
#include "osl/process.h"
#include "rtl/instance.hxx"
#include "rtl/uri.hxx"
#include "osl/getglobalmutex.hxx"
#include "com/sun/star/lang/IllegalArgumentException.hpp"
#include "cppuhelper/bootstrap.hxx"

#include "framework.hxx"
#include "fwkutil.hxx"

using namespace rtl;
using namespace osl;

namespace jfw
{

bool isAccessibilitySupportDesired()
{
    bool retVal = false;
#ifdef WNT
    HKEY    hKey = 0;
    if (RegOpenKeyEx(HKEY_CURRENT_USER,
                     "Software\\OpenOffice.org\\Accessibility\\AtToolSupport",
                     0, KEY_READ, &hKey) == ERROR_SUCCESS)
    {
        DWORD   dwType = 0;
        DWORD   dwLen = 16;
        unsigned char arData[16];
        if( RegQueryValueEx(hKey, "SupportAssistiveTechnology", NULL, &dwType, arData,
                            & dwLen)== ERROR_SUCCESS)
        {
            if (dwType == REG_SZ)
            {
                if (strcmp((char*) arData, "true") == 0
                    || strcmp((char*) arData, "1") == 0)
                    retVal = true;
                else if (strcmp((char*) arData, "false") == 0
                         || strcmp((char*) arData, "0") == 0)
                    retVal = false;
#if OSL_DEBUG_LEVEL > 1
                else
                    OSL_ASSERT(0);
#endif
            }
            else if (dwType == REG_DWORD)
            {
                if (arData[0] == 1)
                    retVal = true;
                else if (arData[0] == 0)
                    retVal = false;
#if OSL_DEBUG_LEVEL > 1
                else
                    OSL_ASSERT(0);
#endif
            }
        }
    }
    RegCloseKey(hKey);

#elif UNX
    char buf[16];
    // use 2 shells to suppress the eventual "gcontool-2 not found" message
    // of the shell trying to execute the command
    FILE* fp = popen( "/bin/sh 2>/dev/null -c \"gconftool-2 -g /desktop/gnome/interface/accessibility\"", "r" );
    if( fp )
    {
        if( fgets( buf, sizeof(buf), fp ) )
        {
            int nCompare = strncasecmp( buf, "true", 4 );
            retVal = (nCompare == 0 ? true : false);
        }
        pclose( fp );
    }
#endif
    return retVal;
}

rtl::ByteSequence encodeBase16(const rtl::ByteSequence& rawData)
{
    static char EncodingTable[] =
        {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    sal_Int32 lenRaw = rawData.getLength();
    char* pBuf = new char[lenRaw * 2];
    const sal_Int8* arRaw = rawData.getConstArray();

    char* pCurBuf = pBuf;
    for (int i = 0; i < lenRaw; i++)
    {
        unsigned char curChar = arRaw[i];
        curChar >>= 4;

        *pCurBuf = EncodingTable[curChar];
        pCurBuf++;

        curChar = arRaw[i];
        curChar &= 0x0F;

        *pCurBuf = EncodingTable[curChar];
        pCurBuf++;
    }

    rtl::ByteSequence ret((sal_Int8*) pBuf, lenRaw * 2);
    delete [] pBuf;
    return ret;
}

rtl::ByteSequence decodeBase16(const rtl::ByteSequence& data)
{
    static char decodingTable[] =
        {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    sal_Int32 lenData = data.getLength();
    sal_Int32 lenBuf = lenData / 2; //always divisable by two
    unsigned char* pBuf = new unsigned char[lenBuf];
    const sal_Int8* pData = data.getConstArray();
    for (sal_Int32 i = 0; i < lenBuf; i++)
    {
        sal_Int8 curChar = *pData++;
        //find the index of the first 4bits
        //  TODO  What happens if text is not valid Hex characters?
        unsigned char nibble = 0;
        for (unsigned char j = 0; j < 16; j++)
        {
            if (curChar == decodingTable[j])
            {
                nibble = j;
                break;
            }
        }
        nibble <<= 4;
        curChar = *pData++;
        //find the index for the next 4bits
        for (unsigned char j = 0; j < 16; j++)
        {
            if (curChar == decodingTable[j])
            {
                nibble |= j;
                break;
            }
        }
        pBuf[i] = nibble;
    }
    rtl::ByteSequence ret((sal_Int8*) pBuf, lenBuf );
    delete [] pBuf;
    return ret;
}

rtl::OUString getDirFromFile(const rtl::OUString& usFilePath)
{
    sal_Int32 index= usFilePath.lastIndexOf('/');
    return rtl::OUString(usFilePath.getStr(), index);
}

rtl::OUString getFileFromURL(const rtl::OUString& sFileURL)
{
    sal_Int32 index= sFileURL.lastIndexOf('/');
    if (index == -1)
        return sFileURL;
    return sFileURL.copy(index + 1);
}

rtl::OUString getExecutableDirectory()
{
    rtl_uString* sExe = NULL;
    if (osl_getExecutableFile( & sExe) != osl_Process_E_None)
        throw FrameworkException(
            JFW_E_ERROR,
            "[Java framework] Error in function getApplicationBase (fwkutil.cxx)");

    rtl::OUString ouExe(sExe, SAL_NO_ACQUIRE);
    return getDirFromFile(ouExe);
}

rtl::OUString findPlugin(
    const rtl::OUString & baseUrl, const rtl::OUString & plugin)
{
    rtl::OUString expandedPlugin;
    try
    {
        expandedPlugin = cppu::bootstrap_expandUri(plugin);
    }
    catch (com::sun::star::lang::IllegalArgumentException & e)
    {
        throw FrameworkException(
            JFW_E_ERROR,
            (rtl::OString(
                RTL_CONSTASCII_STRINGPARAM(
                    "[Java framework] IllegalArgumentException in"
                    " findPlugin: "))
             + rtl::OUStringToOString(e.Message, osl_getThreadTextEncoding())));
    }
    rtl::OUString sUrl;
    try
    {
        sUrl = rtl::Uri::convertRelToAbs(baseUrl, expandedPlugin);
    }
    catch (rtl::MalformedUriException & e)
    {
        throw FrameworkException(
            JFW_E_ERROR,
            (rtl::OString(
                RTL_CONSTASCII_STRINGPARAM(
                    "[Java framework] rtl::MalformedUriException in"
                    " findPlugin: "))
             + rtl::OUStringToOString(
                 e.getMessage(), osl_getThreadTextEncoding())));
    }
    if (checkFileURL(sUrl) == jfw::FILE_OK)
    {
        return sUrl;
    }
    rtl::OUString retVal;
    rtl::OUString sProgDir = getExecutableDirectory();
    sUrl = sProgDir + rtl::OUString(RTL_CONSTASCII_USTRINGPARAM("/"))
        + plugin;
    jfw::FileStatus s = checkFileURL(sUrl);
    if (s == jfw::FILE_INVALID || s == jfw::FILE_DOES_NOT_EXIST)
    {
        //If only the name of the library is given, then
        //use PATH, LD_LIBRARY_PATH etc. to locate the plugin
        if (plugin.indexOf('/') == -1)
        {
            rtl::OUString url;
#ifdef UNX
#ifdef MACOSX
            rtl::OUString path = rtl::OUString::createFromAscii("DYLD_LIBRARY_PATH");
#else
            rtl::OUString path = rtl::OUString::createFromAscii("LD_LIBRARY_PATH");
#endif
            rtl::OUString env_path;
            oslProcessError err = osl_getEnvironment(path.pData, &env_path.pData);
            if (err != osl_Process_E_None && err != osl_Process_E_NotFound)
                throw FrameworkException(
                    JFW_E_ERROR,
                    "[Java framework] Error in function findPlugin (fwkutil.cxx).");
            if (err == osl_Process_E_NotFound)
                return retVal;
            if (osl_searchFileURL(plugin.pData, env_path.pData, &url.pData)
                                == osl_File_E_None)
#else
            if (osl_searchFileURL(plugin.pData, NULL, &url.pData)
                == osl_File_E_None)
#endif
                retVal = url;
            else
                throw FrameworkException(
                    JFW_E_ERROR,
                    "[Java framework] Error in function findPlugin (fwkutil.cxx).");
        }
    }
    else
    {
        retVal = sUrl;
    }
    return retVal;
}

rtl::OUString getLibraryLocation()
{
    rtl::OString sExcMsg("[Java framework] Error in function getLibraryLocation "
                         "(fwkutil.cxx).");
    rtl::OUString libraryFileUrl;

    if (!osl::Module::getUrlFromAddress(
            reinterpret_cast< oslGenericFunction >(getLibraryLocation),
            libraryFileUrl))
        throw FrameworkException(JFW_E_ERROR, sExcMsg);

    return getDirFromFile(libraryFileUrl);
}

jfw::FileStatus checkFileURL(const rtl::OUString & sURL)
{
    jfw::FileStatus ret = jfw::FILE_OK;
    DirectoryItem item;
    File::RC rc_item = DirectoryItem::get(sURL, item);
    if (File::E_None == rc_item)
    {
        osl::FileStatus status(FileStatusMask_Validate);

        File::RC rc_stat = item.getFileStatus(status);
        if (File::E_None == rc_stat)
        {
            ret = FILE_OK;
        }
        else if (File::E_NOENT == rc_stat)
        {
            ret = FILE_DOES_NOT_EXIST;
        }
        else
        {
            ret = FILE_INVALID;
        }
    }
    else if (File::E_NOENT == rc_item)
    {
        ret = FILE_DOES_NOT_EXIST;
    }
    else
    {
        ret = FILE_INVALID;
    }
    return ret;
}

}
<|endoftext|>


<commit_before>
// PieceStructuresGen.cpp

// Declares the cPieceStructuresGen class representing the PieceStructures finisher generator

#include "Globals.h"
#include "PieceStructuresGen.h"
#include "PrefabStructure.h"
#include "PieceGeneratorBFSTree.h"
#include "../IniFile.h"
#include "../Stopwatch.h"

class cPieceStructuresGen::cGen:
	public cGridStructGen
{
	using Super = cGridStructGen;

public:

	cGen(int a_Seed, cBiomeGenPtr a_BiomeGen, cTerrainHeightGenPtr a_HeightGen, int a_SeaLevel, const AString & a_Name):
		Super(a_Seed),
		m_BiomeGen(std::move(a_BiomeGen)),
		m_HeightGen(std::move(a_HeightGen)),
		m_SeaLevel(a_SeaLevel),
		m_Name(a_Name),
		m_MaxDepth(5)
	{
	}

	/** Loads the piecepool from a file.
	Returns true on success, logs warning and returns false on failure. */
	bool LoadFromFile(const AString & a_FileName)
	{
		// Load the piecepool from the file, log any warnings:
		if (!m_PiecePool.LoadFromFile(a_FileName, true))
		{
			return false;
		}
		if (NoCaseCompare(m_PiecePool.GetIntendedUse(), "PieceStructures") != 0)
		{
			LOGWARNING("PieceStructures generator: File %s is intended for use in \"%s\", rather than piece structures. Loading the file, but the generator may behave unexpectedly.",
				a_FileName.c_str(), m_PiecePool.GetIntendedUse().c_str()
			);
		}
		m_PiecePool.AssignGens(m_Seed, m_BiomeGen, m_HeightGen, m_SeaLevel);

		// Apply generator params from the piecepool (in the metadata) into the generator:
		auto & generatorParams = m_PiecePool.GetAllMetadata();
		SetGeneratorParams(generatorParams);
		m_MaxDepth = GetStringMapInteger<int>(generatorParams, "MaxDepth", m_MaxDepth);

		return true;
	}

	// cGridStructGen overrides:
	virtual cStructurePtr CreateStructure(int a_GridX, int a_GridZ, int a_OriginX, int a_OriginZ) override
	{
		cStopwatch sw(Printf("CreateStructure for %s at <%d, %d>", m_Name.c_str(), a_GridX, a_GridZ));
		cPlacedPieces outPieces;
		cPieceGeneratorBFSTree pg(m_PiecePool, m_Seed);
		pg.PlacePieces(a_OriginX, a_OriginZ, m_MaxDepth, outPieces);
		return std::make_shared<cPrefabStructure>(a_GridX, a_GridZ, a_OriginX, a_OriginZ, std::move(outPieces), m_HeightGen);
	}

protected:

	/** The type used for storing a connection from one piece to another, while building the piece tree. */
	struct cConnection
	{
		cPiece * m_Piece;                  // The piece being connected
		cPiece::cConnector m_Connector;    // The piece's connector being used (relative non-rotated coords)
		int m_NumCCWRotations;             // Number of rotations necessary to match the two connectors
		int m_Weight;                      // Relative chance that this connection will be chosen

		cConnection(cPiece & a_Piece, cPiece::cConnector & a_Connector, int a_NumCCWRotations, int a_Weight);
	};
	typedef std::vector<cConnection> cConnections;

	/** The type used for storing a pool of connectors that will be attempted to expand by another piece. */
	struct cFreeConnector
	{
		cPlacedPiece * m_Piece;
		cPiece::cConnector m_Connector;

		cFreeConnector(cPlacedPiece * a_Piece, const cPiece::cConnector & a_Connector);
	};
	typedef std::vector<cFreeConnector> cFreeConnectors;

	/** The underlying biome generator that defines whether the structure is created or not */
	cBiomeGenPtr m_BiomeGen;

	/** The underlying height generator, used to position the prefabs crossing chunk borders if they are set to FitGround. */
	cTerrainHeightGenPtr m_HeightGen;

	/** The world's sea level, if available. Used for some cVerticalStrategy descendants. */
	int m_SeaLevel;

	/** The name that is used for reporting. */
	AString m_Name;

	/** All available prefabs. */
	cPrefabPiecePool m_PiecePool;

	/** Maximum depth of the generated piece tree. */
	int m_MaxDepth;
};

////////////////////////////////////////////////////////////////////////////////
// cPieceStructuresGen:

cPieceStructuresGen::cPieceStructuresGen(int a_Seed):
	m_Seed(a_Seed)
{
}

bool cPieceStructuresGen::Initialize(const AString & a_Prefabs, int a_SeaLevel, const cBiomeGenPtr & a_BiomeGen, const cTerrainHeightGenPtr & a_HeightGen)
{
	// Load each piecepool:
	auto structures = StringSplitAndTrim(a_Prefabs, "|");
	for (const auto & s: structures)
	{
		auto fileName = Printf("Prefabs%cPieceStructures%c%s.cubeset", cFile::PathSeparator(), cFile::PathSeparator(), s.c_str());
		if (!cFile::IsFile(fileName))
		{
			fileName.append(".gz");
			if (!cFile::IsFile(fileName))
			{
				LOGWARNING("Cannot load PieceStructures cubeset file %s", fileName.c_str());
				continue;
			}
		}
		auto gen = std::make_shared<cGen>(m_Seed, a_BiomeGen, a_HeightGen, a_SeaLevel, s);
		if (gen->LoadFromFile(fileName))
		{
			m_Gens.push_back(gen);
		}
	}

	// Report a warning if no generators available:
	if (m_Gens.empty())
	{
		LOGWARNING("The PieceStructures generator was asked to generate \"%s\", but none of the prefabs are valid.", a_Prefabs.c_str());
		return false;
	}
	return true;
}

void cPieceStructuresGen::GenFinish(cChunkDesc & a_Chunk)
{
	for (auto & gen: m_Gens)
	{
		gen->GenFinish(a_Chunk);
	}
}

<commit_msg>Remove debug output on PieceStructuresGen.cpp (#4984)<commit_after>
// PieceStructuresGen.cpp

// Declares the cPieceStructuresGen class representing the PieceStructures finisher generator

#include "Globals.h"
#include "PieceStructuresGen.h"
#include "PrefabStructure.h"
#include "PieceGeneratorBFSTree.h"
#include "../IniFile.h"

class cPieceStructuresGen::cGen:
	public cGridStructGen
{
	using Super = cGridStructGen;

public:

	cGen(int a_Seed, cBiomeGenPtr a_BiomeGen, cTerrainHeightGenPtr a_HeightGen, int a_SeaLevel, const AString & a_Name):
		Super(a_Seed),
		m_BiomeGen(std::move(a_BiomeGen)),
		m_HeightGen(std::move(a_HeightGen)),
		m_SeaLevel(a_SeaLevel),
		m_Name(a_Name),
		m_MaxDepth(5)
	{
	}

	/** Loads the piecepool from a file.
	Returns true on success, logs warning and returns false on failure. */
	bool LoadFromFile(const AString & a_FileName)
	{
		// Load the piecepool from the file, log any warnings:
		if (!m_PiecePool.LoadFromFile(a_FileName, true))
		{
			return false;
		}
		if (NoCaseCompare(m_PiecePool.GetIntendedUse(), "PieceStructures") != 0)
		{
			LOGWARNING("PieceStructures generator: File %s is intended for use in \"%s\", rather than piece structures. Loading the file, but the generator may behave unexpectedly.",
				a_FileName.c_str(), m_PiecePool.GetIntendedUse().c_str()
			);
		}
		m_PiecePool.AssignGens(m_Seed, m_BiomeGen, m_HeightGen, m_SeaLevel);

		// Apply generator params from the piecepool (in the metadata) into the generator:
		auto & GeneratorParams = m_PiecePool.GetAllMetadata();
		SetGeneratorParams(GeneratorParams);
		m_MaxDepth = GetStringMapInteger<int>(GeneratorParams, "MaxDepth", m_MaxDepth);

		return true;
	}

	// cGridStructGen overrides:
	virtual cStructurePtr CreateStructure(int a_GridX, int a_GridZ, int a_OriginX, int a_OriginZ) override
	{
		cPlacedPieces OutPieces;
		cPieceGeneratorBFSTree PieceTree(m_PiecePool, m_Seed);
		PieceTree.PlacePieces(a_OriginX, a_OriginZ, m_MaxDepth, OutPieces);
		return std::make_shared<cPrefabStructure>(a_GridX, a_GridZ, a_OriginX, a_OriginZ, std::move(OutPieces), m_HeightGen);
	}

protected:

	/** The type used for storing a connection from one piece to another, while building the piece tree. */
	struct cConnection
	{
		cPiece * m_Piece;                  // The piece being connected
		cPiece::cConnector m_Connector;    // The piece's connector being used (relative non-rotated coords)
		int m_NumCCWRotations;             // Number of rotations necessary to match the two connectors
		int m_Weight;                      // Relative chance that this connection will be chosen

		cConnection(cPiece & a_Piece, cPiece::cConnector & a_Connector, int a_NumCCWRotations, int a_Weight);
	};
	typedef std::vector<cConnection> cConnections;

	/** The type used for storing a pool of connectors that will be attempted to expand by another piece. */
	struct cFreeConnector
	{
		cPlacedPiece * m_Piece;
		cPiece::cConnector m_Connector;

		cFreeConnector(cPlacedPiece * a_Piece, const cPiece::cConnector & a_Connector);
	};
	typedef std::vector<cFreeConnector> cFreeConnectors;

	/** The underlying biome generator that defines whether the structure is created or not */
	cBiomeGenPtr m_BiomeGen;

	/** The underlying height generator, used to position the prefabs crossing chunk borders if they are set to FitGround. */
	cTerrainHeightGenPtr m_HeightGen;

	/** The world's sea level, if available. Used for some cVerticalStrategy descendants. */
	int m_SeaLevel;

	/** The name that is used for reporting. */
	AString m_Name;

	/** All available prefabs. */
	cPrefabPiecePool m_PiecePool;

	/** Maximum depth of the generated piece tree. */
	int m_MaxDepth;
};

////////////////////////////////////////////////////////////////////////////////
// cPieceStructuresGen:

cPieceStructuresGen::cPieceStructuresGen(int a_Seed):
	m_Seed(a_Seed)
{
}

bool cPieceStructuresGen::Initialize(const AString & a_Prefabs, int a_SeaLevel, const cBiomeGenPtr & a_BiomeGen, const cTerrainHeightGenPtr & a_HeightGen)
{
	// Load each piecepool:
	auto Structures = StringSplitAndTrim(a_Prefabs, "|");
	for (const auto & Structure : Structures)
	{
		auto FileName = Printf("Prefabs%cPieceStructures%c%s.cubeset", cFile::PathSeparator(), cFile::PathSeparator(), Structure.c_str());
		if (!cFile::IsFile(FileName))
		{
			FileName.append(".gz");
			if (!cFile::IsFile(FileName))
			{
				LOGWARNING("Cannot load PieceStructures cubeset file %s", FileName.c_str());
				continue;
			}
		}
		auto Gen = std::make_shared<cGen>(m_Seed, a_BiomeGen, a_HeightGen, a_SeaLevel, Structure);
		if (Gen->LoadFromFile(FileName))
		{
			m_Gens.push_back(Gen);
		}
	}

	// Report a warning if no generators available:
	if (m_Gens.empty())
	{
		LOGWARNING("The PieceStructures generator was asked to generate \"%s\", but none of the prefabs are valid.", a_Prefabs.c_str());
		return false;
	}
	return true;
}

void cPieceStructuresGen::GenFinish(cChunkDesc & a_Chunk)
{
	for (auto & Gen : m_Gens)
	{
		Gen->GenFinish(a_Chunk);
	}
}

<|endoftext|>


<commit_before>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2009 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"

#include "OgreGLES2Prerequisites.h"
#include "OgreGLES2RenderSystem.h"

#include "OgreX11EGLSupport.h"
#include "OgreX11EGLWindow.h"
#include "OgreX11EGLRenderTexture.h"
#include "OgreX11EGLContext.h"

#if (OGRE_PLATFORM != OGRE_PLATFORM_LINUX)
	void XStringListToTextProperty(char ** prop, int num, XTextProperty * textProp){};
	Window DefaultRootWindow(Display* nativeDisplayType){return Window();};
	bool XQueryExtension(Display* nativeDisplayType, char * name, int * dummy0, int * dummy2, int * dummy3){return 0;}
	XRRScreenConfiguration * XRRGetScreenInfo(Display* nativeDisplayType, Window window ){return 0;};
	int XRRConfigCurrentConfiguration(XRRScreenConfiguration * config, Rotation * rotation){return 0;};
	XRRScreenSize * XRRConfigSizes(XRRScreenConfiguration * config, int * nSizes){return 0;};
	int XRRConfigCurrentRate(XRRScreenConfiguration * config){return 0;};
	short * XRRConfigRates(XRRScreenConfiguration * config, int sizeID, int * nRates){return 0;};
	void XRRFreeScreenConfigInfo(XRRScreenConfiguration * config){}
	int DefaultScreen(NativeDisplayType nativeDisplayType){return 0;};
	int DisplayWidth(Display* nativeDisplayType, int screen){return 0;};
	int DisplayHeight(Display* nativeDisplayType, int screen){return 0;};
	Display* XOpenDisplay(int num){return NULL;};
	void XCloseDisplay(Display* nativeDisplayType){};
	Atom XInternAtom(Display* nativeDisplayType, char * name, X11Bool isTrue) {return Atom();};
	char * DisplayString(NativeDisplayType nativeDisplayType){return 0;};
	const char * XDisplayName(char * name){return 0;};
	Visual * DefaultVisual(Display* nativeDisplayType,  int screen){return 0;};
	int XVisualIDFromVisual(Visual *v){return 0;};
	void XRRSetScreenConfigAndRate(Display* nativeDisplayType, XRRScreenConfiguration * config, Window window, int size, Rotation rotation, int mode, int currentTime ){};
	XVisualInfo * XGetVisualInfo(Display* nativeDisplayType,  int mask, XVisualInfo * info, int * n){return 0;};
	typedef int (*XErrorHandler)(Display *, XErrorEvent*);
	XErrorHandler XSetErrorHandler(XErrorHandler xErrorHandler){return 0;};
	void XDestroyWindow(Display* nativeDisplayType, Window nativeWindowType){};
	bool XGetWindowAttributes(Display* nativeDisplayType, Window nativeWindowType, XWindowAttributes * xWindowAttributes){return 0;};
	int XCreateColormap(Display* nativeDisplayType, Window nativeWindowType, int visual, int allocNone){return 0;};
	Window XCreateWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top, int width, int height, int dummy1, int depth, int inputOutput, int visual, int mask, XSetWindowAttributes * xSetWindowAttributes){return Window();};
	void XFree(void *data){};
	XWMHints * XAllocWMHints(){return 0;};
	XSizeHints * XAllocSizeHints(){return 0;};
	void XSetWMProperties(Display* nativeDisplayType, Window nativeWindowType,XTextProperty * titleprop, char * dummy1, char * dummy2, int num, XSizeHints *sizeHints, XWMHints *wmHints, char * dummy3){};
	void XSetWMProtocols(Display* nativeDisplayType, Window nativeWindowType, Atom * atom, int num){};
	void XMapWindow(Display* nativeDisplayType, Window nativeWindowType){};
	void XFlush(Display* nativeDisplayType){};
	void XMoveWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top){};
	void XResizeWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top){};
	void XQueryTree(Display* nativeDisplayType, Window nativeWindowType, Window * root, Window *parent, Window **children, unsigned int * nChildren){};
	void XSendEvent(Display* nativeDisplayType, Window nativeWindowType, int dummy1, int mask, XEvent* xevent){};
#endif

namespace Ogre {

    X11EGLSupport::X11EGLSupport()
    {
	mNativeDisplay = getNativeDisplay();
        mGLDisplay = getGLDisplay();

	int dummy;

	// TODO: Probe video modes
        mCurrentMode.first.first = 1280;
        mCurrentMode.first.second = 1024;
//            mCurrentMode.first.first = DisplayWidth((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
//            mCurrentMode.first.second = DisplayHeight((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
        mCurrentMode.second = 0;
        mOriginalMode = mCurrentMode;
        mVideoModes.push_back(mCurrentMode);

	EGLConfig *glConfigs;
        int config, nConfigs = 0;

        glConfigs = chooseGLConfig(NULL, &nConfigs);

        for (config = 0; config < nConfigs; config++)
        {
            int caveat, samples;

            getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat);

            if (caveat != EGL_SLOW_CONFIG)
            {
                getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples);
                mSampleLevels.push_back(StringConverter::toString(samples));
            }
        }

        free(glConfigs);

        removeDuplicates(mSampleLevels);
    }

    X11EGLSupport::~X11EGLSupport()
    {
        if (mNativeDisplay)
        {
            XCloseDisplay((Display*)mNativeDisplay);
        }

        if (mGLDisplay)
        {
            eglTerminate(mGLDisplay);
        }
    }

    NativeDisplayType X11EGLSupport::getNativeDisplay()
    {
        if (!mNativeDisplay)
        {
	    mNativeDisplay = (NativeDisplayType)XOpenDisplay(NULL);

            if (!mNativeDisplay)
            {
                OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                            "Couldn`t open X display",
                            "X11EGLSupport::getXDisplay");
            }

            mAtomDeleteWindow = XInternAtom((Display*)mNativeDisplay, "WM_DELETE_WINDOW", True);
            mAtomFullScreen = XInternAtom((Display*)mNativeDisplay, "_NET_WM_STATE_FULLSCREEN", True);
            mAtomState = XInternAtom((Display*)mNativeDisplay, "_NET_WM_STATE", True);
        }

        return mNativeDisplay;
    }

    String X11EGLSupport::getDisplayName(void)
    {
		return String((const char*)XDisplayName(DisplayString(mNativeDisplay)));
    }

    void X11EGLSupport::switchMode(uint& width, uint& height, short& frequency)
    {
//        if (!mRandr)
//            return;

        int size = 0;
        int newSize = -1;

        VideoModes::iterator mode;
        VideoModes::iterator end = mVideoModes.end();
        VideoMode *newMode = 0;

        for(mode = mVideoModes.begin(); mode != end; size++)
        {
            if (mode->first.first >= static_cast<int>(width) &&
                mode->first.second >= static_cast<int>(height))
            {
                if (!newMode ||
                    mode->first.first < newMode->first.first ||
                    mode->first.second < newMode->first.second)
                {
                    newSize = size;
                    newMode = &(*mode);
                }
            }

            VideoMode* lastMode = &(*mode);

            while (++mode != end && mode->first == lastMode->first)
            {
                if (lastMode == newMode && mode->second == frequency)
                {
                    newMode = &(*mode);
                }
            }
        }

        if (newMode && *newMode != mCurrentMode)
        {
            XWindowAttributes winAtt;
            newMode->first.first = DisplayWidth(mNativeDisplay, 0);
            newMode->first.second = DisplayHeight(mNativeDisplay, 0);
            newMode->second = 0; // TODO: Hardcoding refresh rate for LCD's
            mCurrentMode = *newMode;
        }
    }

    XVisualInfo *X11EGLSupport::getVisualFromFBConfig(::EGLConfig glConfig)
    {
        XVisualInfo *vi, tmp;
        int vid, n;
        ::EGLDisplay glDisplay;

        glDisplay = getGLDisplay();
        mNativeDisplay = getNativeDisplay();

        if (eglGetConfigAttrib(glDisplay, glConfig, EGL_NATIVE_VISUAL_ID, &vid) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to get VISUAL_ID from glConfig",
                        __FUNCTION__);
            return 0;
        }
	EGL_CHECK_ERROR

        if (vid == 0)
        {
            const int screen_number = DefaultScreen(mNativeDisplay);
            Visual *v = DefaultVisual((Display*)mNativeDisplay, screen_number);
            vid = XVisualIDFromVisual(v);
        }

        tmp.visualid = vid;
        vi = 0;
        vi = XGetVisualInfo((Display*)mNativeDisplay,
                            VisualIDMask,
                            &tmp, &n);
        if (vi == 0)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to get X11 VISUAL",
                        __FUNCTION__);
            return 0;
        }

        return vi;
    }

    RenderWindow* X11EGLSupport::newWindow(const String &name,
                                        unsigned int width, unsigned int height,
                                        bool fullScreen,
                                        const NameValuePairList *miscParams)
    {
	EGLWindow* window = new X11EGLWindow(this);
        window->create(name, width, height, fullScreen, miscParams);

        return window;
    }

	//X11EGLSupport::getGLDisplay sets up the native variable
	//then calls EGLSupport::getGLDisplay
    EGLDisplay X11EGLSupport::getGLDisplay()
    {
	if (!mGLDisplay)
	{
		if(!mNativeDisplay)
			mNativeDisplay = getNativeDisplay();
		return EGLSupport::getGLDisplay();
	}
	return mGLDisplay;
    }

}

<commit_msg>GLES2: Forgot this file in last commit<commit_after>/*
-----------------------------------------------------------------------------
This source file is part of OGRE
    (Object-oriented Graphics Rendering Engine)
For the latest info, see http://www.ogre3d.org/

Copyright (c) 2008 Renato Araujo Oliveira Filho <renatox@gmail.com>
Copyright (c) 2000-2009 Torus Knot Software Ltd

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
-----------------------------------------------------------------------------
*/

#include "OgreException.h"
#include "OgreLogManager.h"
#include "OgreStringConverter.h"
#include "OgreRoot.h"

#include "OgreGLES2Prerequisites.h"
#include "OgreGLES2RenderSystem.h"

#include "OgreX11EGLSupport.h"
#include "OgreX11EGLWindow.h"
#include "OgreX11EGLRenderTexture.h"
#include "OgreX11EGLContext.h"

#if (OGRE_PLATFORM != OGRE_PLATFORM_LINUX) && (OGRE_PLATFORM != OGRE_PLATFORM_TEGRA2)
	void XStringListToTextProperty(char ** prop, int num, XTextProperty * textProp){};
	Window DefaultRootWindow(Display* nativeDisplayType){return Window();};
	bool XQueryExtension(Display* nativeDisplayType, char * name, int * dummy0, int * dummy2, int * dummy3){return 0;}
	XRRScreenConfiguration * XRRGetScreenInfo(Display* nativeDisplayType, Window window ){return 0;};
	int XRRConfigCurrentConfiguration(XRRScreenConfiguration * config, Rotation * rotation){return 0;};
	XRRScreenSize * XRRConfigSizes(XRRScreenConfiguration * config, int * nSizes){return 0;};
	int XRRConfigCurrentRate(XRRScreenConfiguration * config){return 0;};
	short * XRRConfigRates(XRRScreenConfiguration * config, int sizeID, int * nRates){return 0;};
	void XRRFreeScreenConfigInfo(XRRScreenConfiguration * config){}
	int DefaultScreen(NativeDisplayType nativeDisplayType){return 0;};
	int DisplayWidth(Display* nativeDisplayType, int screen){return 0;};
	int DisplayHeight(Display* nativeDisplayType, int screen){return 0;};
	Display* XOpenDisplay(int num){return NULL;};
	void XCloseDisplay(Display* nativeDisplayType){};
	Atom XInternAtom(Display* nativeDisplayType, char * name, X11Bool isTrue) {return Atom();};
	char * DisplayString(NativeDisplayType nativeDisplayType){return 0;};
	const char * XDisplayName(char * name){return 0;};
	Visual * DefaultVisual(Display* nativeDisplayType,  int screen){return 0;};
	int XVisualIDFromVisual(Visual *v){return 0;};
	void XRRSetScreenConfigAndRate(Display* nativeDisplayType, XRRScreenConfiguration * config, Window window, int size, Rotation rotation, int mode, int currentTime ){};
	XVisualInfo * XGetVisualInfo(Display* nativeDisplayType,  int mask, XVisualInfo * info, int * n){return 0;};
	typedef int (*XErrorHandler)(Display *, XErrorEvent*);
	XErrorHandler XSetErrorHandler(XErrorHandler xErrorHandler){return 0;};
	void XDestroyWindow(Display* nativeDisplayType, Window nativeWindowType){};
	bool XGetWindowAttributes(Display* nativeDisplayType, Window nativeWindowType, XWindowAttributes * xWindowAttributes){return 0;};
	int XCreateColormap(Display* nativeDisplayType, Window nativeWindowType, int visual, int allocNone){return 0;};
	Window XCreateWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top, int width, int height, int dummy1, int depth, int inputOutput, int visual, int mask, XSetWindowAttributes * xSetWindowAttributes){return Window();};
	void XFree(void *data){};
	XWMHints * XAllocWMHints(){return 0;};
	XSizeHints * XAllocSizeHints(){return 0;};
	void XSetWMProperties(Display* nativeDisplayType, Window nativeWindowType,XTextProperty * titleprop, char * dummy1, char * dummy2, int num, XSizeHints *sizeHints, XWMHints *wmHints, char * dummy3){};
	void XSetWMProtocols(Display* nativeDisplayType, Window nativeWindowType, Atom * atom, int num){};
	void XMapWindow(Display* nativeDisplayType, Window nativeWindowType){};
	void XFlush(Display* nativeDisplayType){};
	void XMoveWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top){};
	void XResizeWindow(Display* nativeDisplayType, Window nativeWindowType, int left, int top){};
	void XQueryTree(Display* nativeDisplayType, Window nativeWindowType, Window * root, Window *parent, Window **children, unsigned int * nChildren){};
	void XSendEvent(Display* nativeDisplayType, Window nativeWindowType, int dummy1, int mask, XEvent* xevent){};
#endif

namespace Ogre {

    X11EGLSupport::X11EGLSupport()
    {
		// A connection that might be shared with the application for GL rendering:
        mGLDisplay = getGLDisplay();

 		// A connection that is NOT shared to enable independent event processing:
        mNativeDisplay = getNativeDisplay();

        int dummy = 0;

	// TODO: Probe video modes
        mCurrentMode.first.first = 1280;
        mCurrentMode.first.second = 1024;
//            mCurrentMode.first.first = DisplayWidth((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
//            mCurrentMode.first.second = DisplayHeight((Display*)mNativeDisplay, DefaultScreen(mNativeDisplay));
        mCurrentMode.second = 0;
        mOriginalMode = mCurrentMode;
        mVideoModes.push_back(mCurrentMode);

        EGLConfig *glConfigs;
        int config, nConfigs = 0;

        glConfigs = chooseGLConfig(NULL, &nConfigs);

        for (config = 0; config < nConfigs; config++)
        {
            int caveat, samples;

            getGLConfigAttrib(glConfigs[config], EGL_CONFIG_CAVEAT, &caveat);

            if (caveat != EGL_SLOW_CONFIG)
            {
                getGLConfigAttrib(glConfigs[config], EGL_SAMPLES, &samples);
                mSampleLevels.push_back(StringConverter::toString(samples));
            }
        }

        free(glConfigs);

        removeDuplicates(mSampleLevels);
    }

    X11EGLSupport::~X11EGLSupport()
    {
        if (mNativeDisplay)
        {
            XCloseDisplay((Display*)mNativeDisplay);
        }

        if (mGLDisplay)
        {
            eglTerminate(mGLDisplay);
        }
    }

    NativeDisplayType X11EGLSupport::getNativeDisplay()
    {
        if (!mNativeDisplay)
        {
	    mNativeDisplay = (NativeDisplayType)XOpenDisplay(NULL);

            if (!mNativeDisplay)
            {
                OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                            "Couldn`t open X display",
                            "X11EGLSupport::getXDisplay");
            }

            mAtomDeleteWindow = XInternAtom((Display*)mNativeDisplay, "WM_DELETE_WINDOW", True);
            mAtomFullScreen = XInternAtom((Display*)mNativeDisplay, "_NET_WM_STATE_FULLSCREEN", True);
            mAtomState = XInternAtom((Display*)mNativeDisplay, "_NET_WM_STATE", True);
        }

        return mNativeDisplay;
    }

    String X11EGLSupport::getDisplayName(void)
    {
		return String((const char*)XDisplayName(DisplayString(mNativeDisplay)));
    }

    void X11EGLSupport::switchMode(uint& width, uint& height, short& frequency)
    {
//        if (!mRandr)
//            return;

        int size = 0;
        int newSize = -1;

        VideoModes::iterator mode;
        VideoModes::iterator end = mVideoModes.end();
        VideoMode *newMode = 0;

        for(mode = mVideoModes.begin(); mode != end; size++)
        {
            if (mode->first.first >= static_cast<int>(width) &&
                mode->first.second >= static_cast<int>(height))
            {
                if (!newMode ||
                    mode->first.first < newMode->first.first ||
                    mode->first.second < newMode->first.second)
                {
                    newSize = size;
                    newMode = &(*mode);
                }
            }

            VideoMode* lastMode = &(*mode);

            while (++mode != end && mode->first == lastMode->first)
            {
                if (lastMode == newMode && mode->second == frequency)
                {
                    newMode = &(*mode);
                }
            }
        }

        if (newMode && *newMode != mCurrentMode)
        {
            XWindowAttributes winAtt;
            newMode->first.first = DisplayWidth(mNativeDisplay, 0);
            newMode->first.second = DisplayHeight(mNativeDisplay, 0);
            newMode->second = 0; // TODO: Hardcoding refresh rate for LCD's
            mCurrentMode = *newMode;
        }
    }

    XVisualInfo *X11EGLSupport::getVisualFromFBConfig(::EGLConfig glConfig)
    {
        XVisualInfo *vi, tmp;
        int vid, n;
        ::EGLDisplay glDisplay;

        glDisplay = getGLDisplay();
        mNativeDisplay = getNativeDisplay();

        if (eglGetConfigAttrib(glDisplay, glConfig, EGL_NATIVE_VISUAL_ID, &vid) == EGL_FALSE)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to get VISUAL_ID from glConfig",
                        __FUNCTION__);
            return 0;
        }
        EGL_CHECK_ERROR

        if (vid == 0)
        {
            const int screen_number = DefaultScreen(mNativeDisplay);
            Visual *v = DefaultVisual((Display*)mNativeDisplay, screen_number);
            vid = XVisualIDFromVisual(v);
        }

        tmp.visualid = vid;
        vi = 0;
        vi = XGetVisualInfo((Display*)mNativeDisplay,
                            VisualIDMask,
                            &tmp, &n);
        if (vi == 0)
        {
            OGRE_EXCEPT(Exception::ERR_RENDERINGAPI_ERROR,
                        "Fail to get X11 VISUAL",
                        __FUNCTION__);
            return 0;
        }

        return vi;
    }

    RenderWindow* X11EGLSupport::newWindow(const String &name,
                                        unsigned int width, unsigned int height,
                                        bool fullScreen,
                                        const NameValuePairList *miscParams)
    {
        EGLWindow* window = new X11EGLWindow(this);
        window->create(name, width, height, fullScreen, miscParams);

        return window;
    }

	//X11EGLSupport::getGLDisplay sets up the native variable
	//then calls EGLSupport::getGLDisplay
    EGLDisplay X11EGLSupport::getGLDisplay()
    {
        if (!mGLDisplay)
        {
            if(!mNativeDisplay)
                mNativeDisplay = getNativeDisplay();
            return EGLSupport::getGLDisplay();
        }
        return mGLDisplay;
    }

}

<|endoftext|>


<commit_before><commit_msg>oops, fixing invalid handling of "silent" option<commit_after><|endoftext|>


<commit_before>
#include "Internal.hpp"
#include <LuminoEngine/Graphics/RenderState.hpp>
#include <LuminoEngine/UI/UIRenderingContext.hpp>
#include <LuminoEngine/UI/UIEvents.hpp>
#include <LuminoEngine/UI/UIContext.hpp>
#include <LuminoEngine/UI/UIStyle.hpp>
#include <LuminoEngine/UI/UIElement.hpp>
#include <LuminoEngine/UI/UIContainerElement.hpp>
#include "../Rendering/RenderStage.hpp"
#include "UIManager.hpp"

namespace ln {

//==============================================================================
// UIElement

UIElement::UIElement()
    : m_manager(nullptr)
    , m_context(nullptr)
    , m_visualParent(nullptr)
    , m_localStyle(newObject<UIStyle>()) // TODO: ふつうは static なオブジェクトのほうが多くなるので、必要なやつだけ遅延作成でいいと思う
    , m_actualStyle(nullptr)
    , m_renderPriority(0)
    , m_isHitTestVisible(true)
{
}

void UIElement::initialize()
{
    Object::initialize();
    m_manager = detail::EngineDomain::uiManager();

    UIContainerElement* primaryElement = m_manager->primaryElement();
    if (primaryElement) {
        primaryElement->addElement(this);
    }

    if (m_manager->mainContext()) {
        m_manager->mainContext()->addElement(this);
    }
}

void UIElement::setMargin(const Thickness& margin)
{
    m_localStyle->margin = margin;
}

const Thickness& UIElement::margin() const
{
    return m_localStyle->margin;
}

void UIElement::setPadding(const Thickness& padding)
{
    m_localStyle->padding = padding;
}

const Thickness& UIElement::padding() const
{
    return m_localStyle->padding;
}

void UIElement::setPosition(const Vector3 & pos)
{
    m_localStyle->position = pos;
}

const Vector3 & UIElement::position() const
{
    return m_localStyle->position.getOrDefault(Vector3::Zero);
}

void UIElement::setRotation(const Quaternion & rot)
{
    m_localStyle->rotation = rot;
}

const Quaternion & UIElement::rotation() const
{
    return m_localStyle->rotation.getOrDefault(Quaternion::Identity);
}

void UIElement::setScale(const Vector3 & scale)
{
    m_localStyle->scale = scale;
}

const Vector3 & UIElement::scale() const
{
    return m_localStyle->scale.getOrDefault(Vector3::Ones);
}

void UIElement::setCenterPoint(const Vector3 & value)
{
    m_localStyle->centerPoint = value;
}

const Vector3 & UIElement::centerPoint() const
{
    return m_localStyle->centerPoint.getOrDefault(Vector3::Zero);
}

void UIElement::setVisible(bool value)
{
    m_localStyle->visible = value;
}

bool UIElement::isVisible() const
{
    return m_localStyle->visible.getOrDefault(true);
}

void UIElement::setBlendMode(const Optional<BlendMode>& value)
{
    if (value.hasValue()) {
        m_localStyle->blendMode = value.value();
    }
    else {
        m_localStyle->blendMode.reset();
    }
}

const BlendMode & UIElement::blendMode() const
{
    return m_localStyle->blendMode.getOrDefault(BlendMode::Alpha);
}

void UIElement::setOpacity(float value)
{
    m_localStyle->opacity = value;
}

float UIElement::opacity() const
{
    return m_localStyle->opacity.getOrDefault(detail::BuiltinEffectData::DefaultValue.opacity);
}

void UIElement::setColorScale(const Color & value)
{
    m_localStyle->colorScale = value;
}

const Color & UIElement::colorScale() const
{
    return m_localStyle->colorScale.getOrDefault(detail::BuiltinEffectData::DefaultValue.colorScale);
}

void UIElement::setBlendColor(const Color & value)
{
    m_localStyle->blendColor = value;
}

const Color & UIElement::blendColor() const
{
    return m_localStyle->blendColor.getOrDefault(detail::BuiltinEffectData::DefaultValue.blendColor);
}

void UIElement::setTone(const ToneF & value)
{
    m_localStyle->tone = value;
}

const ToneF & UIElement::tone() const
{
    return m_localStyle->tone.getOrDefault(detail::BuiltinEffectData::DefaultValue.tone);
}

void UIElement::setRenderPriority(int value)
{
    m_renderPriority = value;
}

void UIElement::updateFrame(float elapsedSeconds)
{
    onUpdateFrame(elapsedSeconds);

    // child elements
    int count = getVisualChildrenCount();
    for (int i = 0; i < count; i++) {
        getVisualChild(i)->updateFrame(elapsedSeconds);
    }
}

void UIElement::raiseEvent(UIEventArgs* e)
{
    raiseEventInternal(e);
}

UIElement* UIElement::lookupMouseHoverElement(const Point& globalPt)
{
    // 後ろからループする。後のモノが上に描画されるので、この方が自然。
    // TODO: Zオーダーは別のリストにしたほうがいい気がする・・・
    int count = getVisualChildrenCount();
    for (int i = count - 1; i >= 0; i--)
    {
        UIElement* e = static_cast<UIElement*>(getVisualChild(i))->lookupMouseHoverElement(globalPt);
        if (e != nullptr) return e;
    }

    if (m_isHitTestVisible)
    {
        Point localPoint = globalPt;
        if (m_visualParent != nullptr)
        {
            localPoint.x -= m_visualParent->m_finalGlobalRect.x;
            localPoint.y -= m_visualParent->m_finalGlobalRect.y;
        }

        if (onHitTest(localPoint)) {
            return this;
        }
    }

    return nullptr;
}

void UIElement::onUpdateFrame(float elapsedSeconds)
{
}

Size UIElement::measureOverride(const Size& constraint)
{
    // TODO: tmp
    return constraint;
}

Size UIElement::arrangeOverride(const Size& finalSize)
{
    // TODO: tmp
    return finalSize;
}

int UIElement::getVisualChildrenCount() const
{
	return 0;
}

UIElement* UIElement::getVisualChild(int index) const
{
	return nullptr;
}

void UIElement::onRender(UIRenderingContext* context)
{
}

void UIElement::updateLayout(const Size& size)
{
    // TODO: tmp
    arrangeOverride(size);

    // TODO: Layoutelement に実装を持っていく

    // child elements
    int count = getVisualChildrenCount();
    for (int i = 0; i < count; i++) {
        getVisualChild(i)->updateLayout(size);
    }
}

void UIElement::render(UIRenderingContext* context)
{
    if (isVisible())
    {

        context->pushState();

        context->setBaseTransfrom(Matrix::makeAffineTransformation(
            scale(), Vector3::Zero, rotation(), position() - centerPoint()));
        detail::BuiltinEffectData data;
        data.opacity = opacity();
        data.colorScale = colorScale();
        data.blendColor = blendColor();
        data.tone = tone();
        context->setBaseBuiltinEffectData(data);
        context->setBlendMode(blendMode());
        context->setRenderPriority(m_renderPriority);
        // TODO: setMaterial
        onRender(context);

        context->popState();	// TODO: scoped

        //onRender(context);

        // child elements
        int count = getVisualChildrenCount();
        for (int i = 0; i < count; i++) {
            getVisualChild(i)->render(context);
        }
    }
}

void UIElement::onRoutedEvent(UIEventArgs* e)
{
}

bool UIElement::onHitTest(const Point& localPoint)
{
    // TODO:
    return true;
    //return m_finalLocalActualRect.makeDeflate(m_renderFrameThickness).contains(localPoint);
}

void UIElement::raiseEventInternal(UIEventArgs* e)
{
    if (LN_REQUIRE(e)) return;

    // まずは this に通知
    onRoutedEvent(e);
    if (e->handled) return;

    // TODO: bubble
    //if (m_visualParent != nullptr)
    //{
    //    m_visualParent->raiseEventInternal(e);
    //}
}

} // namespace ln

<commit_msg>uielement transform<commit_after>
#include "Internal.hpp"
#include <LuminoEngine/Graphics/RenderState.hpp>
#include <LuminoEngine/UI/UIRenderingContext.hpp>
#include <LuminoEngine/UI/UIEvents.hpp>
#include <LuminoEngine/UI/UIContext.hpp>
#include <LuminoEngine/UI/UIStyle.hpp>
#include <LuminoEngine/UI/UIElement.hpp>
#include <LuminoEngine/UI/UIContainerElement.hpp>
#include "../Rendering/RenderStage.hpp"
#include "UIManager.hpp"

namespace ln {

//==============================================================================
// UIElement

UIElement::UIElement()
    : m_manager(nullptr)
    , m_context(nullptr)
    , m_visualParent(nullptr)
    , m_localStyle(newObject<UIStyle>()) // TODO: ふつうは static なオブジェクトのほうが多くなるので、必要なやつだけ遅延作成でいいと思う
    , m_actualStyle(nullptr)
    , m_renderPriority(0)
    , m_isHitTestVisible(true)
{
}

void UIElement::initialize()
{
    Object::initialize();
    m_manager = detail::EngineDomain::uiManager();

    UIContainerElement* primaryElement = m_manager->primaryElement();
    if (primaryElement) {
        primaryElement->addElement(this);
    }

    if (m_manager->mainContext()) {
        m_manager->mainContext()->addElement(this);
    }
}

void UIElement::setMargin(const Thickness& margin)
{
    m_localStyle->margin = margin;
}

const Thickness& UIElement::margin() const
{
    return m_localStyle->margin;
}

void UIElement::setPadding(const Thickness& padding)
{
    m_localStyle->padding = padding;
}

const Thickness& UIElement::padding() const
{
    return m_localStyle->padding;
}

void UIElement::setPosition(const Vector3 & pos)
{
    m_localStyle->position = pos;
}

const Vector3 & UIElement::position() const
{
    return m_localStyle->position.getOrDefault(Vector3::Zero);
}

void UIElement::setRotation(const Quaternion & rot)
{
    m_localStyle->rotation = rot;
}

const Quaternion & UIElement::rotation() const
{
    return m_localStyle->rotation.getOrDefault(Quaternion::Identity);
}

void UIElement::setScale(const Vector3 & scale)
{
    m_localStyle->scale = scale;
}

const Vector3 & UIElement::scale() const
{
    return m_localStyle->scale.getOrDefault(Vector3::Ones);
}

void UIElement::setCenterPoint(const Vector3 & value)
{
    m_localStyle->centerPoint = value;
}

const Vector3 & UIElement::centerPoint() const
{
    return m_localStyle->centerPoint.getOrDefault(Vector3::Zero);
}

void UIElement::setVisible(bool value)
{
    m_localStyle->visible = value;
}

bool UIElement::isVisible() const
{
    return m_localStyle->visible.getOrDefault(true);
}

void UIElement::setBlendMode(const Optional<BlendMode>& value)
{
    if (value.hasValue()) {
        m_localStyle->blendMode = value.value();
    }
    else {
        m_localStyle->blendMode.reset();
    }
}

const BlendMode & UIElement::blendMode() const
{
    return m_localStyle->blendMode.getOrDefault(BlendMode::Alpha);
}

void UIElement::setOpacity(float value)
{
    m_localStyle->opacity = value;
}

float UIElement::opacity() const
{
    return m_localStyle->opacity.getOrDefault(detail::BuiltinEffectData::DefaultValue.opacity);
}

void UIElement::setColorScale(const Color & value)
{
    m_localStyle->colorScale = value;
}

const Color & UIElement::colorScale() const
{
    return m_localStyle->colorScale.getOrDefault(detail::BuiltinEffectData::DefaultValue.colorScale);
}

void UIElement::setBlendColor(const Color & value)
{
    m_localStyle->blendColor = value;
}

const Color & UIElement::blendColor() const
{
    return m_localStyle->blendColor.getOrDefault(detail::BuiltinEffectData::DefaultValue.blendColor);
}

void UIElement::setTone(const ToneF & value)
{
    m_localStyle->tone = value;
}

const ToneF & UIElement::tone() const
{
    return m_localStyle->tone.getOrDefault(detail::BuiltinEffectData::DefaultValue.tone);
}

void UIElement::setRenderPriority(int value)
{
    m_renderPriority = value;
}

void UIElement::updateFrame(float elapsedSeconds)
{
    onUpdateFrame(elapsedSeconds);

    // child elements
    int count = getVisualChildrenCount();
    for (int i = 0; i < count; i++) {
        getVisualChild(i)->updateFrame(elapsedSeconds);
    }
}

void UIElement::raiseEvent(UIEventArgs* e)
{
    raiseEventInternal(e);
}

UIElement* UIElement::lookupMouseHoverElement(const Point& globalPt)
{
    // 後ろからループする。後のモノが上に描画されるので、この方が自然。
    // TODO: Zオーダーは別のリストにしたほうがいい気がする・・・
    int count = getVisualChildrenCount();
    for (int i = count - 1; i >= 0; i--)
    {
        UIElement* e = static_cast<UIElement*>(getVisualChild(i))->lookupMouseHoverElement(globalPt);
        if (e != nullptr) return e;
    }

    if (m_isHitTestVisible)
    {
        Point localPoint = globalPt;
        if (m_visualParent != nullptr)
        {
            localPoint.x -= m_visualParent->m_finalGlobalRect.x;
            localPoint.y -= m_visualParent->m_finalGlobalRect.y;
        }

        if (onHitTest(localPoint)) {
            return this;
        }
    }

    return nullptr;
}

void UIElement::onUpdateFrame(float elapsedSeconds)
{
}

Size UIElement::measureOverride(const Size& constraint)
{
    // TODO: tmp
    return constraint;
}

Size UIElement::arrangeOverride(const Size& finalSize)
{
    // TODO: tmp
    return finalSize;
}

int UIElement::getVisualChildrenCount() const
{
	return 0;
}

UIElement* UIElement::getVisualChild(int index) const
{
	return nullptr;
}

void UIElement::onRender(UIRenderingContext* context)
{
}

void UIElement::updateLayout(const Size& size)
{
    // TODO: tmp
    arrangeOverride(size);

    // TODO: Layoutelement に実装を持っていく

    // child elements
    int count = getVisualChildrenCount();
    for (int i = 0; i < count; i++) {
        getVisualChild(i)->updateLayout(size);
    }
}

void UIElement::render(UIRenderingContext* context)
{
    if (isVisible())
    {

        context->pushState();

        {
            Matrix m = Matrix::makeTranslation(-centerPoint());
            m.scale(scale());
            m.rotateQuaternion(rotation());
            m.translate(position());
            context->setBaseTransfrom(m);
        }
        detail::BuiltinEffectData data;
        data.opacity = opacity();
        data.colorScale = colorScale();
        data.blendColor = blendColor();
        data.tone = tone();
        context->setBaseBuiltinEffectData(data);
        context->setBlendMode(blendMode());
        context->setRenderPriority(m_renderPriority);
        // TODO: setMaterial
        onRender(context);

        context->popState();	// TODO: scoped

        //onRender(context);

        // child elements
        int count = getVisualChildrenCount();
        for (int i = 0; i < count; i++) {
            getVisualChild(i)->render(context);
        }
    }
}

void UIElement::onRoutedEvent(UIEventArgs* e)
{
}

bool UIElement::onHitTest(const Point& localPoint)
{
    // TODO:
    return true;
    //return m_finalLocalActualRect.makeDeflate(m_renderFrameThickness).contains(localPoint);
}

void UIElement::raiseEventInternal(UIEventArgs* e)
{
    if (LN_REQUIRE(e)) return;

    // まずは this に通知
    onRoutedEvent(e);
    if (e->handled) return;

    // TODO: bubble
    //if (m_visualParent != nullptr)
    //{
    //    m_visualParent->raiseEventInternal(e);
    //}
}

} // namespace ln

<|endoftext|>


<commit_before>/**************************************************************************\
**
**       TODDLER: Slimmed-down version of CHILD without Vegetation,
**                Stream Meandering, or mesh densification.
**
**                            C H I L D
**
**       CHANNEL-HILLSLOPE INTEGRATED LANDSCAPE DEVELOPMENT MODEL
**
**                      VERSION 2.1.2, JUNE 2000
**
**  Designed and created by Gregory E. Tucker, Stephen T. Lancaster,
**      Nicole M. Gasparini, and Rafael L. Bras, Department of Civil
**      and Environmental Engineering, Massachusetts Institute of
**      Technology, Cambridge, MA, USA.
**
**  MAIN.CPP -- This file contains the main() routine that handles
**              top-level initialization and implements the main
**              time-loop.
**
**  NOTE: This source code is copyrighted material. It is distributed
**        solely for noncommercial research and educational purposes
**        only. Use in whole or in part for commercial purposes without
**        a written license from the copyright holder(s) is expressly
**        prohibited. Copies of this source code or any of its components
**        may not be transferred to any other individuals or organizations
**        without written consent. Copyright (C) Massachusetts Institute
**        of Technology, 1997-2000. All rights reserved.
**
**  For information regarding this program, please contact Greg Tucker at:
**
**       School of Geography and the Environment
**       University of Oxford
**       Mansfield Road
**       Oxford OX1 3TB United Kingdom
**
**  $Id: toddlermain.cpp,v 1.5 2002-04-11 09:55:38 arnaud Exp $
\**************************************************************************/

#include "Inclusions.h"
#include "tFloodplain/tFloodplain.h"
#include "tEolian/tEolian.h"

Predicates predicate;

int main( int argc, char **argv )
{
   int silent_mode,       // Option for silent mode (no time output to stdout)
       optDetachLim,      // Option for detachment-limited erosion only
       optFloodplainDep,  // Option for floodplain (overbank) deposition
       optLoessDep,       // Option for eolian deposition
       optVegetation,     // Option for dynamic vegetation cover
       optDiffuseDepo;    // Option for deposition / no deposition by diff'n
   tVegetation *vegetation;  // -> vegetation object
   tFloodplain *floodplain;  // -> floodplain object
   tEolian *loess;           // -> eolian deposition object

   /****************** INITIALIZATION *************************************\
   **  ALGORITHM
   **    Get command-line arguments (name of input file + any other opts)
   **    Set silent_mode flag
   **    Open main input file
   **    Create and initialize objects for...
   **      Mesh
   **      Output files
   **      Storm
   **      Stream network
   **      Erosion
   **      Uplift (or baselevel change)
   **      Run timer
   **    Write output for initial state
   **    Get options for erosion type, meandering, etc.
   \**********************************************************************/

   // Check command-line arguments
   if( argc<2 )
   {
      cerr << "Usage: " << argv[0] << " <input file>" << endl;
      ReportFatalError( "You need to give the name of an input file." );
   }

   // Check whether we're in silent mode
   silent_mode = ( argc>2 && argv[2][1]=='s' );

   // Say hello
   cout << "\nThis is TODDLER, version " << VERSION << endl << endl;

   // Open main input file
   tInputFile inputFile( argv[1] );

   // Create and initialize objects:
   cout << "Creating mesh...\n";
   tMesh<tLNode> mesh( inputFile );
   cout << "Creating output files...\n";
   tLOutput<tLNode> output( &mesh, inputFile );
   tStorm storm( inputFile );
   cout << "Creating stream network...\n";
   tStreamNet strmNet( mesh, storm, inputFile );
   tErosion erosion( &mesh, inputFile );
   tUplift uplift( inputFile );
   cout << "Writing data for time zero...\n";
   tRunTimer time( inputFile, !silent_mode );
   output.WriteOutput( 0 );
   cout << "Initialization done.\n";

   // Get various options
   optDetachLim = inputFile.ReadItem( optDetachLim, "OPTDETACHLIM" );
   optDiffuseDepo = inputFile.ReadItem( optDiffuseDepo, "OPTDIFFDEP" );
   optVegetation = inputFile.ReadItem( optVegetation, "OPTVEG" );
   optFloodplainDep = inputFile.ReadItem( optFloodplainDep, "OPTFLOODPLAIN" );
   optLoessDep = inputFile.ReadItem( optLoessDep, "OPTLOESSDEP" );

   // If applicable, create Vegetation object
   if( optVegetation )
       vegetation = new tVegetation( &mesh, inputFile );

   // If applicable, create floodplain object
   if( optFloodplainDep )
       floodplain = new tFloodplain( inputFile, &mesh );

   // If applicable, create eolian deposition object
   if( optLoessDep )
       loess = new tEolian( inputFile );

   // Option for time series output (IN PROGRESS)
   /*   switch( optTSOutput ){
   case 1:   // Volume output each N years.
     if( time.CheckTSOutputTime() )
       output.WriteVolOutput();
     break;
   case 2:   // Volume and vegetation cover output each N years.
     cout << "here" << endl;
     if( time.CheckTSOutputTime() ){
       cout << "there" << endl;
       output.WriteVolVegOutput();}
     break;
   case 3:   // All data at each storm.
     output.WriteTSOutput();
     break;
   case 0:   // No additional timeseries output.
     break;
   default:  // Invalid option.
     ReportFatalError( "The input file contains an invalid value for
OptTSOutput." );
   }   */

   // Temporary -- for canyon range stuff
   /*cout << "Densifying around fold strike ...\n";
   int optFoldDens = inputFile.ReadItem( optFoldDens, "OPTFOLDDENS" );
   if( optFoldDens )
     {
       double foldDensYmin = inputFile.ReadItem( foldDensYmin, "FOLDDENSYMIN" );
       double foldDensYmax = inputFile.ReadItem( foldDensYmax, "FOLDDENSYMAX" );
       double fault = inputFile.ReadItem( fault, "FAULTPOS" );
       for( int i=1; i<=optFoldDens; i++ )
	 {
	   tPtrList<tLNode> foldPoints;
	   tMeshListIter<tLNode> ni( mesh.getNodeList() );
	   tLNode *cn;
	   for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )
	     {
	     if( cn->getY()>=foldDensYmin && cn->getY()<=foldDensYmax &&
		 cn->getX()>=7500 && cn->getX()<=92500 )
	       foldPoints.insertAtBack( cn );
	     if( cn->getY()<fault )
	       cn->setAlluvThickness( 100000 );
	     }
	   tPtrListIter<tLNode> fpi( foldPoints );
	   for( cn=fpi.FirstP(); !(fpi.AtEnd()); cn=fpi.NextP() )
	     mesh.AddNodesAround( cn, 0.0 );
	   foldPoints.Flush();
	 }
	 }*/

   /**************** MAIN LOOP ******************************************\
   **  ALGORITHM
   **    Generate storm
   **    Do storm...
   **      Update network (flow directions, drainage area, runoff)
   **      Water erosion/deposition (vertical)
   **      Meandering (if applicable)
   **      Floodplain deposition (if applicable)
   **    Do interstorm...
   **      Hillslope transport
   **      Vegetation (if applicable)
   **      Exposure history
   **      Mesh densification (if applicable)
   **      Eolian (loess) deposition (if applicable)
   **      Uplift (or baselevel change)
   **********************************************************************/
   while( !time.IsFinished() )
   {
      time.ReportTimeStatus();

      // Do storm...
      storm.GenerateStorm( time.getCurrentTime(),
                           strmNet.getInfilt(), strmNet.getSoilStore() );
      cout << storm.getRainrate() << " " << storm.getStormDuration() << " "
           << storm.interstormDur() << endl;

      strmNet.UpdateNet( time.getCurrentTime(), storm );

      if( optDetachLim )
          erosion.ErodeDetachLim( storm.getStormDuration(), &strmNet );
      else
          erosion.DetachErode( storm.getStormDuration(), &strmNet,
                               time.getCurrentTime() );

      if( optVegetation )
	  vegetation->UpdateVegetation( &mesh, storm.getStormDuration(),
					storm.interstormDur() );

      if( optFloodplainDep )
          floodplain->DepositOverbank( storm.getRainrate(),
                                       storm.getStormDuration(),
                                       time.getCurrentTime() );

      // Do interstorm...
      erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(),
      optDiffuseDepo );

      erosion.UpdateExposureTime( storm.getStormDuration() +
                                      storm.interstormDur() );

      if( optLoessDep )
          loess->DepositLoess( &mesh,
                               storm.getStormDuration()+storm.interstormDur(),
                               time.getCurrentTime() );

      if( time.getCurrentTime() < uplift.getDuration() )
          uplift.DoUplift( &mesh,
                           storm.getStormDuration() + storm.interstormDur() );

      time.Advance( storm.getStormDuration() + storm.interstormDur() );

      if( time.CheckOutputTime() )
          output.WriteOutput( time.getCurrentTime() );

      if( output.OptTSOutput() ) output.WriteTSOutput();

      /* IN PROGRESS
      switch( optTSOutput ){
      case 1:   // Volume output each N years.
        if( time.CheckTSOutputTime() )
  output.WriteVolOutput();
break;
      case 2:   // Volume and vegetation cover output each N years.
if( time.CheckTSOutputTime() )
  output.WriteVolVegOutput();
break;
      case 3:   // All data at each storm.
output.WriteTSOutput();
break;
      case 0:   // No additional timeseries output.
break;
      default:  // Invalid option.
ReportFatalError( "The input file contains an invalid value for OptTSOutput."
*/

     /*tMeshListIter<tLNode> ni( mesh.getNodeList() );
      tLNode *cn;
      for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )
	{
	  if( cn->getY()<25 && cn->getX()>250 && cn->getDrArea()>1000 )
	    cn->TellAll();
	}*/

   } // end of main loop

   return 0;
}

<commit_msg>added explicit initialisation to avoid spurious warnings<commit_after>/**************************************************************************\
**
**       TODDLER: Slimmed-down version of CHILD without Vegetation,
**                Stream Meandering, or mesh densification.
**
**                            C H I L D
**
**       CHANNEL-HILLSLOPE INTEGRATED LANDSCAPE DEVELOPMENT MODEL
**
**                      VERSION 2.1.2, JUNE 2000
**
**  Designed and created by Gregory E. Tucker, Stephen T. Lancaster,
**      Nicole M. Gasparini, and Rafael L. Bras, Department of Civil
**      and Environmental Engineering, Massachusetts Institute of
**      Technology, Cambridge, MA, USA.
**
**  MAIN.CPP -- This file contains the main() routine that handles
**              top-level initialization and implements the main
**              time-loop.
**
**  NOTE: This source code is copyrighted material. It is distributed
**        solely for noncommercial research and educational purposes
**        only. Use in whole or in part for commercial purposes without
**        a written license from the copyright holder(s) is expressly
**        prohibited. Copies of this source code or any of its components
**        may not be transferred to any other individuals or organizations
**        without written consent. Copyright (C) Massachusetts Institute
**        of Technology, 1997-2000. All rights reserved.
**
**  For information regarding this program, please contact Greg Tucker at:
**
**       School of Geography and the Environment
**       University of Oxford
**       Mansfield Road
**       Oxford OX1 3TB United Kingdom
**
**  $Id: toddlermain.cpp,v 1.6 2002-04-11 10:55:00 arnaud Exp $
\**************************************************************************/

#include "Inclusions.h"
#include "tFloodplain/tFloodplain.h"
#include "tEolian/tEolian.h"

Predicates predicate;

int main( int argc, char **argv )
{
   int silent_mode,       // Option for silent mode (no time output to stdout)
       optDetachLim,      // Option for detachment-limited erosion only
       optFloodplainDep,  // Option for floodplain (overbank) deposition
       optLoessDep,       // Option for eolian deposition
       optVegetation,     // Option for dynamic vegetation cover
       optDiffuseDepo;    // Option for deposition / no deposition by diff'n
   tVegetation *vegetation(0);  // -> vegetation object
   tFloodplain *floodplain(0);  // -> floodplain object
   tEolian *loess(0);           // -> eolian deposition object

   /****************** INITIALIZATION *************************************\
   **  ALGORITHM
   **    Get command-line arguments (name of input file + any other opts)
   **    Set silent_mode flag
   **    Open main input file
   **    Create and initialize objects for...
   **      Mesh
   **      Output files
   **      Storm
   **      Stream network
   **      Erosion
   **      Uplift (or baselevel change)
   **      Run timer
   **    Write output for initial state
   **    Get options for erosion type, meandering, etc.
   \**********************************************************************/

   // Check command-line arguments
   if( argc<2 )
   {
      cerr << "Usage: " << argv[0] << " <input file>" << endl;
      ReportFatalError( "You need to give the name of an input file." );
   }

   // Check whether we're in silent mode
   silent_mode = ( argc>2 && argv[2][1]=='s' );

   // Say hello
   cout << "\nThis is TODDLER, version " << VERSION << endl << endl;

   // Open main input file
   tInputFile inputFile( argv[1] );

   // Create and initialize objects:
   cout << "Creating mesh...\n";
   tMesh<tLNode> mesh( inputFile );
   cout << "Creating output files...\n";
   tLOutput<tLNode> output( &mesh, inputFile );
   tStorm storm( inputFile );
   cout << "Creating stream network...\n";
   tStreamNet strmNet( mesh, storm, inputFile );
   tErosion erosion( &mesh, inputFile );
   tUplift uplift( inputFile );
   cout << "Writing data for time zero...\n";
   tRunTimer time( inputFile, !silent_mode );
   output.WriteOutput( 0 );
   cout << "Initialization done.\n";

   // Get various options
   optDetachLim = inputFile.ReadItem( optDetachLim, "OPTDETACHLIM" );
   optDiffuseDepo = inputFile.ReadItem( optDiffuseDepo, "OPTDIFFDEP" );
   optVegetation = inputFile.ReadItem( optVegetation, "OPTVEG" );
   optFloodplainDep = inputFile.ReadItem( optFloodplainDep, "OPTFLOODPLAIN" );
   optLoessDep = inputFile.ReadItem( optLoessDep, "OPTLOESSDEP" );

   // If applicable, create Vegetation object
   if( optVegetation )
       vegetation = new tVegetation( &mesh, inputFile );

   // If applicable, create floodplain object
   if( optFloodplainDep )
       floodplain = new tFloodplain( inputFile, &mesh );

   // If applicable, create eolian deposition object
   if( optLoessDep )
       loess = new tEolian( inputFile );

   // Option for time series output (IN PROGRESS)
   /*   switch( optTSOutput ){
   case 1:   // Volume output each N years.
     if( time.CheckTSOutputTime() )
       output.WriteVolOutput();
     break;
   case 2:   // Volume and vegetation cover output each N years.
     cout << "here" << endl;
     if( time.CheckTSOutputTime() ){
       cout << "there" << endl;
       output.WriteVolVegOutput();}
     break;
   case 3:   // All data at each storm.
     output.WriteTSOutput();
     break;
   case 0:   // No additional timeseries output.
     break;
   default:  // Invalid option.
     ReportFatalError( "The input file contains an invalid value for
OptTSOutput." );
   }   */

   // Temporary -- for canyon range stuff
   /*cout << "Densifying around fold strike ...\n";
   int optFoldDens = inputFile.ReadItem( optFoldDens, "OPTFOLDDENS" );
   if( optFoldDens )
     {
       double foldDensYmin = inputFile.ReadItem( foldDensYmin, "FOLDDENSYMIN" );
       double foldDensYmax = inputFile.ReadItem( foldDensYmax, "FOLDDENSYMAX" );
       double fault = inputFile.ReadItem( fault, "FAULTPOS" );
       for( int i=1; i<=optFoldDens; i++ )
	 {
	   tPtrList<tLNode> foldPoints;
	   tMeshListIter<tLNode> ni( mesh.getNodeList() );
	   tLNode *cn;
	   for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )
	     {
	     if( cn->getY()>=foldDensYmin && cn->getY()<=foldDensYmax &&
		 cn->getX()>=7500 && cn->getX()<=92500 )
	       foldPoints.insertAtBack( cn );
	     if( cn->getY()<fault )
	       cn->setAlluvThickness( 100000 );
	     }
	   tPtrListIter<tLNode> fpi( foldPoints );
	   for( cn=fpi.FirstP(); !(fpi.AtEnd()); cn=fpi.NextP() )
	     mesh.AddNodesAround( cn, 0.0 );
	   foldPoints.Flush();
	 }
	 }*/

   /**************** MAIN LOOP ******************************************\
   **  ALGORITHM
   **    Generate storm
   **    Do storm...
   **      Update network (flow directions, drainage area, runoff)
   **      Water erosion/deposition (vertical)
   **      Meandering (if applicable)
   **      Floodplain deposition (if applicable)
   **    Do interstorm...
   **      Hillslope transport
   **      Vegetation (if applicable)
   **      Exposure history
   **      Mesh densification (if applicable)
   **      Eolian (loess) deposition (if applicable)
   **      Uplift (or baselevel change)
   **********************************************************************/
   while( !time.IsFinished() )
   {
      time.ReportTimeStatus();

      // Do storm...
      storm.GenerateStorm( time.getCurrentTime(),
                           strmNet.getInfilt(), strmNet.getSoilStore() );
      cout << storm.getRainrate() << " " << storm.getStormDuration() << " "
           << storm.interstormDur() << endl;

      strmNet.UpdateNet( time.getCurrentTime(), storm );

      if( optDetachLim )
          erosion.ErodeDetachLim( storm.getStormDuration(), &strmNet );
      else
          erosion.DetachErode( storm.getStormDuration(), &strmNet,
                               time.getCurrentTime() );

      if( optVegetation )
	  vegetation->UpdateVegetation( &mesh, storm.getStormDuration(),
					storm.interstormDur() );

      if( optFloodplainDep )
          floodplain->DepositOverbank( storm.getRainrate(),
                                       storm.getStormDuration(),
                                       time.getCurrentTime() );

      // Do interstorm...
      erosion.Diffuse( storm.getStormDuration() + storm.interstormDur(),
      optDiffuseDepo );

      erosion.UpdateExposureTime( storm.getStormDuration() +
                                      storm.interstormDur() );

      if( optLoessDep )
          loess->DepositLoess( &mesh,
                               storm.getStormDuration()+storm.interstormDur(),
                               time.getCurrentTime() );

      if( time.getCurrentTime() < uplift.getDuration() )
          uplift.DoUplift( &mesh,
                           storm.getStormDuration() + storm.interstormDur() );

      time.Advance( storm.getStormDuration() + storm.interstormDur() );

      if( time.CheckOutputTime() )
          output.WriteOutput( time.getCurrentTime() );

      if( output.OptTSOutput() ) output.WriteTSOutput();

      /* IN PROGRESS
      switch( optTSOutput ){
      case 1:   // Volume output each N years.
        if( time.CheckTSOutputTime() )
  output.WriteVolOutput();
break;
      case 2:   // Volume and vegetation cover output each N years.
if( time.CheckTSOutputTime() )
  output.WriteVolVegOutput();
break;
      case 3:   // All data at each storm.
output.WriteTSOutput();
break;
      case 0:   // No additional timeseries output.
break;
      default:  // Invalid option.
ReportFatalError( "The input file contains an invalid value for OptTSOutput."
*/

     /*tMeshListIter<tLNode> ni( mesh.getNodeList() );
      tLNode *cn;
      for( cn=ni.FirstP(); ni.IsActive(); cn=ni.NextP() )
	{
	  if( cn->getY()<25 && cn->getX()>250 && cn->getDrArea()>1000 )
	    cn->TellAll();
	}*/

   } // end of main loop

   return 0;
}

<|endoftext|>


<commit_before>//===-- XCoreTargetTransformInfo.cpp - XCore specific TTI pass ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements a TargetTransformInfo analysis pass specific to the
/// XCore target machine. It uses the target's detailed information to provide
/// more precise answers to certain TTI queries, while letting the target
/// independent and default TTI implementations handle the rest.
///
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "xcoretti"
#include "XCore.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/CostTable.h"
using namespace llvm;

// Declare the pass initialization routine locally as target-specific passes
// don't havve a target-wide initialization entry point, and so we rely on the
// pass constructor initialization.
namespace llvm {
void initializeXCoreTTIPass(PassRegistry &);
}

namespace {

class XCoreTTI : public ImmutablePass, public TargetTransformInfo {
  const XCoreTargetMachine *TM;

public:
  XCoreTTI() : ImmutablePass(ID), TM(0) {
    llvm_unreachable("This pass cannot be directly constructed");
  }

  XCoreTTI(const XCoreTargetMachine *TM)
      : ImmutablePass(ID), TM(TM) {
    initializeXCoreTTIPass(*PassRegistry::getPassRegistry());
  }

  virtual void initializePass() {
    pushTTIStack(this);
  }

  virtual void finalizePass() {
    popTTIStack();
  }

  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    TargetTransformInfo::getAnalysisUsage(AU);
  }

  static char ID;

  virtual void *getAdjustedAnalysisPointer(const void *ID) {
    if (ID == &TargetTransformInfo::ID)
      return (TargetTransformInfo*)this;
    return this;
  }

  unsigned getNumberOfRegisters(bool Vector) const {
    if (Vector) {
       return 0;
    }
    return 12;
  }
};

} // end anonymous namespace

INITIALIZE_AG_PASS(XCoreTTI, TargetTransformInfo, "xcoretti",
                   "XCore Target Transform Info", true, true, false)
char XCoreTTI::ID = 0;

ImmutablePass *
llvm::createXCoreTargetTransformInfoPass(const XCoreTargetMachine *TM) {
  return new XCoreTTI(TM);
}
<commit_msg>More XCore TTI cleanup -- remove an unused private field flagged by -Wunused-private-field with Clang.<commit_after>//===-- XCoreTargetTransformInfo.cpp - XCore specific TTI pass ----------------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
/// \file
/// This file implements a TargetTransformInfo analysis pass specific to the
/// XCore target machine. It uses the target's detailed information to provide
/// more precise answers to certain TTI queries, while letting the target
/// independent and default TTI implementations handle the rest.
///
//===----------------------------------------------------------------------===//

#define DEBUG_TYPE "xcoretti"
#include "XCore.h"
#include "llvm/Analysis/TargetTransformInfo.h"
#include "llvm/Support/Debug.h"
#include "llvm/Target/TargetLowering.h"
#include "llvm/Target/CostTable.h"
using namespace llvm;

// Declare the pass initialization routine locally as target-specific passes
// don't havve a target-wide initialization entry point, and so we rely on the
// pass constructor initialization.
namespace llvm {
void initializeXCoreTTIPass(PassRegistry &);
}

namespace {

class XCoreTTI : public ImmutablePass, public TargetTransformInfo {
public:
  XCoreTTI() : ImmutablePass(ID) {
    llvm_unreachable("This pass cannot be directly constructed");
  }

  XCoreTTI(const XCoreTargetMachine *TM)
      : ImmutablePass(ID) {
    initializeXCoreTTIPass(*PassRegistry::getPassRegistry());
  }

  virtual void initializePass() {
    pushTTIStack(this);
  }

  virtual void finalizePass() {
    popTTIStack();
  }

  virtual void getAnalysisUsage(AnalysisUsage &AU) const {
    TargetTransformInfo::getAnalysisUsage(AU);
  }

  static char ID;

  virtual void *getAdjustedAnalysisPointer(const void *ID) {
    if (ID == &TargetTransformInfo::ID)
      return (TargetTransformInfo*)this;
    return this;
  }

  unsigned getNumberOfRegisters(bool Vector) const {
    if (Vector) {
       return 0;
    }
    return 12;
  }
};

} // end anonymous namespace

INITIALIZE_AG_PASS(XCoreTTI, TargetTransformInfo, "xcoretti",
                   "XCore Target Transform Info", true, true, false)
char XCoreTTI::ID = 0;

ImmutablePass *
llvm::createXCoreTargetTransformInfoPass(const XCoreTargetMachine *TM) {
  return new XCoreTTI(TM);
}
<|endoftext|>