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

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_i18npool.hxx"

#include <assert.h>
#include <textconversion.hxx>
#include <com/sun/star/i18n/TextConversionType.hpp>
#include <com/sun/star/i18n/TextConversionOption.hpp>
#include <com/sun/star/linguistic2/ConversionDirection.hpp>
#include <com/sun/star/linguistic2/ConversionDictionaryType.hpp>
#include <i18nutil/x_rtl_ustring.h>

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

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

TextConversion_zh::TextConversion_zh( const Reference < XMultiServiceFactory >& xMSF )
{
    Reference < XInterface > xI;
    xI = xMSF->createInstance(
        OUString::createFromAscii( "com.sun.star.linguistic2.ConversionDictionaryList" ));
    if ( xI.is() )
        xI->queryInterface( getCppuType((const Reference< XConversionDictionaryList>*)0) ) >>= xCDL;

    implementationName = "com.sun.star.i18n.TextConversion_zh";
}

sal_Unicode SAL_CALL getOneCharConversion(sal_Unicode ch, const sal_Unicode* Data, const sal_uInt16* Index)
{
    if (Data && Index) {
        sal_Unicode address = Index[ch>>8];
        if (address != 0xFFFF)
            address = Data[address + (ch & 0xFF)];
        return (address != 0xFFFF) ? address : ch;
    } else {
        return ch;
    }
}

OUString SAL_CALL
TextConversion_zh::getCharConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions)
{
    const sal_Unicode *Data;
    const sal_uInt16 *Index;

    if (toSChinese) {
        Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_T2S"))();
        Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_T2S"))();
    } else if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) {
        Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_S2V"))();
        Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_S2V"))();
    } else {
        Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_S2T"))();
        Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_S2T"))();
    }

    rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength ); // defined in x_rtl_ustring.h
    for (sal_Int32 i = 0; i < nLength; i++)
        newStr->buffer[i] =
            getOneCharConversion(aText[nStartPos+i], Data, Index);
    return OUString( newStr->buffer, nLength);
}

OUString SAL_CALL
TextConversion_zh::getWordConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions, Sequence<sal_Int32>& offset)
{
    sal_Int32 dictLen = 0;
    sal_Int32 maxLen = 0;
    const sal_uInt16 *index;
    const sal_uInt16 *entry;
    const sal_Unicode *charData;
    const sal_uInt16 *charIndex;
    sal_Bool one2one=sal_True;

    const sal_Unicode *wordData = ((const sal_Unicode* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordData"))(dictLen);
    if (toSChinese) {
        index = ((const sal_uInt16* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordIndex_T2S"))(maxLen);
        entry = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_WordEntry_T2S"))();
        charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_T2S"))();
        charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_T2S"))();
    } else {
        index = ((const sal_uInt16* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordIndex_S2T"))(maxLen);
        entry = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_WordEntry_S2T"))();
        if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) {
            charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_S2V"))();
            charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_S2V"))();
        } else {
            charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_S2T"))();
            charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_S2T"))();
        }
    }

    if ((!wordData || !index || !entry) && !xCDL.is()) // no word mapping defined, do char2char conversion.
        return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);

    rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength * 2 ); // defined in x_rtl_ustring.h
    sal_Int32 currPos = 0, count = 0;
    while (currPos < nLength) {
        sal_Int32 len = nLength - currPos;
        sal_Bool found = sal_False;
        if (len > maxLen)
            len = maxLen;
        for (; len > 0 && ! found; len--) {
            OUString word = aText.copy(nStartPos + currPos, len);
            sal_Int32 current = 0;
            // user dictionary
            if (xCDL.is()) {
                Sequence < OUString > conversions;
                try {
                    conversions = xCDL->queryConversions(word, 0, len,
                            aLocale, ConversionDictionaryType::SCHINESE_TCHINESE,
                            /*toSChinese ?*/ ConversionDirection_FROM_LEFT /*: ConversionDirection_FROM_RIGHT*/,
                            nConversionOptions);
                }
                catch ( NoSupportException & ) {
                    // clear reference (when there is no user dictionary) in order
                    // to not always have to catch this exception again
                    // in further calls. (save time)
                    xCDL = 0;
                }
                catch (...) {
                    // catch all other exceptions to allow
                    // querying the system dictionary in the next line
                }
                if (conversions.getLength() > 0) {
                    if (offset.getLength() > 0) {
                        if (word.getLength() != conversions[0].getLength())
                            one2one=sal_False;
                        while (current < conversions[0].getLength()) {
                            offset[count] = nStartPos + currPos + (current *
                                    word.getLength() / conversions[0].getLength());
                            newStr->buffer[count++] = conversions[0][current++];
                        }
                        // offset[count-1] = nStartPos + currPos + word.getLength() - 1;
                    } else {
                        while (current < conversions[0].getLength())
                            newStr->buffer[count++] = conversions[0][current++];
                    }
                    currPos += word.getLength();
                    found = sal_True;
                }
            }

            if (!found && index[len+1] - index[len] > 0) {
                sal_Int32 bottom = (sal_Int32) index[len];
                sal_Int32 top = (sal_Int32) index[len+1] - 1;

                while (bottom <= top && !found) {
                    current = (top + bottom) / 2;
                    const sal_Int32 result = word.compareTo(wordData + entry[current]);
                    if (result < 0)
                        top = current - 1;
                    else if (result > 0)
                        bottom = current + 1;
                    else {
                        if (toSChinese)   // Traditionary/Simplified conversion,
                            for (current = entry[current]-1; current > 0 && wordData[current-1]; current--);
                        else  // Simplified/Traditionary conversion, forwards search for next word
                            current = entry[current] + word.getLength() + 1;
                        sal_Int32 start=current;
                        if (offset.getLength() > 0) {
                            if (word.getLength() != OUString(&wordData[current]).getLength())
                                one2one=sal_False;
                            sal_Int32 convertedLength=OUString(&wordData[current]).getLength();
                            while (wordData[current]) {
                                offset[count]=nStartPos + currPos + ((current-start) *
                                    word.getLength() / convertedLength);
                                newStr->buffer[count++] = wordData[current++];
                            }
                            // offset[count-1]=nStartPos + currPos + word.getLength() - 1;
                        } else {
                            while (wordData[current])
                                newStr->buffer[count++] = wordData[current++];
                        }
                        currPos += word.getLength();
                        found = sal_True;
                    }
                }
            }
        }
        if (!found) {
            if (offset.getLength() > 0)
                offset[count]=nStartPos+currPos;
            newStr->buffer[count++] =
                getOneCharConversion(aText[nStartPos+currPos], charData, charIndex);
            currPos++;
        }
    }
    if (offset.getLength() > 0)
        offset.realloc(one2one ? 0 : count);
    return OUString( newStr->buffer, count);
}

TextConversionResult SAL_CALL
TextConversion_zh::getConversions( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
    const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)
    throw(  RuntimeException, IllegalArgumentException, NoSupportException )
{
    TextConversionResult result;

    result.Candidates.realloc(1);
    result.Candidates[0] = getConversion( aText, nStartPos, nLength, rLocale, nConversionType, nConversionOptions);
    result.Boundary.startPos = nStartPos;
    result.Boundary.endPos = nStartPos + nLength;

    return result;
}

OUString SAL_CALL
TextConversion_zh::getConversion( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
    const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)
    throw(  RuntimeException, IllegalArgumentException, NoSupportException )
{
    if (rLocale.Language.equalsAscii("zh") &&
            ( nConversionType == TextConversionType::TO_SCHINESE ||
            nConversionType == TextConversionType::TO_TCHINESE) ) {

        aLocale=rLocale;
        sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE;

        if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER)
            // char to char dictionary
            return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);
        else {
            Sequence <sal_Int32> offset;
            // word to word dictionary
            return  getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset);
        }
    } else
        throw NoSupportException(); // Conversion type is not supported in this service.
}

OUString SAL_CALL
TextConversion_zh::getConversionWithOffset( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
    const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions, Sequence<sal_Int32>& offset)
    throw(  RuntimeException, IllegalArgumentException, NoSupportException )
{
    if (rLocale.Language.equalsAscii("zh") &&
            ( nConversionType == TextConversionType::TO_SCHINESE ||
            nConversionType == TextConversionType::TO_TCHINESE) ) {

        aLocale=rLocale;
        sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE;

        if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER) {
            offset.realloc(0);
            // char to char dictionary
            return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);
        } else {
            if (offset.getLength() < 2*nLength)
                offset.realloc(2*nLength);
            // word to word dictionary
            return  getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset);
        }
    } else
        throw NoSupportException(); // Conversion type is not supported in this service.
}

sal_Bool SAL_CALL
TextConversion_zh::interactiveConversion( const Locale& /*rLocale*/, sal_Int16 /*nTextConversionType*/, sal_Int32 /*nTextConversionOptions*/ )
    throw(  RuntimeException, IllegalArgumentException, NoSupportException )
{
    return sal_False;
}

} } } }
<commit_msg>INTEGRATION: CWS changefileheader (1.10.112); FILE MERGED 2008/03/31 16:01:30 rt 1.10.112.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: textconversion_zh.cxx,v $
 * $Revision: 1.11 $
 *
 * 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_i18npool.hxx"

#include <assert.h>
#include <textconversion.hxx>
#include <com/sun/star/i18n/TextConversionType.hpp>
#include <com/sun/star/i18n/TextConversionOption.hpp>
#include <com/sun/star/linguistic2/ConversionDirection.hpp>
#include <com/sun/star/linguistic2/ConversionDictionaryType.hpp>
#include <i18nutil/x_rtl_ustring.h>

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

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

TextConversion_zh::TextConversion_zh( const Reference < XMultiServiceFactory >& xMSF )
{
    Reference < XInterface > xI;
    xI = xMSF->createInstance(
        OUString::createFromAscii( "com.sun.star.linguistic2.ConversionDictionaryList" ));
    if ( xI.is() )
        xI->queryInterface( getCppuType((const Reference< XConversionDictionaryList>*)0) ) >>= xCDL;

    implementationName = "com.sun.star.i18n.TextConversion_zh";
}

sal_Unicode SAL_CALL getOneCharConversion(sal_Unicode ch, const sal_Unicode* Data, const sal_uInt16* Index)
{
    if (Data && Index) {
        sal_Unicode address = Index[ch>>8];
        if (address != 0xFFFF)
            address = Data[address + (ch & 0xFF)];
        return (address != 0xFFFF) ? address : ch;
    } else {
        return ch;
    }
}

OUString SAL_CALL
TextConversion_zh::getCharConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions)
{
    const sal_Unicode *Data;
    const sal_uInt16 *Index;

    if (toSChinese) {
        Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_T2S"))();
        Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_T2S"))();
    } else if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) {
        Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_S2V"))();
        Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_S2V"))();
    } else {
        Data = ((const sal_Unicode* (*)())getFunctionBySymbol("getSTC_CharData_S2T"))();
        Index = ((const sal_uInt16* (*)())getFunctionBySymbol("getSTC_CharIndex_S2T"))();
    }

    rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength ); // defined in x_rtl_ustring.h
    for (sal_Int32 i = 0; i < nLength; i++)
        newStr->buffer[i] =
            getOneCharConversion(aText[nStartPos+i], Data, Index);
    return OUString( newStr->buffer, nLength);
}

OUString SAL_CALL
TextConversion_zh::getWordConversion(const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength, sal_Bool toSChinese, sal_Int32 nConversionOptions, Sequence<sal_Int32>& offset)
{
    sal_Int32 dictLen = 0;
    sal_Int32 maxLen = 0;
    const sal_uInt16 *index;
    const sal_uInt16 *entry;
    const sal_Unicode *charData;
    const sal_uInt16 *charIndex;
    sal_Bool one2one=sal_True;

    const sal_Unicode *wordData = ((const sal_Unicode* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordData"))(dictLen);
    if (toSChinese) {
        index = ((const sal_uInt16* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordIndex_T2S"))(maxLen);
        entry = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_WordEntry_T2S"))();
        charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_T2S"))();
        charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_T2S"))();
    } else {
        index = ((const sal_uInt16* (*)(sal_Int32&)) getFunctionBySymbol("getSTC_WordIndex_S2T"))(maxLen);
        entry = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_WordEntry_S2T"))();
        if (nConversionOptions & TextConversionOption::USE_CHARACTER_VARIANTS) {
            charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_S2V"))();
            charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_S2V"))();
        } else {
            charData = ((const sal_Unicode* (*)()) getFunctionBySymbol("getSTC_CharData_S2T"))();
            charIndex = ((const sal_uInt16* (*)()) getFunctionBySymbol("getSTC_CharIndex_S2T"))();
        }
    }

    if ((!wordData || !index || !entry) && !xCDL.is()) // no word mapping defined, do char2char conversion.
        return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);

    rtl_uString * newStr = x_rtl_uString_new_WithLength( nLength * 2 ); // defined in x_rtl_ustring.h
    sal_Int32 currPos = 0, count = 0;
    while (currPos < nLength) {
        sal_Int32 len = nLength - currPos;
        sal_Bool found = sal_False;
        if (len > maxLen)
            len = maxLen;
        for (; len > 0 && ! found; len--) {
            OUString word = aText.copy(nStartPos + currPos, len);
            sal_Int32 current = 0;
            // user dictionary
            if (xCDL.is()) {
                Sequence < OUString > conversions;
                try {
                    conversions = xCDL->queryConversions(word, 0, len,
                            aLocale, ConversionDictionaryType::SCHINESE_TCHINESE,
                            /*toSChinese ?*/ ConversionDirection_FROM_LEFT /*: ConversionDirection_FROM_RIGHT*/,
                            nConversionOptions);
                }
                catch ( NoSupportException & ) {
                    // clear reference (when there is no user dictionary) in order
                    // to not always have to catch this exception again
                    // in further calls. (save time)
                    xCDL = 0;
                }
                catch (...) {
                    // catch all other exceptions to allow
                    // querying the system dictionary in the next line
                }
                if (conversions.getLength() > 0) {
                    if (offset.getLength() > 0) {
                        if (word.getLength() != conversions[0].getLength())
                            one2one=sal_False;
                        while (current < conversions[0].getLength()) {
                            offset[count] = nStartPos + currPos + (current *
                                    word.getLength() / conversions[0].getLength());
                            newStr->buffer[count++] = conversions[0][current++];
                        }
                        // offset[count-1] = nStartPos + currPos + word.getLength() - 1;
                    } else {
                        while (current < conversions[0].getLength())
                            newStr->buffer[count++] = conversions[0][current++];
                    }
                    currPos += word.getLength();
                    found = sal_True;
                }
            }

            if (!found && index[len+1] - index[len] > 0) {
                sal_Int32 bottom = (sal_Int32) index[len];
                sal_Int32 top = (sal_Int32) index[len+1] - 1;

                while (bottom <= top && !found) {
                    current = (top + bottom) / 2;
                    const sal_Int32 result = word.compareTo(wordData + entry[current]);
                    if (result < 0)
                        top = current - 1;
                    else if (result > 0)
                        bottom = current + 1;
                    else {
                        if (toSChinese)   // Traditionary/Simplified conversion,
                            for (current = entry[current]-1; current > 0 && wordData[current-1]; current--);
                        else  // Simplified/Traditionary conversion, forwards search for next word
                            current = entry[current] + word.getLength() + 1;
                        sal_Int32 start=current;
                        if (offset.getLength() > 0) {
                            if (word.getLength() != OUString(&wordData[current]).getLength())
                                one2one=sal_False;
                            sal_Int32 convertedLength=OUString(&wordData[current]).getLength();
                            while (wordData[current]) {
                                offset[count]=nStartPos + currPos + ((current-start) *
                                    word.getLength() / convertedLength);
                                newStr->buffer[count++] = wordData[current++];
                            }
                            // offset[count-1]=nStartPos + currPos + word.getLength() - 1;
                        } else {
                            while (wordData[current])
                                newStr->buffer[count++] = wordData[current++];
                        }
                        currPos += word.getLength();
                        found = sal_True;
                    }
                }
            }
        }
        if (!found) {
            if (offset.getLength() > 0)
                offset[count]=nStartPos+currPos;
            newStr->buffer[count++] =
                getOneCharConversion(aText[nStartPos+currPos], charData, charIndex);
            currPos++;
        }
    }
    if (offset.getLength() > 0)
        offset.realloc(one2one ? 0 : count);
    return OUString( newStr->buffer, count);
}

TextConversionResult SAL_CALL
TextConversion_zh::getConversions( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
    const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)
    throw(  RuntimeException, IllegalArgumentException, NoSupportException )
{
    TextConversionResult result;

    result.Candidates.realloc(1);
    result.Candidates[0] = getConversion( aText, nStartPos, nLength, rLocale, nConversionType, nConversionOptions);
    result.Boundary.startPos = nStartPos;
    result.Boundary.endPos = nStartPos + nLength;

    return result;
}

OUString SAL_CALL
TextConversion_zh::getConversion( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
    const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions)
    throw(  RuntimeException, IllegalArgumentException, NoSupportException )
{
    if (rLocale.Language.equalsAscii("zh") &&
            ( nConversionType == TextConversionType::TO_SCHINESE ||
            nConversionType == TextConversionType::TO_TCHINESE) ) {

        aLocale=rLocale;
        sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE;

        if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER)
            // char to char dictionary
            return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);
        else {
            Sequence <sal_Int32> offset;
            // word to word dictionary
            return  getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset);
        }
    } else
        throw NoSupportException(); // Conversion type is not supported in this service.
}

OUString SAL_CALL
TextConversion_zh::getConversionWithOffset( const OUString& aText, sal_Int32 nStartPos, sal_Int32 nLength,
    const Locale& rLocale, sal_Int16 nConversionType, sal_Int32 nConversionOptions, Sequence<sal_Int32>& offset)
    throw(  RuntimeException, IllegalArgumentException, NoSupportException )
{
    if (rLocale.Language.equalsAscii("zh") &&
            ( nConversionType == TextConversionType::TO_SCHINESE ||
            nConversionType == TextConversionType::TO_TCHINESE) ) {

        aLocale=rLocale;
        sal_Bool toSChinese = nConversionType == TextConversionType::TO_SCHINESE;

        if (nConversionOptions & TextConversionOption::CHARACTER_BY_CHARACTER) {
            offset.realloc(0);
            // char to char dictionary
            return getCharConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions);
        } else {
            if (offset.getLength() < 2*nLength)
                offset.realloc(2*nLength);
            // word to word dictionary
            return  getWordConversion(aText, nStartPos, nLength, toSChinese, nConversionOptions, offset);
        }
    } else
        throw NoSupportException(); // Conversion type is not supported in this service.
}

sal_Bool SAL_CALL
TextConversion_zh::interactiveConversion( const Locale& /*rLocale*/, sal_Int16 /*nTextConversionType*/, sal_Int32 /*nTextConversionOptions*/ )
    throw(  RuntimeException, IllegalArgumentException, NoSupportException )
{
    return sal_False;
}

} } } }
<|endoftext|>


<commit_before>#include "../tests.h"

// Random number generation

using cl::sycl::float1;
using cl::sycl::uint1;
using cl::sycl::uint2;

// http://stackoverflow.com/a/16077942
template <class Float, class Uint1, class Uint2>
Float getRandom(Uint2& seed) {
	static const Float invMaxInt = 1.0f / 4294967296.0f;
	Uint1 x = seed.x() * 17 + seed.y() * 13123;
	seed.x() = (x << 13) ^ x;
	seed.y() ^= x << 7;
	return (Float)(x * (x * x * 15731 + 74323) + 871483) * invMaxInt;
}

float1 deviceRandom(uint2& seed) {
	using namespace cl::sycl;
	return getRandom<float1, uint1>(seed);
}

float hostRandom(cl_uint2& seed) {
	return getRandom<float, cl::sycl::cl_uint>(seed);
}

bool test11() {

	using namespace cl::sycl;
	using namespace std;

	queue myQueue;

	const int size = 4096;
	buffer<float> numbers(size);

	// TODO: Should not be zero
	uint32_t startSeed_x = 24325;
	uint32_t startSeed_y = 32536;

	myQueue.submit([&](handler& cgh) {
		auto n = numbers.get_access<access::mode::discard_write>(cgh);

		cgh.single_task<class generate>([=]() {
			uint2 seed(startSeed_x, startSeed_y);
			SYCL_FOR(int1 i = 0, i < size, ++i) {
				n[i] = deviceRandom(seed);
			}
			SYCL_END
		});
	});

	float eps = 1e-3f;	// Don't need very high accuracy
	auto n = numbers.get_access<access::mode::read, access::target::host_buffer>();
	::cl_uint2 seed = { startSeed_x, startSeed_y };

	// TODO: Better automatic testing
	for(auto i = 0; i < size; ++i) {
		auto hostRnd = hostRandom(seed);
		auto deviceRnd = n[i];
		if(deviceRnd < hostRnd - eps || deviceRnd > hostRnd + eps) {
			cout << i << " -> expected " << hostRnd << ", got " << deviceRnd << endl;
			return false;
		}
	}

	return true;
}
<commit_msg>tests - fixed CL type usage in test11<commit_after>#include "../tests.h"

// Random number generation

using cl::sycl::float1;
using cl::sycl::uint1;
using cl::sycl::uint2;

// http://stackoverflow.com/a/16077942
template <class Float, class Uint1, class Uint2>
Float getRandom(Uint2& seed) {
	static const Float invMaxInt = 1.0f / 4294967296.0f;
	Uint1 x = seed.x() * 17 + seed.y() * 13123;
	seed.x() = (x << 13) ^ x;
	seed.y() ^= x << 7;
	return (Float)(x * (x * x * 15731 + 74323) + 871483) * invMaxInt;
}

float1 deviceRandom(uint2& seed) {
	using namespace cl::sycl;
	return getRandom<float1, uint1>(seed);
}

float hostRandom(cl::sycl::cl_uint2& seed) {
	return getRandom<float, cl::sycl::cl_uint>(seed);
}

bool test11() {

	using namespace cl::sycl;
	using namespace std;

	queue myQueue;

	const int size = 4096;
	buffer<float> numbers(size);

	// TODO: Should not be zero
	::cl_uint2 startSeed = { 24325, 32536 };

	myQueue.submit([&](handler& cgh) {
		auto n = numbers.get_access<access::mode::discard_write>(cgh);

		cgh.single_task<class generate>([=]() {
			uint2 seed(startSeed.x, startSeed.y);
			SYCL_FOR(int1 i = 0, i < size, ++i) {
				n[i] = deviceRandom(seed);
			}
			SYCL_END
		});
	});

	float eps = 1e-3f;	// Don't need very high accuracy
	auto n = numbers.get_access<access::mode::read, access::target::host_buffer>();
	cl::sycl::cl_uint2 seed = startSeed;

	// TODO: Better automatic testing
	for(auto i = 0; i < size; ++i) {
		auto hostRnd = hostRandom(seed);
		auto deviceRnd = n[i];
		if(deviceRnd < hostRnd - eps || deviceRnd > hostRnd + eps) {
			cout << i << " -> expected " << hostRnd << ", got " << deviceRnd << endl;
			return false;
		}
	}

	return true;
}
<|endoftext|>


<commit_before>#include <QSettings>
#include <QTranslator>

#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <projectexplorer/task.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/buildsteplist.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/buildmanager.h>
#include <coreplugin/icore.h>

#include <QtPlugin>

#include "QtcPaneEncodePlugin.h"
#include "OptionsPage.h"
#include "Utils.h"
#include "Constants.h"

using namespace QtcPaneEncode::Internal;
using namespace QtcPaneEncode::Constants;

using namespace Core;
using namespace ProjectExplorer;
using namespace ExtensionSystem;

namespace {
  const QString appOutputPaneClassName =
      QLatin1String("ProjectExplorer::Internal::AppOutputPane");
}

QtcPaneEncodePlugin::QtcPaneEncodePlugin():
  IPlugin()
{
  // Create your members
}

QtcPaneEncodePlugin::~QtcPaneEncodePlugin() {
  // Unregister objects from the plugin manager's object pool
  // Delete members
}

bool QtcPaneEncodePlugin::initialize(const QStringList &arguments, QString *errorString) {
  // Register objects in the plugin manager's object pool
  // Load settings
  // Add actions to menus
  // Connect to other plugins' signals
  // In the initialize function, a plugin can be sure that the plugins it
  // depends on have initialized their members.

  Q_UNUSED(arguments)
  Q_UNUSED(errorString)

  initLanguage();
  updateSettings();

  OptionsPage *optionsPage = new OptionsPage;
  connect(optionsPage, SIGNAL(settingsChanged()), SLOT(updateSettings()));
  addAutoReleasedObject(optionsPage);

  return true;
}

void QtcPaneEncodePlugin::initLanguage() {
  const QString& language = Core::ICore::userInterfaceLanguage();
  if (!language.isEmpty()) {
    QStringList paths;
    paths << ICore::resourcePath () << ICore::userResourcePath();
    const QString& trFile = QLatin1String ("QtcPaneEncode_") + language;
    QTranslator* translator = new QTranslator (this);
    foreach (const QString& path, paths) {
      if (translator->load (trFile, path + QLatin1String ("/translations"))) {
        qApp->installTranslator (translator);
        break;
      }
    }
  }
}

void QtcPaneEncodePlugin::updateSettings() {
  Q_ASSERT(Core::ICore::settings() != NULL);
  QSettings& settings = *(Core::ICore::settings());
  settings.beginGroup(SETTINGS_GROUP);

  if(settings.value(SETTINGS_BUILD_ENABLED, false).toBool()) {
    buildEncoding_ = settings.value(SETTINGS_BUILD_ENCODING, AUTO_ENCODING).toByteArray();
  }
  else {
    buildEncoding_.clear();
  }

  if(settings.value(SETTINGS_APP_ENABLED, false).toBool()) {
    appEncoding_ = settings.value(SETTINGS_APP_ENCODING, AUTO_ENCODING).toByteArray();
  }
  else {
    appEncoding_.clear();
  }

  settings.endGroup();
}

void QtcPaneEncodePlugin::extensionsInitialized() {
  // Retrieve objects from the plugin manager's object pool
  // In the extensionsInitialized function, a plugin can be sure that all
  // plugins that depend on it are completely initialized.

  // Compiler output
  connect(BuildManager::instance(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
          this, SLOT(handleBuild(ProjectExplorer::Project*)));
  connect(this, SIGNAL(newOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
          BuildManager::instance(), SLOT(addToOutputWindow(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)));
  connect(this, SIGNAL(newTask(ProjectExplorer::Task, int, int)),
          BuildManager::instance(), SLOT(addToTaskWindow(ProjectExplorer::Task, int, int)));

  // Run control output
  QObject *appOutputPane = PluginManager::getObjectByClassName(appOutputPaneClassName);
  if(appOutputPane != NULL) {
    connect(ProjectExplorerPlugin::instance(), SIGNAL(runControlStarted(ProjectExplorer::RunControl *)),
             this, SLOT(handleRunStart(ProjectExplorer::RunControl *)));
    connect(this, SIGNAL(newMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
            appOutputPane, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)));
  }
  else {
    qCritical() << "Failed to find appOutputPane";
  }
}

ExtensionSystem::IPlugin::ShutdownFlag QtcPaneEncodePlugin::aboutToShutdown() {
  // Save settings
  // Disconnect from signals that are not needed during shutdown
  // Hide UI(if you add UI that is not in the main window directly)
  this->disconnect();
  return SynchronousShutdown;
}

void QtcPaneEncodePlugin::handleBuild(ProjectExplorer::Project *project) {
  if(!BuildManager::isBuilding()) {
    return;
  }
  const Target *buildingTarget = NULL;
  foreach(Target* target, project->targets ()) {
    if (BuildManager::isBuilding (target)) {
      buildingTarget = target;
      break;
    }
  }
  if(buildingTarget == NULL) {
    return;
  }

  BuildConfiguration* buildingConfiguration = NULL;
  foreach(BuildConfiguration* config, buildingTarget->buildConfigurations ()) {
    if (BuildManager::isBuilding (config)) {
      buildingConfiguration = config;
      break;
    }
  }
  if(buildingConfiguration == NULL) {
    return;
  }

  QList<Core::Id> stepsIds = buildingConfiguration->knownStepLists();
  foreach(const Core::Id &id, stepsIds) {
    BuildStepList *steps = buildingConfiguration->stepList(id);
    if(steps == NULL) {
      continue;
    }
    for(int i = 0, end = steps->count(); i < end; ++i) {
      BuildStep *step = steps->at(i);
      connect(step, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
              this, SLOT(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
              Qt::UniqueConnection);
      disconnect(step, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
                 BuildManager::instance(), SLOT(addToOutputWindow(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)));

      connect(step, SIGNAL(addTask(ProjectExplorer::Task, int, int)),
              this, SLOT(addTask(ProjectExplorer::Task, int, int)),
              Qt::UniqueConnection);
      disconnect(step, SIGNAL(addTask(ProjectExplorer::Task, int, int)),
                 BuildManager::instance(), SLOT(addToTaskWindow(ProjectExplorer::Task, int, int)));
    }
  }
}

void QtcPaneEncodePlugin::addTask(const Task &task, int linkedOutputLines, int skipLines) {
  if (buildEncoding_.isEmpty ()) {
    emit newTask(task, linkedOutputLines, skipLines);
    return;
  }
  Task convertedTask = task;
  // Unknown charset will be handled like auto-detection request
  convertedTask.description = reencode(task.description,
                                       QTextCodec::codecForName(buildEncoding_));
  emit newTask(convertedTask, linkedOutputLines, skipLines);
}

void QtcPaneEncodePlugin::addOutput(const QString &string, BuildStep::OutputFormat format, BuildStep::OutputNewlineSetting newlineSetting) {
  if (buildEncoding_.isEmpty ()) {
    emit newOutput(string, format, newlineSetting);
    return;
  }
  QString convertedString = reencode(string,
                                     QTextCodec::codecForName(buildEncoding_));
  emit newOutput(convertedString, format, newlineSetting);
}

void QtcPaneEncodePlugin::handleRunStart(RunControl *runControl) {
  QObject *appOutputPane = PluginManager::getObjectByClassName(appOutputPaneClassName);
  if(appOutputPane != NULL) {
    connect(runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
            this, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
            Qt::UniqueConnection);
    disconnect(runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
                appOutputPane, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)));
  }
}

void QtcPaneEncodePlugin::appendMessage(RunControl *rc, const QString &out, Utils::OutputFormat format) {
  if (appEncoding_.isEmpty ()) {
    emit newMessage(rc, out, format);
    return;
  }
  QString convertedOut = reencode(out, QTextCodec::codecForName(appEncoding_));
  emit newMessage(rc, convertedOut, format);
}
<commit_msg>Qtc 4.0.2 "fix". Requires to make QtcPaneEncodePlugin friend to BuildManager (change qtc source). Also disconnects all slots from BuildStep::addOutput/Task instead of only required ones. Acceptable for now (there is only 1 connection) but may break something in future.<commit_after>#include <QSettings>
#include <QTranslator>

#include <projectexplorer/projectexplorer.h>
#include <projectexplorer/project.h>
#include <projectexplorer/target.h>
#include <projectexplorer/task.h>
#include <projectexplorer/buildconfiguration.h>
#include <projectexplorer/buildsteplist.h>
#include <extensionsystem/pluginmanager.h>
#include <projectexplorer/buildmanager.h>
#include <coreplugin/icore.h>

#include <QtPlugin>

#include "QtcPaneEncodePlugin.h"
#include "OptionsPage.h"
#include "Utils.h"
#include "Constants.h"

using namespace QtcPaneEncode::Internal;
using namespace QtcPaneEncode::Constants;

using namespace Core;
using namespace ProjectExplorer;
using namespace ExtensionSystem;

namespace {
  const QString appOutputPaneClassName =
      QLatin1String("ProjectExplorer::Internal::AppOutputPane");
}

QtcPaneEncodePlugin::QtcPaneEncodePlugin():
  IPlugin()
{
  // Create your members
}

QtcPaneEncodePlugin::~QtcPaneEncodePlugin() {
  // Unregister objects from the plugin manager's object pool
  // Delete members
}

bool QtcPaneEncodePlugin::initialize(const QStringList &arguments, QString *errorString) {
  // Register objects in the plugin manager's object pool
  // Load settings
  // Add actions to menus
  // Connect to other plugins' signals
  // In the initialize function, a plugin can be sure that the plugins it
  // depends on have initialized their members.

  Q_UNUSED(arguments)
  Q_UNUSED(errorString)

  initLanguage();
  updateSettings();

  OptionsPage *optionsPage = new OptionsPage;
  connect(optionsPage, SIGNAL(settingsChanged()), SLOT(updateSettings()));
  addAutoReleasedObject(optionsPage);

  return true;
}

void QtcPaneEncodePlugin::initLanguage() {
  const QString& language = Core::ICore::userInterfaceLanguage();
  if (!language.isEmpty()) {
    QStringList paths;
    paths << ICore::resourcePath () << ICore::userResourcePath();
    const QString& trFile = QLatin1String ("QtcPaneEncode_") + language;
    QTranslator* translator = new QTranslator (this);
    foreach (const QString& path, paths) {
      if (translator->load (trFile, path + QLatin1String ("/translations"))) {
        qApp->installTranslator (translator);
        break;
      }
    }
  }
}

void QtcPaneEncodePlugin::updateSettings() {
  Q_ASSERT(Core::ICore::settings() != NULL);
  QSettings& settings = *(Core::ICore::settings());
  settings.beginGroup(SETTINGS_GROUP);

  if(settings.value(SETTINGS_BUILD_ENABLED, false).toBool()) {
    buildEncoding_ = settings.value(SETTINGS_BUILD_ENCODING, AUTO_ENCODING).toByteArray();
  }
  else {
    buildEncoding_.clear();
  }

  if(settings.value(SETTINGS_APP_ENABLED, false).toBool()) {
    appEncoding_ = settings.value(SETTINGS_APP_ENCODING, AUTO_ENCODING).toByteArray();
  }
  else {
    appEncoding_.clear();
  }

  settings.endGroup();
}

void QtcPaneEncodePlugin::extensionsInitialized() {
  // Retrieve objects from the plugin manager's object pool
  // In the extensionsInitialized function, a plugin can be sure that all
  // plugins that depend on it are completely initialized.

  // Compiler output
  connect(BuildManager::instance(), SIGNAL(buildStateChanged(ProjectExplorer::Project*)),
          this, SLOT(handleBuild(ProjectExplorer::Project*)));
  connect(this, &QtcPaneEncodePlugin::newOutput,
          BuildManager::instance(), &BuildManager::addToOutputWindow);
  connect(this, &QtcPaneEncodePlugin::newTask,
          BuildManager::instance(), &BuildManager::addToTaskWindow);

  // Run control output
  QObject *appOutputPane = PluginManager::getObjectByClassName(appOutputPaneClassName);
  if(appOutputPane != NULL) {
    connect(ProjectExplorerPlugin::instance(), SIGNAL(runControlStarted(ProjectExplorer::RunControl *)),
             this, SLOT(handleRunStart(ProjectExplorer::RunControl *)));
    connect(this, SIGNAL(newMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
            appOutputPane, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)));
  }
  else {
    qCritical() << "Failed to find appOutputPane";
  }
}

ExtensionSystem::IPlugin::ShutdownFlag QtcPaneEncodePlugin::aboutToShutdown() {
  // Save settings
  // Disconnect from signals that are not needed during shutdown
  // Hide UI(if you add UI that is not in the main window directly)
  this->disconnect();
  return SynchronousShutdown;
}

void QtcPaneEncodePlugin::handleBuild(ProjectExplorer::Project *project) {
  if(!BuildManager::isBuilding()) {
    return;
  }
  const Target *buildingTarget = NULL;
  foreach(Target* target, project->targets ()) {
    if (BuildManager::isBuilding (target)) {
      buildingTarget = target;
      break;
    }
  }
  if(buildingTarget == NULL) {
    return;
  }

  BuildConfiguration* buildingConfiguration = NULL;
  foreach(BuildConfiguration* config, buildingTarget->buildConfigurations ()) {
    if (BuildManager::isBuilding (config)) {
      buildingConfiguration = config;
      break;
    }
  }
  if(buildingConfiguration == NULL) {
    return;
  }

  QList<Core::Id> stepsIds = buildingConfiguration->knownStepLists();
  foreach(const Core::Id &id, stepsIds) {
    BuildStepList *steps = buildingConfiguration->stepList(id);
    if(steps == NULL) {
      continue;
    }
    for(int i = 0, end = steps->count(); i < end; ++i) {
      BuildStep *step = steps->at(i);
      disconnect(step, &BuildStep::addOutput, 0, 0);
      connect(step, SIGNAL(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
              this, SLOT(addOutput(QString,ProjectExplorer::BuildStep::OutputFormat,ProjectExplorer::BuildStep::OutputNewlineSetting)),
              Qt::UniqueConnection);

      disconnect(step, &BuildStep::addTask, 0, 0);
      connect(step, SIGNAL(addTask(ProjectExplorer::Task, int, int)),
              this, SLOT(addTask(ProjectExplorer::Task, int, int)),
              Qt::UniqueConnection);
    }
  }
}

void QtcPaneEncodePlugin::addTask(const Task &task, int linkedOutputLines, int skipLines) {
  if (buildEncoding_.isEmpty ()) {
    emit newTask(task, linkedOutputLines, skipLines);
    return;
  }
  Task convertedTask = task;
  // Unknown charset will be handled like auto-detection request
  convertedTask.description = reencode(task.description,
                                       QTextCodec::codecForName(buildEncoding_));
  emit newTask(convertedTask, linkedOutputLines, skipLines);
}

void QtcPaneEncodePlugin::addOutput(const QString &string, BuildStep::OutputFormat format, BuildStep::OutputNewlineSetting newlineSetting) {
  if (buildEncoding_.isEmpty ()) {
    emit newOutput(string, format, newlineSetting);
    return;
  }
  QString convertedString = reencode(string,
                                     QTextCodec::codecForName(buildEncoding_));
  emit newOutput(convertedString, format, newlineSetting);
}

void QtcPaneEncodePlugin::handleRunStart(RunControl *runControl) {
  QObject *appOutputPane = PluginManager::getObjectByClassName(appOutputPaneClassName);
  if(appOutputPane != NULL) {
    connect(runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
            this, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
            Qt::UniqueConnection);
    disconnect(runControl, SIGNAL(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)),
                appOutputPane, SLOT(appendMessage(ProjectExplorer::RunControl*,QString,Utils::OutputFormat)));
  }
}

void QtcPaneEncodePlugin::appendMessage(RunControl *rc, const QString &out, Utils::OutputFormat format) {
  if (appEncoding_.isEmpty ()) {
    emit newMessage(rc, out, format);
    return;
  }
  QString convertedOut = reencode(out, QTextCodec::codecForName(appEncoding_));
  emit newMessage(rc, convertedOut, format);
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkReviewHeaderTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
#include <cstdlib>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkBinaryMorphologicalClosingImageFilter.txx"
#include "itkBinaryMorphologicalOpeningImageFilter.txx"
#include "itkConformalFlatteningMeshFilter.txx"
#include "itkContourExtractor2DImageFilter.txx"
#include "itkFlatStructuringElement.txx"
#include "itkGeometricalQuadEdge.txx"
#include "itkImageToPathFilter.txx"
#include "itkLabelOverlayFunctor.h"
#include "itkLabelOverlayImageFilter.txx"
#include "itkLabelToRGBFunctor.h"
#include "itkLabelToRGBImageFilter.txx"
#include "itkMatlabTransformIO.h"
#include "itkMatlabTransformIOFactory.h"
#include "itkMorphologicalWatershedFromMarkersImageFilter.txx"
#include "itkMorphologicalWatershedImageFilter.txx"
#include "itkNeuralNetworkFileReader.txx"
#include "itkNeuralNetworkFileWriter.txx"
#include "itkQuadEdge.h"
#include "itkQuadEdgeCellTraitsInfo.h"
#include "itkQuadEdgeMesh.txx"
#include "itkQuadEdgeMeshBaseIterator.h"
#include "itkQuadEdgeMeshBoundaryEdgesMeshFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorCreateCenterVertexFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorDeleteCenterVertexFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorJoinFacetFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorJoinVertexFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorSplitEdgeFunction.h"
#include "itkQuadEdgeMeshEulerOperatorSplitFacetFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorSplitVertexFunction.txx"
#include "itkQuadEdgeMeshFrontIterator.txx"
#include "itkQuadEdgeMeshFunctionBase.h"
#include "itkQuadEdgeMeshLineCell.txx"
#include "itkQuadEdgeMeshMacro.h"
#include "itkQuadEdgeMeshPoint.txx"
#include "itkQuadEdgeMeshPolygonCell.txx"
#include "itkQuadEdgeMeshToQuadEdgeMeshFilter.txx"
#include "itkQuadEdgeMeshTopologyChecker.txx"
#include "itkQuadEdgeMeshTraits.h"
#include "itkQuadEdgeMeshZipMeshFunction.txx"
#include "itkRegionalMaximaImageFilter.txx"
#include "itkRegionalMinimaImageFilter.txx"
#include "itkTransformFileReaderWithFactory.h"
#include "itkTransformFileWriterWithFactory.h"
#include "itkTransformIOBase.h"
#include "itkTransformIOFactory.h"
#include "itkTxtTransformIO.h"
#include "itkTxtTransformIOFactory.h"
#include "itkVTKPolyDataReader.txx"
#include "itkVTKPolyDataWriter.txx"
#include "itkValuedRegionalExtremaImageFilter.txx"
#include "itkValuedRegionalMaximaImageFilter.h"
#include "itkValuedRegionalMinimaImageFilter.h"

#include "itkBoxImageFilter.h"
#include "itkKernelImageFilter.h"
#include "itkMovingHistogramImageFilterBase.h"
#include "itkMovingHistogramImageFilter.h"
#include "itkMovingHistogramMorphologyImageFilter.h"
#include "itkMovingHistogramDilateImageFilter.h"
#include "itkMovingHistogramErodeImageFilter.h"
#include "itkMovingHistogramMorphologicalGradientImageFilter.h"
#include "itkBasicDilateImageFilter.h"
#include "itkBasicErodeImageFilter.h"
#include "itkAnchorCloseImageFilter.h"
#include "itkAnchorDilateImageFilter.h"
#include "itkAnchorErodeDilateImageFilter.h"
#include "itkAnchorErodeDilateImageFilter.txx"
#include "itkAnchorErodeDilateLine.h"
#include "itkAnchorErodeDilateLine.txx"
#include "itkAnchorErodeImageFilter.h"
#include "itkAnchorHistogram.h"
#include "itkAnchorOpenCloseImageFilter.h"
#include "itkAnchorOpenCloseImageFilter.txx"
#include "itkAnchorOpenCloseLine.h"
#include "itkAnchorOpenCloseLine.txx"
#include "itkAnchorOpenImageFilter.h"
#include "itkAnchorUtilities.h"
#include "itkAnchorUtilities.txx"
#include "itkBresenhamLine.h"
#include "itkBresenhamLine.txx"
#include "itkSharedMorphologyUtilities.h"
#include "itkSharedMorphologyUtilities.txx"
#include "itkVanHerkGilWermanDilateImageFilter.h"
#include "itkVanHerkGilWermanErodeDilateImageFilter.h"
#include "itkVanHerkGilWermanErodeDilateImageFilter.txx"
#include "itkVanHerkGilWermanErodeImageFilter.h"
#include "itkVanHerkGilWermanUtilities.h"
#include "itkVanHerkGilWermanUtilities.txx"

#include "itkBoxUtilities.h"
#include "itkBoxMeanImageFilter.h"
#include "itkBoxMeanImageFilter.txx"
#include "itkBoxSigmaImageFilter.h"
#include "itkBoxSigmaImageFilter.txx"

#include "itkRankHistogram.h"
#include "itkRankImageFilter.h"
#include "itkRankImageFilter.txx"
#include "itkMaskedRankHistogram.h"
#include "itkMaskedRankImageFilter.h"
#include "itkMaskedRankImageFilter.txx"
#include "itkMiniPipelineSeparableImageFilter.h"
#include "itkMiniPipelineSeparableImageFilter.txx"
#include "itkFastApproximateRankImageFilter.h"

#include "itkBinaryContourImageFilter.h"
#include "itkLabelContourImageFilter.h"

#include "itkFFTShiftImageFilter.h"

#include "itkConvolutionImageFilter.h"

#include "itkHessianToObjectnessMeasureImageFilter.h"
#include "itkMultiScaleHessianBasedMeasureImageFilterTest.h"

int main ( int , char * [] )
{

  return EXIT_SUCCESS;
}
<commit_msg>BUG: incorrect header file included<commit_after>/*=========================================================================

  Program:   Insight Segmentation & Registration Toolkit
  Module:    itkReviewHeaderTest.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) Insight Software Consortium. All rights reserved.
  See ITKCopyright.txt or http://www.itk.org/HTML/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notices for more information.

=========================================================================*/
#if defined(_MSC_VER)
#pragma warning ( disable : 4786 )
#endif

#include <iostream>
#include <cstdlib>
// This file has been generated by BuildHeaderTest.tcl
// Test to include each header file for Insight

#include "itkBinaryMorphologicalClosingImageFilter.txx"
#include "itkBinaryMorphologicalOpeningImageFilter.txx"
#include "itkConformalFlatteningMeshFilter.txx"
#include "itkContourExtractor2DImageFilter.txx"
#include "itkFlatStructuringElement.txx"
#include "itkGeometricalQuadEdge.txx"
#include "itkImageToPathFilter.txx"
#include "itkLabelOverlayFunctor.h"
#include "itkLabelOverlayImageFilter.txx"
#include "itkLabelToRGBFunctor.h"
#include "itkLabelToRGBImageFilter.txx"
#include "itkMatlabTransformIO.h"
#include "itkMatlabTransformIOFactory.h"
#include "itkMorphologicalWatershedFromMarkersImageFilter.txx"
#include "itkMorphologicalWatershedImageFilter.txx"
#include "itkNeuralNetworkFileReader.txx"
#include "itkNeuralNetworkFileWriter.txx"
#include "itkQuadEdge.h"
#include "itkQuadEdgeCellTraitsInfo.h"
#include "itkQuadEdgeMesh.txx"
#include "itkQuadEdgeMeshBaseIterator.h"
#include "itkQuadEdgeMeshBoundaryEdgesMeshFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorCreateCenterVertexFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorDeleteCenterVertexFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorFlipEdgeFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorJoinFacetFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorJoinVertexFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorSplitEdgeFunction.h"
#include "itkQuadEdgeMeshEulerOperatorSplitFacetFunction.txx"
#include "itkQuadEdgeMeshEulerOperatorSplitVertexFunction.txx"
#include "itkQuadEdgeMeshFrontIterator.txx"
#include "itkQuadEdgeMeshFunctionBase.h"
#include "itkQuadEdgeMeshLineCell.txx"
#include "itkQuadEdgeMeshMacro.h"
#include "itkQuadEdgeMeshPoint.txx"
#include "itkQuadEdgeMeshPolygonCell.txx"
#include "itkQuadEdgeMeshToQuadEdgeMeshFilter.txx"
#include "itkQuadEdgeMeshTopologyChecker.txx"
#include "itkQuadEdgeMeshTraits.h"
#include "itkQuadEdgeMeshZipMeshFunction.txx"
#include "itkRegionalMaximaImageFilter.txx"
#include "itkRegionalMinimaImageFilter.txx"
#include "itkTransformFileReaderWithFactory.h"
#include "itkTransformFileWriterWithFactory.h"
#include "itkTransformIOBase.h"
#include "itkTransformIOFactory.h"
#include "itkTxtTransformIO.h"
#include "itkTxtTransformIOFactory.h"
#include "itkVTKPolyDataReader.txx"
#include "itkVTKPolyDataWriter.txx"
#include "itkValuedRegionalExtremaImageFilter.txx"
#include "itkValuedRegionalMaximaImageFilter.h"
#include "itkValuedRegionalMinimaImageFilter.h"

#include "itkBoxImageFilter.h"
#include "itkKernelImageFilter.h"
#include "itkMovingHistogramImageFilterBase.h"
#include "itkMovingHistogramImageFilter.h"
#include "itkMovingHistogramMorphologyImageFilter.h"
#include "itkMovingHistogramDilateImageFilter.h"
#include "itkMovingHistogramErodeImageFilter.h"
#include "itkMovingHistogramMorphologicalGradientImageFilter.h"
#include "itkBasicDilateImageFilter.h"
#include "itkBasicErodeImageFilter.h"
#include "itkAnchorCloseImageFilter.h"
#include "itkAnchorDilateImageFilter.h"
#include "itkAnchorErodeDilateImageFilter.h"
#include "itkAnchorErodeDilateImageFilter.txx"
#include "itkAnchorErodeDilateLine.h"
#include "itkAnchorErodeDilateLine.txx"
#include "itkAnchorErodeImageFilter.h"
#include "itkAnchorHistogram.h"
#include "itkAnchorOpenCloseImageFilter.h"
#include "itkAnchorOpenCloseImageFilter.txx"
#include "itkAnchorOpenCloseLine.h"
#include "itkAnchorOpenCloseLine.txx"
#include "itkAnchorOpenImageFilter.h"
#include "itkAnchorUtilities.h"
#include "itkAnchorUtilities.txx"
#include "itkBresenhamLine.h"
#include "itkBresenhamLine.txx"
#include "itkSharedMorphologyUtilities.h"
#include "itkSharedMorphologyUtilities.txx"
#include "itkVanHerkGilWermanDilateImageFilter.h"
#include "itkVanHerkGilWermanErodeDilateImageFilter.h"
#include "itkVanHerkGilWermanErodeDilateImageFilter.txx"
#include "itkVanHerkGilWermanErodeImageFilter.h"
#include "itkVanHerkGilWermanUtilities.h"
#include "itkVanHerkGilWermanUtilities.txx"

#include "itkBoxUtilities.h"
#include "itkBoxMeanImageFilter.h"
#include "itkBoxMeanImageFilter.txx"
#include "itkBoxSigmaImageFilter.h"
#include "itkBoxSigmaImageFilter.txx"

#include "itkRankHistogram.h"
#include "itkRankImageFilter.h"
#include "itkRankImageFilter.txx"
#include "itkMaskedRankHistogram.h"
#include "itkMaskedRankImageFilter.h"
#include "itkMaskedRankImageFilter.txx"
#include "itkMiniPipelineSeparableImageFilter.h"
#include "itkMiniPipelineSeparableImageFilter.txx"
#include "itkFastApproximateRankImageFilter.h"

#include "itkBinaryContourImageFilter.h"
#include "itkLabelContourImageFilter.h"

#include "itkFFTShiftImageFilter.h"

#include "itkConvolutionImageFilter.h"

#include "itkHessianToObjectnessMeasureImageFilter.h"
#include "itkMultiScaleHessianBasedMeasureImageFilter.h"

int main ( int , char * [] )
{

  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 13129 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkRigidRegistrationPreset.h"
#include <itkArray.h>

int mitkRigidRegistrationPresetTest(int argc, char* argv[])
{
  typedef itk::Array<double>               ArrayType;

  mitk::RigidRegistrationPreset* rrp = new mitk::RigidRegistrationPreset;
  std::cout<<"[PASSED]"<<std::endl;

  // Check if the default presets (in the Functionality directory) can be loaded.
  std::cout<<"Testing default parameter loading...\n";
  if(!rrp->LoadPreset())
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  // Check if an exemplary parameter set can be extracted from the read presets.
  std::cout<<"Testing if exemplary default values match default parameters...\n";

  ArrayType transformValues = rrp->getTransformValues("ITK Image Registration 12");
  ArrayType metricValues = rrp->getMetricValues("ITK Image Registration 12");
  ArrayType optimizerValues = rrp->getOptimizerValues("ITK Image Registration 12");
  ArrayType interpolatorValues = rrp->getInterpolatorValues("ITK Image Registration 12");

  std::cout << transformValues[5] << metricValues[1] << optimizerValues[4] << interpolatorValues[0] << std::endl;

  if( !(transformValues[5]==0.001) || !(metricValues[1]==1) || !(optimizerValues[4]==0.1) || !(interpolatorValues[0]==0) )
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  // Testing if a save operation can be performed.
  std::cout<<"Testing if saving is possible...\n";
  if (!rrp->newPresets( rrp->getTransformValuesPresets(), rrp->getMetricValuesPresets(),
    rrp->getOptimizerValuesPresets(), rrp->getInterpolatorValuesPresets() ))
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  // Testing what happens if we now repeat the test with the previously written xml file
  delete rrp;

  mitk::RigidRegistrationPreset* rrp2 = new mitk::RigidRegistrationPreset;
  std::cout<<"[PASSED]"<<std::endl;

  // Check if the default presets (in the Functionality directory) can be loaded.
  std::cout<<"Testing default parameter loading, second time...\n";
  if(!rrp2->LoadPreset())
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  // Check if an exemplary parameter set can be extracted from the read presets.
  std::cout<<"Testing if exemplary default values match default parameters, second time...\n";

  transformValues = rrp2->getTransformValues("ITK Image Registration 12");
  metricValues = rrp2->getMetricValues("ITK Image Registration 12");
  optimizerValues = rrp2->getOptimizerValues("ITK Image Registration 12");
  interpolatorValues = rrp2->getInterpolatorValues("ITK Image Registration 12");

  if( !(transformValues[5]==0.001) || !(metricValues[1]==1) || !(optimizerValues[4]==0.1) || !(interpolatorValues[0]==0) )
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  delete rrp2;

  std::cout<<"[TEST DONE]"<<std::endl;
  return EXIT_SUCCESS;
}<commit_msg>COMP: Fix warnings<commit_after>/*=========================================================================

Program:   Medical Imaging & Interaction Toolkit
Language:  C++
Date:      $Date$
Version:   $Revision: 13129 $

Copyright (c) German Cancer Research Center, Division of Medical and
Biological Informatics. All rights reserved.
See MITKCopyright.txt or http://www.mitk.org/copyright.html for details.

This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE.  See the above copyright notices for more information.

=========================================================================*/

#include "mitkRigidRegistrationPreset.h"
#include <itkArray.h>

int mitkRigidRegistrationPresetTest(int /*argc*/, char* /*argv*/[])
{
  typedef itk::Array<double>               ArrayType;

  mitk::RigidRegistrationPreset* rrp = new mitk::RigidRegistrationPreset;
  std::cout<<"[PASSED]"<<std::endl;

  // Check if the default presets (in the Functionality directory) can be loaded.
  std::cout<<"Testing default parameter loading...\n";
  if(!rrp->LoadPreset())
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  // Check if an exemplary parameter set can be extracted from the read presets.
  std::cout<<"Testing if exemplary default values match default parameters...\n";

  ArrayType transformValues = rrp->getTransformValues("ITK Image Registration 12");
  ArrayType metricValues = rrp->getMetricValues("ITK Image Registration 12");
  ArrayType optimizerValues = rrp->getOptimizerValues("ITK Image Registration 12");
  ArrayType interpolatorValues = rrp->getInterpolatorValues("ITK Image Registration 12");

  std::cout << transformValues[5] << metricValues[1] << optimizerValues[4] << interpolatorValues[0] << std::endl;

  if( !(transformValues[5]==0.001) || !(metricValues[1]==1) || !(optimizerValues[4]==0.1) || !(interpolatorValues[0]==0) )
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  // Testing if a save operation can be performed.
  std::cout<<"Testing if saving is possible...\n";
  if (!rrp->newPresets( rrp->getTransformValuesPresets(), rrp->getMetricValuesPresets(),
    rrp->getOptimizerValuesPresets(), rrp->getInterpolatorValuesPresets() ))
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  // Testing what happens if we now repeat the test with the previously written xml file
  delete rrp;

  mitk::RigidRegistrationPreset* rrp2 = new mitk::RigidRegistrationPreset;
  std::cout<<"[PASSED]"<<std::endl;

  // Check if the default presets (in the Functionality directory) can be loaded.
  std::cout<<"Testing default parameter loading, second time...\n";
  if(!rrp2->LoadPreset())
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  // Check if an exemplary parameter set can be extracted from the read presets.
  std::cout<<"Testing if exemplary default values match default parameters, second time...\n";

  transformValues = rrp2->getTransformValues("ITK Image Registration 12");
  metricValues = rrp2->getMetricValues("ITK Image Registration 12");
  optimizerValues = rrp2->getOptimizerValues("ITK Image Registration 12");
  interpolatorValues = rrp2->getInterpolatorValues("ITK Image Registration 12");

  if( !(transformValues[5]==0.001) || !(metricValues[1]==1) || !(optimizerValues[4]==0.1) || !(interpolatorValues[0]==0) )
  {
    std::cout<<"[FAILED]"<<std::endl;
    return EXIT_FAILURE;
  }
  std::cout<<"[PASSED]"<<std::endl;

  delete rrp2;

  std::cout<<"[TEST DONE]"<<std::endl;
  return EXIT_SUCCESS;
}
<|endoftext|>


<commit_before>/*
Copyright (c) 2015-2017 Advanced Micro Devices, Inc. All rights reserved.
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.
*/

/* HIT_START
 * BUILD: %t %s ../test_common.cpp EXCLUDE_HIP_PLATFORM nvcc
 * RUN: %t
 * HIT_END
 */

#include <iostream>
#include <hip/hip_fp16.h>
#include "hip/hip_runtime.h"
#include "test_common.h"

#if __HIP_ARCH_GFX803__ || __HIP_ARCH_GFX900__ || __HIP_ARCH_GFX906__

__global__
__attribute__((optnone))
void __halfMath(bool* result) {
  __half a{1};

  result[0] = __heq(__hadd(a, __half{1}), __half{2});
  result[0] = __heq(__hadd_sat(a, __half{1}), __half{1}) && result[0];
  result[0] = __heq(__hfma(a, __half{2}, __half{3}), __half{5}) && result[0];
  result[0] =
    __heq(__hfma_sat(a, __half{2}, __half{3}), __half{1}) && result[0];
  result[0] = __heq(__hsub(a, __half{1}), __half{0}) && result[0];
  result[0] = __heq(__hsub_sat(a, __half{2}), __half{0}) && result[0];
  result[0] = __heq(__hmul(a, __half{2}), __half{2}) && result[0];
  result[0] = __heq(__hmul_sat(a, __half{2}), __half{1}) && result[0];
  result[0] = __heq(__hdiv(a, __half{2}), __half{0.5}) && result[0];
}

__device__
bool to_bool(const __half2& x)
{
  auto r = static_cast<const __half2_raw&>(x);

  return r.data.x != 0 && r.data.y != 0;
}

__global__
__attribute__((optnone))
void __half2Math(bool* result) {
  __half2 a{1, 1};

  result[0] = to_bool(__heq2(__hadd2(a, __half2{1, 1}), __half2{2, 2}));
  result[0] = to_bool(__heq2(__hadd2_sat(a, __half2{1, 1}), __half2{1, 1})) &&
    result[0];
  result[0] = to_bool(__heq2(
    __hfma2(a, __half2{2, 2}, __half2{3, 3}), __half2{5, 5})) && result[0];
  result[0] = to_bool(__heq2(
    __hfma2_sat(a, __half2{2, 2}, __half2{3, 3}), __half2{1, 1})) && result[0];
  result[0] = to_bool(__heq2(__hsub2(a, __half2{1, 1}), __half2{0, 0})) &&
    result[0];
  result[0] = to_bool(__heq2(__hsub2_sat(a, __half2{2, 2}), __half2{0, 0})) &&
    result[0];
  result[0] = to_bool(__heq2(__hmul2(a, __half2{2, 2}), __half2{2, 2})) &&
    result[0];
  result[0] = to_bool(__heq2(__hmul2_sat(a, __half2{2, 2}), __half2{1, 1})) &&
    result[0];
  result[0] = to_bool(__heq2(__h2div(a, __half2{2, 2}), __half2{0.5, 0.5})) &&
    result[0];
}

__global__ void kernel_hisnan(__half* input, int* output) {
  int tx = threadIdx.x;
  output[tx] = __hisnan(input[tx]);
}

__global__ void kernel_hisinf(__half* input, int* output) {
  int tx = threadIdx.x;
  output[tx] = __hisinf(input[tx]);
}

#endif

__half host_ushort_as_half(unsigned short s) {
  union {__half h; unsigned short s; } converter;
  converter.s = s;
  return converter.h;
}

void check_hisnan(int NUM_INPUTS, __half* inputCPU, __half* inputGPU) {

  // allocate memory
  auto memsize = NUM_INPUTS * sizeof(int);
  int* outputGPU = nullptr;
  hipMalloc((void**)&outputGPU, memsize);

  // launch the kernel
  hipLaunchKernelGGL(
    kernel_hisnan, dim3(1), dim3(NUM_INPUTS), 0, 0, inputGPU, outputGPU);

  // copy output from device
  int* outputCPU = (int*) malloc(memsize);
  hipMemcpy(outputCPU, outputGPU, memsize, hipMemcpyDeviceToHost);

  // check output
  for (int i=0; i<NUM_INPUTS; i++) {
    if ((2 <= i) && (i <= 5)) { // inputs are nan, output should be true
      if (outputCPU[i] == 0) {
	      failed(
          "__hisnan() returned false for %f (input idx = %d)\n",
          static_cast<float>(inputCPU[i]),
          i);
      }
    }
    else { // inputs are NOT nan, output should be false
      if (outputCPU[i] != 0) {
	      failed(
          "__hisnan() returned true for %f (input idx = %d)\n",
          static_cast<float>(inputCPU[i]),
          i);
      }
    }
  }

  // free memory
  free(outputCPU);
  hipFree(outputGPU);

  // done
  return;
}

void check_hisinf(int NUM_INPUTS, __half* inputCPU, __half* inputGPU) {
  // allocate memory
  auto memsize = NUM_INPUTS * sizeof(int);
  int* outputGPU = nullptr;
  hipMalloc((void**)&outputGPU, memsize);

  // launch the kernel
  hipLaunchKernelGGL(
    kernel_hisinf, dim3(1), dim3(NUM_INPUTS), 0, 0, inputGPU, outputGPU);

  // copy output from device
  int* outputCPU = (int*) malloc(memsize);
  hipMemcpy(outputCPU, outputGPU, memsize, hipMemcpyDeviceToHost);

  // check output
  for (int i=0; i<NUM_INPUTS; i++) {
    if ((0 <= i) && (i <= 1)) { // inputs are inf, output should be true
      if (outputCPU[i] == 0) {
	      failed(
          "__hisinf() returned false for %f (input idx = %d)\n",
          static_cast<float>(inputCPU[i]),
          i);
      }
    }
    else { // inputs are NOT inf, output should be false
      if (outputCPU[i] != 0) {
	      failed(
          "__hisinf() returned true for %f (input idx = %d)\n",
          static_cast<float>(inputCPU[i]),
          i);
      }
    }
  }

  // free memory
  free(outputCPU);
  hipFree(outputGPU);

  // done
  return;
}

void checkFunctional() {

  // allocate memory
  const int NUM_INPUTS = 16;
  auto memsize = NUM_INPUTS * sizeof(__half);
  __half* inputCPU = (__half*) malloc(memsize);

  // populate inputs
  inputCPU[0] = host_ushort_as_half(0x7c00);  //  inf
  inputCPU[1] = host_ushort_as_half(0xfc00);  // -inf
  inputCPU[2] = host_ushort_as_half(0x7c01);  //  nan
  inputCPU[3] = host_ushort_as_half(0x7e00);  //  nan
  inputCPU[4] = host_ushort_as_half(0xfc01);  //  nan
  inputCPU[5] = host_ushort_as_half(0xfe00);  //  nan
  inputCPU[6] = host_ushort_as_half(0x0000);  //  0
  inputCPU[7] = host_ushort_as_half(0x8000);  // -0
  inputCPU[8] = host_ushort_as_half(0x7bff);  // max +ve normal
  inputCPU[9] = host_ushort_as_half(0xfbff);  // max -ve normal
  inputCPU[10] = host_ushort_as_half(0x0400); // min +ve normal
  inputCPU[11] = host_ushort_as_half(0x8400); // min -ve normal
  inputCPU[12] = host_ushort_as_half(0x03ff); // max +ve sub-normal
  inputCPU[13] = host_ushort_as_half(0x83ff); // max -ve sub-normal
  inputCPU[14] = host_ushort_as_half(0x0001); // min +ve sub-normal
  inputCPU[15] = host_ushort_as_half(0x8001); // min -ve sub-normal

  // copy inputs to the GPU
  __half* inputGPU = nullptr;
  hipMalloc((void**)&inputGPU, memsize);
  hipMemcpy(inputGPU, inputCPU, memsize, hipMemcpyHostToDevice);

  // run checks

  check_hisnan(NUM_INPUTS, inputCPU, inputGPU);

  check_hisinf(NUM_INPUTS, inputCPU, inputGPU);

  // free memory
  hipFree(inputGPU);
  free(inputCPU);

  // all done
  return;
}

int main() {
  bool* result{nullptr};
  hipHostMalloc(&result, sizeof(result));

  result[0] = false;
  hipLaunchKernelGGL(__halfMath, dim3(1, 1, 1), dim3(1, 1, 1), 0, 0, result);
  hipDeviceSynchronize();

  if (!result[0]) { failed("Failed __half tests."); }

  result[0] = false;
  hipLaunchKernelGGL(__half2Math, dim3(1, 1, 1), dim3(1, 1, 1), 0, 0, result);
  hipDeviceSynchronize();

  if (!result[0]) { failed("Failed __half2 tests."); }

  hipHostFree(result);

  // run some functional checks
  checkFunctional();

  passed();
}
<commit_msg>Missing bits.<commit_after>/*
Copyright (c) 2015-2017 Advanced Micro Devices, Inc. All rights reserved.
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.
*/

/* HIT_START
 * BUILD: %t %s ../test_common.cpp EXCLUDE_HIP_PLATFORM nvcc
 * RUN: %t
 * HIT_END
 */

#include <hip/hip_fp16.h>
#include "hip/hip_runtime.h"

#include "test_common.h"

#if __HIP_ARCH_GFX803__ || __HIP_ARCH_GFX900__ || __HIP_ARCH_GFX906__

__global__
__attribute__((optnone))
void __halfMath(bool* result) {
  __half a{1};

  result[0] = __heq(__hadd(a, __half{1}), __half{2});
  result[0] = __heq(__hadd_sat(a, __half{1}), __half{1}) && result[0];
  result[0] = __heq(__hfma(a, __half{2}, __half{3}), __half{5}) && result[0];
  result[0] =
    __heq(__hfma_sat(a, __half{2}, __half{3}), __half{1}) && result[0];
  result[0] = __heq(__hsub(a, __half{1}), __half{0}) && result[0];
  result[0] = __heq(__hsub_sat(a, __half{2}), __half{0}) && result[0];
  result[0] = __heq(__hmul(a, __half{2}), __half{2}) && result[0];
  result[0] = __heq(__hmul_sat(a, __half{2}), __half{1}) && result[0];
  result[0] = __heq(__hdiv(a, __half{2}), __half{0.5}) && result[0];
}

__device__
bool to_bool(const __half2& x)
{
  auto r = static_cast<const __half2_raw&>(x);

  return r.data.x != 0 && r.data.y != 0;
}

__global__
__attribute__((optnone))
void __half2Math(bool* result) {
  __half2 a{1, 1};

  result[0] = to_bool(__heq2(__hadd2(a, __half2{1, 1}), __half2{2, 2}));
  result[0] = to_bool(__heq2(__hadd2_sat(a, __half2{1, 1}), __half2{1, 1})) &&
    result[0];
  result[0] = to_bool(__heq2(
    __hfma2(a, __half2{2, 2}, __half2{3, 3}), __half2{5, 5})) && result[0];
  result[0] = to_bool(__heq2(
    __hfma2_sat(a, __half2{2, 2}, __half2{3, 3}), __half2{1, 1})) && result[0];
  result[0] = to_bool(__heq2(__hsub2(a, __half2{1, 1}), __half2{0, 0})) &&
    result[0];
  result[0] = to_bool(__heq2(__hsub2_sat(a, __half2{2, 2}), __half2{0, 0})) &&
    result[0];
  result[0] = to_bool(__heq2(__hmul2(a, __half2{2, 2}), __half2{2, 2})) &&
    result[0];
  result[0] = to_bool(__heq2(__hmul2_sat(a, __half2{2, 2}), __half2{1, 1})) &&
    result[0];
  result[0] = to_bool(__heq2(__h2div(a, __half2{2, 2}), __half2{0.5, 0.5})) &&
    result[0];
}

__global__ void kernel_hisnan(__half* input, int* output) {
  int tx = threadIdx.x;
  output[tx] = __hisnan(input[tx]);
}

__global__ void kernel_hisinf(__half* input, int* output) {
  int tx = threadIdx.x;
  output[tx] = __hisinf(input[tx]);
}

#endif

__half host_ushort_as_half(unsigned short s) {
  union {__half h; unsigned short s; } converter;
  converter.s = s;
  return converter.h;
}

void check_hisnan(int NUM_INPUTS, __half* inputCPU, __half* inputGPU) {

  // allocate memory
  auto memsize = NUM_INPUTS * sizeof(int);
  int* outputGPU = nullptr;
  hipMalloc((void**)&outputGPU, memsize);

  // launch the kernel
  hipLaunchKernelGGL(
    kernel_hisnan, dim3(1), dim3(NUM_INPUTS), 0, 0, inputGPU, outputGPU);

  // copy output from device
  int* outputCPU = (int*) malloc(memsize);
  hipMemcpy(outputCPU, outputGPU, memsize, hipMemcpyDeviceToHost);

  // check output
  for (int i=0; i<NUM_INPUTS; i++) {
    if ((2 <= i) && (i <= 5)) { // inputs are nan, output should be true
      if (outputCPU[i] == 0) {
	      failed(
          "__hisnan() returned false for %f (input idx = %d)\n",
          static_cast<float>(inputCPU[i]),
          i);
      }
    }
    else { // inputs are NOT nan, output should be false
      if (outputCPU[i] != 0) {
	      failed(
          "__hisnan() returned true for %f (input idx = %d)\n",
          static_cast<float>(inputCPU[i]),
          i);
      }
    }
  }

  // free memory
  free(outputCPU);
  hipFree(outputGPU);

  // done
  return;
}

void check_hisinf(int NUM_INPUTS, __half* inputCPU, __half* inputGPU) {
  // allocate memory
  auto memsize = NUM_INPUTS * sizeof(int);
  int* outputGPU = nullptr;
  hipMalloc((void**)&outputGPU, memsize);

  // launch the kernel
  hipLaunchKernelGGL(
    kernel_hisinf, dim3(1), dim3(NUM_INPUTS), 0, 0, inputGPU, outputGPU);

  // copy output from device
  int* outputCPU = (int*) malloc(memsize);
  hipMemcpy(outputCPU, outputGPU, memsize, hipMemcpyDeviceToHost);

  // check output
  for (int i=0; i<NUM_INPUTS; i++) {
    if ((0 <= i) && (i <= 1)) { // inputs are inf, output should be true
      if (outputCPU[i] == 0) {
	      failed(
          "__hisinf() returned false for %f (input idx = %d)\n",
          static_cast<float>(inputCPU[i]),
          i);
      }
    }
    else { // inputs are NOT inf, output should be false
      if (outputCPU[i] != 0) {
	      failed(
          "__hisinf() returned true for %f (input idx = %d)\n",
          static_cast<float>(inputCPU[i]),
          i);
      }
    }
  }

  // free memory
  free(outputCPU);
  hipFree(outputGPU);

  // done
  return;
}

void checkFunctional() {

  // allocate memory
  const int NUM_INPUTS = 16;
  auto memsize = NUM_INPUTS * sizeof(__half);
  __half* inputCPU = (__half*) malloc(memsize);

  // populate inputs
  inputCPU[0] = host_ushort_as_half(0x7c00);  //  inf
  inputCPU[1] = host_ushort_as_half(0xfc00);  // -inf
  inputCPU[2] = host_ushort_as_half(0x7c01);  //  nan
  inputCPU[3] = host_ushort_as_half(0x7e00);  //  nan
  inputCPU[4] = host_ushort_as_half(0xfc01);  //  nan
  inputCPU[5] = host_ushort_as_half(0xfe00);  //  nan
  inputCPU[6] = host_ushort_as_half(0x0000);  //  0
  inputCPU[7] = host_ushort_as_half(0x8000);  // -0
  inputCPU[8] = host_ushort_as_half(0x7bff);  // max +ve normal
  inputCPU[9] = host_ushort_as_half(0xfbff);  // max -ve normal
  inputCPU[10] = host_ushort_as_half(0x0400); // min +ve normal
  inputCPU[11] = host_ushort_as_half(0x8400); // min -ve normal
  inputCPU[12] = host_ushort_as_half(0x03ff); // max +ve sub-normal
  inputCPU[13] = host_ushort_as_half(0x83ff); // max -ve sub-normal
  inputCPU[14] = host_ushort_as_half(0x0001); // min +ve sub-normal
  inputCPU[15] = host_ushort_as_half(0x8001); // min -ve sub-normal

  // copy inputs to the GPU
  __half* inputGPU = nullptr;
  hipMalloc((void**)&inputGPU, memsize);
  hipMemcpy(inputGPU, inputCPU, memsize, hipMemcpyHostToDevice);

  // run checks

  check_hisnan(NUM_INPUTS, inputCPU, inputGPU);

  check_hisinf(NUM_INPUTS, inputCPU, inputGPU);

  // free memory
  hipFree(inputGPU);
  free(inputCPU);

  // all done
  return;
}

int main() {
  bool* result{nullptr};
  hipHostMalloc(&result, sizeof(result));

  result[0] = false;
  hipLaunchKernelGGL(__halfMath, dim3(1, 1, 1), dim3(1, 1, 1), 0, 0, result);
  hipDeviceSynchronize();

  if (!result[0]) { failed("Failed __half tests."); }

  result[0] = false;
  hipLaunchKernelGGL(__half2Math, dim3(1, 1, 1), dim3(1, 1, 1), 0, 0, result);
  hipDeviceSynchronize();

  if (!result[0]) { failed("Failed __half2 tests."); }

  hipHostFree(result);

  // run some functional checks
  checkFunctional();

  passed();
}
<|endoftext|>


<commit_before>//  SMESH SMESH : implementaion of SMESH idl descriptions
//
//  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
//  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License.
//
//  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
//
//  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
//
//
//
//  File   : SMESH_Hexa_3D.hxx
//  Author : Paul RASCLE, EDF
//  Module : SMESH
//  $Header$

#ifndef _SMESH_HEXA_3D_HXX_
#define _SMESH_HEXA_3D_HXX_

#include "SMESH_3D_Algo.hxx"
#include "SMESH_Mesh.hxx"
#include "SMESH_Quadrangle_2D.hxx"
#include "Utils_SALOME_Exception.hxx"

typedef struct point3Dstruct
{
  int nodeId;
} Point3DStruct;

typedef double Pt3[3];

typedef struct conv2dstruct
{
  double a1; // X = a1*x + b1*y + c1
  double b1; // Y = a2*x + b2*y + c2
  double c1; // a1, b1 a2, b2 in {-1,0,1}
  double a2; // c1, c2 in {0,1}
  double b2;
  double c2;
  int ia;    // I = ia*i + ib*j + ic
  int ib;
  int ic;
  int ja;    // J = ja*i + jb*j + jc
  int jb;
  int jc;
} Conv2DStruct;

typedef struct cubeStruct
{
  TopoDS_Vertex V000;
  TopoDS_Vertex V001;
  TopoDS_Vertex V010;
  TopoDS_Vertex V011;
  TopoDS_Vertex V100;
  TopoDS_Vertex V101;
  TopoDS_Vertex V110;
  TopoDS_Vertex V111;
  faceQuadStruct* quad_X0;
  faceQuadStruct* quad_X1;
  faceQuadStruct* quad_Y0;
  faceQuadStruct* quad_Y1;
  faceQuadStruct* quad_Z0;
  faceQuadStruct* quad_Z1;
  Point3DStruct* np; // normalised 3D coordinates
} CubeStruct;

class SMESH_Hexa_3D:
  public SMESH_3D_Algo
{
public:
  SMESH_Hexa_3D(int hypId, int studyId, SMESH_Gen* gen);
  virtual ~SMESH_Hexa_3D();

  virtual bool CheckHypothesis(SMESH_Mesh& aMesh,
			       const TopoDS_Shape& aShape);

  virtual bool Compute(SMESH_Mesh& aMesh,
		       const TopoDS_Shape& aShape)
    throw (SALOME_Exception);

  ostream & SaveTo(ostream & save);
  istream & LoadFrom(istream & load);
  friend ostream & operator << (ostream & save, SMESH_Hexa_3D & hyp);
  friend istream & operator >> (istream & load, SMESH_Hexa_3D & hyp);

protected:
  TopoDS_Edge
  EdgeNotInFace(SMESH_Mesh& aMesh,
		const TopoDS_Shape& aShape,
		const TopoDS_Face& aFace,
		const TopoDS_Vertex& aVertex,
		const TopTools_IndexedDataMapOfShapeListOfShape& MS);

  int GetFaceIndex(SMESH_Mesh& aMesh,
		   const TopoDS_Shape& aShape,
		   const vector<SMESH_subMesh*>& meshFaces,
		   const TopoDS_Vertex& V0,
		   const TopoDS_Vertex& V1,
		   const TopoDS_Vertex& V2,
		   const TopoDS_Vertex& V3);

  void GetConv2DCoefs(const faceQuadStruct& quad,
		      const TopoDS_Shape& aShape,
		      const TopoDS_Vertex& V0,
		      const TopoDS_Vertex& V1,
		      const TopoDS_Vertex& V2,
		      const TopoDS_Vertex& V3,
		      Conv2DStruct& conv);

  void GetPoint(Pt3 p,
		int i, int j, int k,
		int nbx, int nby, int nbz,
		Point3DStruct *np,
		const Handle(SMESHDS_Mesh)& meshDS);

  CubeStruct _cube;
  FaceQuadStruct* _quads[6];
  int _indX0;
  int _indX1;
  int _indY0;
  int _indY1;
  int _indZ0;
  int _indZ1;
};

#endif
<commit_msg>Update to match the change of SMDS (new DS).<commit_after>//  SMESH SMESH : implementaion of SMESH idl descriptions
//
//  Copyright (C) 2003  OPEN CASCADE, EADS/CCR, LIP6, CEA/DEN,
//  CEDRAT, EDF R&D, LEG, PRINCIPIA R&D, BUREAU VERITAS
//
//  This library is free software; you can redistribute it and/or
//  modify it under the terms of the GNU Lesser General Public
//  License as published by the Free Software Foundation; either
//  version 2.1 of the License.
//
//  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
//
//  See http://www.opencascade.org/SALOME/ or email : webmaster.salome@opencascade.org
//
//
//
//  File   : SMESH_Hexa_3D.hxx
//  Author : Paul RASCLE, EDF
//  Module : SMESH
//  $Header$

#ifndef _SMESH_HEXA_3D_HXX_
#define _SMESH_HEXA_3D_HXX_

#include "SMESH_3D_Algo.hxx"
#include "SMESH_Mesh.hxx"
#include "SMESH_Quadrangle_2D.hxx"
#include "Utils_SALOME_Exception.hxx"

typedef struct point3Dstruct
{
  int nodeId;
} Point3DStruct;

typedef double Pt3[3];

typedef struct conv2dstruct
{
  double a1; // X = a1*x + b1*y + c1
  double b1; // Y = a2*x + b2*y + c2
  double c1; // a1, b1 a2, b2 in {-1,0,1}
  double a2; // c1, c2 in {0,1}
  double b2;
  double c2;
  int ia;    // I = ia*i + ib*j + ic
  int ib;
  int ic;
  int ja;    // J = ja*i + jb*j + jc
  int jb;
  int jc;
} Conv2DStruct;

typedef struct cubeStruct
{
  TopoDS_Vertex V000;
  TopoDS_Vertex V001;
  TopoDS_Vertex V010;
  TopoDS_Vertex V011;
  TopoDS_Vertex V100;
  TopoDS_Vertex V101;
  TopoDS_Vertex V110;
  TopoDS_Vertex V111;
  faceQuadStruct* quad_X0;
  faceQuadStruct* quad_X1;
  faceQuadStruct* quad_Y0;
  faceQuadStruct* quad_Y1;
  faceQuadStruct* quad_Z0;
  faceQuadStruct* quad_Z1;
  Point3DStruct* np; // normalised 3D coordinates
} CubeStruct;

class SMESH_Hexa_3D:
  public SMESH_3D_Algo
{
public:
  SMESH_Hexa_3D(int hypId, int studyId, SMESH_Gen* gen);
  virtual ~SMESH_Hexa_3D();

  virtual bool CheckHypothesis(SMESH_Mesh& aMesh,
			       const TopoDS_Shape& aShape);

  virtual bool Compute(SMESH_Mesh& aMesh,
		       const TopoDS_Shape& aShape)
    throw (SALOME_Exception);

  ostream & SaveTo(ostream & save);
  istream & LoadFrom(istream & load);
  friend ostream & operator << (ostream & save, SMESH_Hexa_3D & hyp);
  friend istream & operator >> (istream & load, SMESH_Hexa_3D & hyp);

protected:
  TopoDS_Edge
  EdgeNotInFace(SMESH_Mesh& aMesh,
		const TopoDS_Shape& aShape,
		const TopoDS_Face& aFace,
		const TopoDS_Vertex& aVertex,
		const TopTools_IndexedDataMapOfShapeListOfShape& MS);

  int GetFaceIndex(SMESH_Mesh& aMesh,
		   const TopoDS_Shape& aShape,
		   const vector<SMESH_subMesh*>& meshFaces,
		   const TopoDS_Vertex& V0,
		   const TopoDS_Vertex& V1,
		   const TopoDS_Vertex& V2,
		   const TopoDS_Vertex& V3);

  void GetConv2DCoefs(const faceQuadStruct& quad,
		      const TopoDS_Shape& aShape,
		      const TopoDS_Vertex& V0,
		      const TopoDS_Vertex& V1,
		      const TopoDS_Vertex& V2,
		      const TopoDS_Vertex& V3,
		      Conv2DStruct& conv);

  void GetPoint(Pt3 p,
		int i, int j, int k,
		int nbx, int nby, int nbz,
		Point3DStruct *np,
		const SMESHDS_Mesh* meshDS);

  CubeStruct _cube;
  FaceQuadStruct* _quads[6];
  int _indX0;
  int _indX1;
  int _indY0;
  int _indY1;
  int _indZ0;
  int _indZ1;
};

#endif
<|endoftext|>