<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_corequad_init.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file  p9_pm_corequad_init.C
/// @brief Establish safe settings for Core and Quad.
///
// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com>
// *HWP Team: PM
// *HWP Level: 1
// *HWP Consumed by: HS

// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include <p9_pm_corequad_init.H>

// -----------------------------------------------------------------------------
// Function prototypes
// -----------------------------------------------------------------------------

// Reset function
///
/// @brief Stop the CMEs and clear the CME FIRs, PPM Errors and their masks
///        for all functional and enabled EX chiplets
///
/// @param[in] i_target Proc Chip target
///
/// @return FAPI2_RC_SUCCESS on success or error return code
///
fapi2::ReturnCode pm_corequad_reset(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);

// Init function
///
/// @brief Setup the CME and PPM Core & Quad for all functional and enabled
///        EX chiplets
///
/// @param[in] i_target Proc Chip target
///
/// @return FAPI2_RC_SUCCESS on success or error return code
///
fapi2::ReturnCode pm_corequad_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);

// ----------------------------------------------------------------------
// Function definitions
// ----------------------------------------------------------------------

fapi2::ReturnCode p9_pm_corequad_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const p9pm::PM_FLOW_MODE i_mode)
{
    FAPI_IMP("Entering p9_pm_corequad_init...");

    FAPI_IMP("Exiting p9_pm_corequad_init...");
    return fapi2::current_err;
}

fapi2::ReturnCode pm_corequad_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    FAPI_IMP("Entering pm_corequad_init...");

    return fapi2::current_err;
}

fapi2::ReturnCode pm_corequad_reset(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    FAPI_IMP("Entering pm_corequad_reset...");

    return fapi2::current_err;
}
<commit_msg>p9_pm_corequad_init: Level 2 - Fapi 1.0 to Fapi 2.0 transliteration<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_corequad_init.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2016,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file  p9_pm_corequad_init.C
/// @brief Establish safe settings for Core and Quad.
///
// *HWP HWP Owner: Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner: Sangeetha T S <sangeet2@in.ibm.com>
// *HWP Team: PM
// *HWP Level: 2
// *HWP Consumed by: HS

/// @verbatim
/// High-level procedure flow:
///
///  Procedure Prereq:
///  - completed istep procedure
///  - completed multicast setup
///
///  if PM_INIT
///  {
///    loop over all valid chiplets (EX, EQ and Core)
///    {
///      Clear the Doorbells to remove latent values
///      Setup static Core PM mode register bits
///      Setup static Quad PM mode register bits
///      Setup CME SCRAM scrub index
///      Clear CME flags and scratch registers
///      Restore CME FIR mask value from HWP attribute
///      Restore PPM Error mask value from HWP attribute
///    }
///  }
///  else if PM_RESET
///  {
///    loop over all valid chiplets (EX, EQ and Core)
///    {
///      Save the CME FIR mask value to HWP attribute and clear the register
///      Save the PPM Error mask value to HWP attribute and clear the register
///      Stop the CME 0 & 1
///      Disable OCC Heartbeat
///      Allow access to the PPM
///      Disable resonant clocks
///      Disable IVRM
///      Clear PPM Errors
///      Clear CME FIRs
///    }
///  }
///
/// @endverbatim

// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include <p9_pm_corequad_init.H>

// -----------------------------------------------------------------------------
// Constant definitions
// -----------------------------------------------------------------------------

const uint64_t CME_DOORBELL_CLEAR[4] = {C_CPPM_CMEDB0_CLEAR,
                                        C_CPPM_CMEDB1_CLEAR,
                                        C_CPPM_CMEDB2_CLEAR,
                                        C_CPPM_CMEDB3_CLEAR
                                       };

const uint8_t DOORBELLS_COUNT = 4;

// -----------------------------------------------------------------------------
// Function prototypes
// -----------------------------------------------------------------------------

// Reset function
///
/// @brief Stop the CMEs and clear the CME FIRs, PPM Errors and their masks
///        for all functional and enabled EX chiplets
///
/// @param[in] i_target Proc Chip target
/// @param[in] i_cmeFirMask  Mask value for CME FIR
/// @param[in] i_cppmErrMask Mask value for Core PPM Error
/// @param[in] i_qppmErrMask Mask value for Quad PPM Error
///
/// @return FAPI2_RC_SUCCESS on success or error return code
///
fapi2::ReturnCode pm_corequad_reset(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint32_t i_cmeFirMask,
    const uint32_t i_cppmErrMask,
    const uint32_t i_qppmErrMask);

// Init function
///
/// @brief Setup the CME and PPM Core & Quad for all functional and enabled
///        EX chiplets
///
/// @param[in] i_target Proc Chip target
///
/// @return FAPI2_RC_SUCCESS on success or error return code
///
fapi2::ReturnCode pm_corequad_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);

// ----------------------------------------------------------------------
// Function definitions
// ----------------------------------------------------------------------

fapi2::ReturnCode p9_pm_corequad_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const p9pm::PM_FLOW_MODE i_mode,
    const uint32_t i_cmeFirMask,
    const uint32_t i_cppmErrMask,
    const uint32_t i_qppmErrMask)
{
    FAPI_IMP("Entering p9_pm_corequad_init...");

    if (i_mode == p9pm::PM_INIT)
    {
        FAPI_TRY(pm_corequad_init(i_target),
                 "ERROR: Failed to initialize the core quad");
    }
    else if (i_mode == p9pm::PM_RESET)
    {
        FAPI_TRY(pm_corequad_reset(i_target, i_cmeFirMask, i_cppmErrMask,
                                   i_qppmErrMask),
                 "ERROR: Failed to reset core quad");
    }
    else
    {
        FAPI_ASSERT(false,
                    fapi2::PM_COREQUAD_BAD_MODE().set_BADMODE(i_mode),
                    "Unknown mode 0x%X passed to p9_pm_corequad_init", i_mode);
    }

fapi_try_exit:
    FAPI_IMP("Exiting p9_pm_corequad_init...");
    return fapi2::current_err;
}

fapi2::ReturnCode pm_corequad_init(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target)
{
    FAPI_IMP("Entering pm_corequad_init...");

    fapi2::buffer<uint64_t> l_data64;
    uint8_t l_chpltNumber = 0;
    uint64_t l_address = 0;
    uint32_t l_errMask = 0;
    uint32_t l_firMask = 0;

    auto l_eqChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EQ>
                        (fapi2::TARGET_STATE_FUNCTIONAL);

    FAPI_DBG("Number of quad chiplets retrieved = %u", l_eqChiplets.size());

    // For each functional EQ chiplet
    for (auto l_quad_chplt : l_eqChiplets)
    {

        // Fetch the position of the EQ target
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_quad_chplt,
                               l_chpltNumber),
                 "ERROR: Failed to get the position of the Quad:0x%08X",
                 l_quad_chplt);
        FAPI_DBG("Quad number = %d", l_chpltNumber);

        // Setup the Quad PPM Mode Register
        // Clear the following bits:
        // 0          : Force FSAFE
        // 1  - 11    : FSAFE
        // 12         : Enable FSAFE on heartbeat loss
        // 13         : Enable DROOP protect upon heartbeat loss
        // 14         : Enable PFETs upon iVRMs dropout
        // 18 - 19    : PCB interrupt
        // 20,22,24,26: CME InterPPM Communication
        FAPI_INF("Setup Quad PPM Mode register");
        l_data64.flush<0>().setBit<0, 15>().setBit<18, 3>().setBit<22>().
        setBit<24>().setBit<26>();
        l_address = EQ_QPPM_QPMMR_CLEAR;
        FAPI_TRY(fapi2::putScom(l_quad_chplt, l_address, l_data64),
                 "ERROR: Failed to setup Quad PMM register");

        // Restore Quad PPM Error Mask
        FAPI_INF("Restore QUAD PPM Error Mask");
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_QUAD_PPM_ERRMASK, l_quad_chplt,
                               l_errMask),
                 "ERROR: Failed to get CORE PPM error Mask");
        l_data64.flush<0>().insertFromRight<0, 32>(l_errMask);
        l_address = EQ_QPPM_ERRMSK;
        FAPI_TRY(fapi2::putScom(l_quad_chplt, l_address, l_data64),
                 "ERROR: Failed to restore the QUAD PPM Error Mask");

        // Clear CME Flags
        FAPI_INF("Clear CME Flags");
        l_data64.flush<1>();
        l_address = EQ_CME_SCOM_FLAGS_CLEAR;
        FAPI_TRY(fapi2::putScom(l_quad_chplt, l_address, l_data64),
                 "ERROR: Failed to reset CME Flags");

        auto l_exChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EX>
                            (fapi2::TARGET_STATE_FUNCTIONAL);

        // For each functional EX chiplet
        for (auto l_ex_chplt : l_exChiplets)
        {

            // Fetch the position of the EX target
            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_ex_chplt,
                                   l_chpltNumber),
                     "ERROR: Failed to get the position of the EX:0x%08X",
                     l_ex_chplt);
            FAPI_DBG("EX number = %d", l_chpltNumber);

            // Setup / Clear CME SRAM Scrub
            // Set bit 1         : SRAM SCRUB enable
            // Clear bits 47 - 59: SRAM SCRUB index
            FAPI_INF("Setup CME SRAM SCRUB");
            l_data64.flush<0>().setBit<1>();
            l_address = EX_CSCR_OR;
            FAPI_TRY(fapi2::putScom(l_ex_chplt, l_address, l_data64),
                     "ERROR: Failed to enable CME SRAM SCRUB");
            l_data64.flush<0>().setBit<47, 13>();
            l_address = EX_CSCR_CLEAR;
            FAPI_TRY(fapi2::putScom(l_ex_chplt, l_address, l_data64),
                     "ERROR: Failed to reset CME SRAM SCRUB INDEX");

            // Clear CME Scratch registers
            FAPI_INF("Clear CME Scratch registers");
            l_data64.flush<0>();
            l_address = EX_CME_SCOM_SRTCH0_SCOM;
            FAPI_TRY(fapi2::putScom(l_ex_chplt, l_address, l_data64),
                     "ERROR: Failed to clear CME scratch register 0");
            l_address = EX_CME_SCOM_SRTCH1_SCOM;
            FAPI_TRY(fapi2::putScom(l_ex_chplt, l_address, l_data64),
                     "ERROR: Failed to clear CME scratch register 1");

            // Restore Local CME FIR Mask
            FAPI_INF("Restore local CME FIR Mask");
            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CME_LOCAL_FIRMASK, l_ex_chplt,
                                   l_firMask),
                     "ERROR: Failed to get local FIR Mask");
            l_data64.flush<0>().insertFromRight<0, 32>(l_firMask);
            l_address = EX_CME_SCOM_LFIRMASK_OR;
            FAPI_TRY(fapi2::putScom(l_ex_chplt, l_address, l_data64),
                     "ERROR: Failed to restore the CME Local FIR");

            auto l_coreChiplets =
                l_ex_chplt.getChildren<fapi2::TARGET_TYPE_CORE>
                (fapi2::TARGET_STATE_FUNCTIONAL);

            // For each core target
            for (auto l_core_chplt : l_coreChiplets)
            {
                // Fetch the position of the Core target
                FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_core_chplt,
                                       l_chpltNumber),
                         "ERROR: Failed to get the position of the CORE:0x%08X",
                         l_core_chplt);
                FAPI_DBG("CORE number = %d", l_chpltNumber);

                // Clear the Core CME DoorBells
                FAPI_INF("Clear the Core PPM CME Doorbells");
                l_data64.flush<1>();

                for (uint8_t l_dbLoop = 0; l_dbLoop < DOORBELLS_COUNT; l_dbLoop++)
                {
                    l_address = CME_DOORBELL_CLEAR[l_dbLoop];
                    FAPI_TRY(fapi2::putScom(l_core_chplt, l_address, l_data64),
                             "ERROR: Failed to clear the doorbells");
                }

                // Setup Core PPM Mode register
                // Clear the following bits:
                // 0 - 1  : PPM Write control
                // 10     : Stop Exit interrupt type
                // 11     : Block interrupts
                // 12     : PPM response for CME error
                // 14 - 15: wakeup interrupts
                // Set the following bit:
                // 13 : Wakeup notification
                FAPI_INF("Setup Core PPM Mode register");
                l_data64.flush<0>().setBit<0, 2>().setBit<10, 3>().
                setBit<14, 2>();
                l_address =  C_CPPM_CPMMR_CLEAR;
                FAPI_TRY(fapi2::putScom(l_core_chplt, l_address, l_data64),
                         "ERROR: Failed to setup Core PMM register");

                l_data64.flush<0>().setBit<13>();
                l_address = C_CPPM_CPMMR_OR;
                FAPI_TRY(fapi2::putScom(l_core_chplt, l_address, l_data64),
                         "ERROR: Failed to setup Core PMM register");

                // Restore CORE PPM Error Mask
                FAPI_INF("Restore CORE PPM Error Mask");
                FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CORE_PPM_ERRMASK, l_core_chplt,
                                       l_errMask),
                         "ERROR: Failed to get CORE PPM error Mask");
                l_data64.flush<0>().insertFromRight<0, 32>(l_errMask);
                l_address = C_CPPM_ERRMSK;
                FAPI_TRY(fapi2::putScom(l_core_chplt, l_address, l_data64),
                         "ERROR: Failed to restore the CORE PPM Error Mask");
            }
        }
    }

fapi_try_exit:
    return fapi2::current_err;
}

fapi2::ReturnCode pm_corequad_reset(
    const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target,
    const uint32_t i_cmeFirMask,
    const uint32_t i_cppmErrMask,
    const uint32_t i_qppmErrMask)
{
    FAPI_IMP("Entering pm_corequad_reset...");

    fapi2::buffer<uint64_t> l_data64;
    uint8_t l_chpltNumber = 0;
    uint64_t l_address = 0;
    uint32_t l_errMask = 0;
    uint32_t l_firMask = 0;
    uint32_t l_pollCount = 20;

    auto l_eqChiplets = i_target.getChildren<fapi2::TARGET_TYPE_EQ>
                        (fapi2::TARGET_STATE_FUNCTIONAL);

    FAPI_DBG("Number of quad chiplets retrieved = %u", l_eqChiplets.size());

    // For each functional EQ chiplet
    for (auto l_quad_chplt : l_eqChiplets)
    {
        // Fetch the position of the EQ target
        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_quad_chplt,
                               l_chpltNumber),
                 "ERROR: Failed to get the position of the Quad:0x%08X",
                 l_quad_chplt);
        FAPI_DBG("Quad number = %d", l_chpltNumber);

        // Store QUAD Error Mask in an attribute
        FAPI_INF("Store QUAD PPM ERROR MASK in HWP attribute");
        l_address = EQ_QPPM_ERRMSK;
        FAPI_TRY(fapi2::getScom(l_quad_chplt, l_address, l_data64),
                 "ERROR: Failed to fetch the QUAD PPM Error Mask");
        l_data64.extractToRight<uint32_t>(l_errMask, 0, 32);
        FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_QUAD_PPM_ERRMASK, l_quad_chplt,
                               l_errMask),
                 "ERROR: Failed to set QUAD PPM error Mask");

        // Write parameter provided value to Quad Error mask
        FAPI_INF("Write QUAD PPM ERROR MASK");
        l_data64.flush<0>().insertFromRight<0, 32>(i_qppmErrMask);
        FAPI_TRY(fapi2::putScom(l_quad_chplt, l_address, l_data64),
                 "ERROR: Failed to write the QUAD PPM Error Mask");

        // Disable OCC Heartbeat
        // Clear the bit 16 : OCC_HEARTBEAT_ENABLE
        FAPI_INF("Disable OCC HeartBeat register");
        l_address = EQ_QPPM_OCCHB;
        FAPI_TRY(fapi2::getScom(l_quad_chplt, l_address, l_data64),
                 "ERROR: Failed to fetch OCC HeartBeat register");
        l_data64.clearBit<16>();
        FAPI_TRY(fapi2::putScom(l_quad_chplt, l_address, l_data64),
                 "ERROR: Failed to disable OCC HeartBeat register");

        // Clear Quad PPM Errors
        FAPI_INF("Clear QUAD PPM ERROR Register");
        l_address = EQ_QPPM_ERR;
        FAPI_TRY(fapi2::putScom(l_quad_chplt, l_address, l_data64),
                 "ERROR: Failed to clear QUAD PPM ERROR");

        auto l_exChiplets = l_quad_chplt.getChildren<fapi2::TARGET_TYPE_EX>
                            (fapi2::TARGET_STATE_FUNCTIONAL);

        // For each EX target
        for (auto l_ex_chplt : l_exChiplets)
        {
            // Fetch the position of the EX target
            FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_ex_chplt,
                                   l_chpltNumber),
                     "ERROR: Failed to get the position of the EX:0x%08X",
                     l_ex_chplt);
            FAPI_DBG("EX number = %d", l_chpltNumber);

            // Store CME FIR MASK in an attribute
            FAPI_INF("Store CME FIR MASK HWP attribute");
            l_address = EX_CME_SCOM_LFIRMASK;
            FAPI_TRY(fapi2::getScom(l_ex_chplt, l_address, l_data64),
                     "ERROR: Failed to fetch the QUAD PPM Error Mask");
            l_data64.extractToRight<uint32_t>(l_firMask, 0, 32);
            FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_CME_LOCAL_FIRMASK, l_ex_chplt,
                                   l_firMask),
                     "ERROR: Failed to set CME FIR Mask");

            // Write parameter provided value to CME FIR MASK
            FAPI_INF(" Write Local CME FIR MASK ");
            l_data64.flush<0>().insertFromRight<0, 32>(i_cmeFirMask);
            l_address = EX_CME_SCOM_LFIRMASK_OR;
            FAPI_TRY(fapi2::putScom(l_ex_chplt, l_address, l_data64),
                     "ERROR: Failed to clear the Local CME FIR Mask");

            // Program XCR to HALT CME 0 & 1 and verify by polling the XSR
            // Set the value of bits as follows:
            // bits (1,2,3) = 001 : halt state
            //
            // NOTE: This will be removed once the PPE common class that does this
            //       functionality is available.
            //       Ex, ppe<PPE_TYPE_CME> cme;
            //           cme.hard_reset();
            FAPI_INF("Stop CME0 and CME1");
            l_data64.flush<0>().insertFromRight(p9hcd::HALT, 1, 3);
            l_address = EX_PPE_XIXCR;
            FAPI_TRY(fapi2::putScom(l_ex_chplt, l_address, l_data64),
                     "ERROR: Failed to stop the CMEs");

            do
            {
                FAPI_INF("Polling the CME Status");
                l_address = EX_PPE_XIRAMDBG;
                FAPI_TRY(fapi2::getScom(l_ex_chplt, l_address, l_data64),
                         "ERROR: Failed to read CME status");
                fapi2::delay(1000, 0); // poll after a delay of 1us
            }
            while((l_data64.getBit<p9hcd::HALTED_STATE>() != 1) &&
                  (--l_pollCount != 0));

            FAPI_ASSERT((l_pollCount != 0),
                        fapi2::PM_CME_ACTIVE_ERROR().set_CMESTATUS(l_data64),
                        "ERROR: Failed to stop the CME");

            // Clear CME LFIRs
            FAPI_INF("Clear CME FIR Register");
            l_data64.flush<0>();
            l_address = EX_CME_SCOM_LFIR_AND;
            FAPI_TRY(fapi2::putScom(l_ex_chplt, l_address, l_data64),
                     "ERROR: Failed to clear CME FIR");

            auto l_coreChiplets =
                l_ex_chplt.getChildren<fapi2::TARGET_TYPE_CORE>
                (fapi2::TARGET_STATE_FUNCTIONAL);

            // For each core target
            for (auto l_core_chplt : l_coreChiplets)
            {
                // Fetch the position of the Core target
                FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, l_core_chplt,
                                       l_chpltNumber),
                         "ERROR: Failed to get the position of the CORE:0x%08X",
                         l_core_chplt);
                FAPI_DBG("CORE number = %d", l_chpltNumber);

                // Write CPPM Error mask into attribute
                FAPI_INF("Store CORE PPM ERROR MASK in HWP attribute");
                l_address = C_CPPM_ERRMSK;
                FAPI_TRY(fapi2::getScom(l_core_chplt, l_address, l_data64),
                         "ERROR: Failed to fetch the CORE PPM Error Mask");
                l_data64.extractToRight<uint32_t>(l_errMask, 0, 32);
                FAPI_TRY(FAPI_ATTR_SET(fapi2::ATTR_CORE_PPM_ERRMASK, l_core_chplt,
                                       l_errMask),
                         "ERROR: Failed to set CORE PPM error Mask");

                // Set parameter provided value to Core PPM ERROR MASK
                FAPI_INF(" Write CORE PPM ERROR MASK ");
                l_data64.flush<0>().insertFromRight<0, 32>(i_cppmErrMask);
                FAPI_TRY(fapi2::putScom(l_core_chplt, l_address, l_data64),
                         "ERROR: Failed to write to CORE PPM Error Mask");

                // Allow PCB Access
                // Set bit 0 : PPM_WRITE_DISABLE
                FAPI_INF("Allow PCB access to PPM");
                l_address = C_CPPM_CPMMR;
                FAPI_TRY(fapi2::getScom(l_core_chplt, l_address, l_data64));
                l_data64.setBit<0>();
                l_address =  C_CPPM_CPMMR_CLEAR;
                FAPI_TRY(fapi2::putScom(l_core_chplt, l_address, l_data64),
                         "ERROR: Failed to allow PCB access to PPM");

                // Clear Core PPM Errors
                l_data64.flush<0>();
                FAPI_INF("Clear CORE PPM ERROR Register");
                l_address = C_CPPM_ERR;
                FAPI_TRY(fapi2::putScom(l_core_chplt, l_address, l_data64),
                         "ERROR: Failed to clear CORE PPM ERROR");
            }
        }
    }

    //TODO: RTC 149078: Disable Resonant Clocks
    //TODO: RTC 149079: Disable IVRM

fapi_try_exit:
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>c12808d4-4b02-11e5-ac25-28cfe9171a43<commit_msg>roselyn broke it<commit_after>c13572f8-4b02-11e5-b177-28cfe9171a43<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: graphic.hxx,v $
 *
 *  $Revision: 1.3 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 03:10:45 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _GOODIES_GRAPHIC_HXX
#define _GOODIES_GRAPHIC_HXX

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_GRAPHIC_XGRAPHIC_HPP_
#include <com/sun/star/graphic/XGraphic.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif

#include "descriptor.hxx"

using namespace com::sun::star;

class Graphic;

namespace unographic {

// -------------------
// - GraphicProvider -
// -------------------

class Graphic : public ::com::sun::star::graphic::XGraphic,
                public ::com::sun::star::lang::XUnoTunnel,
                public ::unographic::GraphicDescriptor
{
public:

    Graphic();
    ~Graphic() throw();

    void init( const ::Graphic& rGraphic ) throw();

    static const ::Graphic* getImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw();
    static ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId_Static(  ) throw(::com::sun::star::uno::RuntimeException);
    static ::rtl::OUString getImplementationName_Static() throw();
    static ::com::sun::star::uno::Sequence< ::rtl::OUString >  getSupportedServiceNames_Static() throw();

protected:

    // XInterface
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL acquire() throw();
    virtual void SAL_CALL release() throw();

    // XServiceInfo
    virtual rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
    virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException );

    // XTypeProvider
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw(::com::sun::star::uno::RuntimeException);

    // XGraphic
    virtual ::sal_Int8 SAL_CALL getType(  ) throw (::com::sun::star::uno::RuntimeException);

    // XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rId ) throw(::com::sun::star::uno::RuntimeException);

private:

    ::Graphic* mpGraphic;
};

}

#endif
<commit_msg>INTEGRATION: CWS warnings01 (1.3.28); FILE MERGED 2005/11/16 16:42:25 pl 1.3.28.1: #i55991# removed warnings<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: graphic.hxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-19 21:52:55 $
 *
 *  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
 *
 ************************************************************************/

#ifndef _GOODIES_GRAPHIC_HXX
#define _GOODIES_GRAPHIC_HXX

#ifndef _COM_SUN_STAR_LANG_XSERVICEINFO_HPP_
#include <com/sun/star/lang/XServiceInfo.hpp>
#endif
#ifndef _COM_SUN_STAR_GRAPHIC_XGRAPHIC_HPP_
#include <com/sun/star/graphic/XGraphic.hpp>
#endif
#ifndef _COM_SUN_STAR_LANG_XUNOTUNNEL_HPP_
#include <com/sun/star/lang/XUnoTunnel.hpp>
#endif

#include "descriptor.hxx"

using namespace com::sun::star;

class Graphic;

namespace unographic {

// -------------------
// - GraphicProvider -
// -------------------

class Graphic : public ::com::sun::star::graphic::XGraphic,
                public ::com::sun::star::lang::XUnoTunnel,
                public ::unographic::GraphicDescriptor
{
public:

    Graphic();
    ~Graphic() throw();

    using unographic::GraphicDescriptor::init;
    void init( const ::Graphic& rGraphic ) throw();

    static const ::Graphic* getImplementation( const ::com::sun::star::uno::Reference< ::com::sun::star::uno::XInterface >& rxIFace ) throw();
    static ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId_Static(  ) throw(::com::sun::star::uno::RuntimeException);
    static ::rtl::OUString getImplementationName_Static() throw();
    static ::com::sun::star::uno::Sequence< ::rtl::OUString >  getSupportedServiceNames_Static() throw();

protected:

    // XInterface
    virtual ::com::sun::star::uno::Any SAL_CALL queryAggregation( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Any SAL_CALL queryInterface( const ::com::sun::star::uno::Type & rType ) throw(::com::sun::star::uno::RuntimeException);
    virtual void SAL_CALL acquire() throw();
    virtual void SAL_CALL release() throw();

    // XServiceInfo
    virtual rtl::OUString SAL_CALL getImplementationName() throw( ::com::sun::star::uno::RuntimeException );
    virtual sal_Bool SAL_CALL supportsService( const rtl::OUString& ServiceName ) throw( ::com::sun::star::uno::RuntimeException );
    virtual ::com::sun::star::uno::Sequence< rtl::OUString > SAL_CALL getSupportedServiceNames() throw( ::com::sun::star::uno::RuntimeException );

    // XTypeProvider
    virtual ::com::sun::star::uno::Sequence< ::com::sun::star::uno::Type > SAL_CALL getTypes(  ) throw(::com::sun::star::uno::RuntimeException);
    virtual ::com::sun::star::uno::Sequence< sal_Int8 > SAL_CALL getImplementationId(  ) throw(::com::sun::star::uno::RuntimeException);

    // XGraphic
    virtual ::sal_Int8 SAL_CALL getType(  ) throw (::com::sun::star::uno::RuntimeException);

    // XUnoTunnel
    virtual sal_Int64 SAL_CALL getSomething( const ::com::sun::star::uno::Sequence< sal_Int8 >& rId ) throw(::com::sun::star::uno::RuntimeException);

private:

    ::Graphic* mpGraphic;
};

}

#endif
<|endoftext|>


<commit_before>#include "controller.h"

void port_connect(jack_port_id_t a, jack_port_id_t b, int connect, void *arg) {
    if (!connect) return;
    // See if "dst" port does not begin with sp_client_
    jack_port_t *port_a = jack_port_by_id(client, a);
    jack_port_t *port_b = jack_port_by_id(client, b);
    if (strstr(jack_port_name(port_b), "sp_client_") == jack_port_name(port_b)) {
        return;
    }
    if (!(JackPortIsOutput & jack_port_flags(port_a))) return;
    //printf("Adding to stack a: %s (b: %s)\n", jack_port_name(port_a), jack_port_name(port_b));
    pthread_mutex_lock(&p_queue_mutex);
    p_queue.push_back(port_a);
    pthread_mutex_unlock(&p_queue_mutex);
    pthread_cond_signal(&p_queue_cond);
}

void *connector(void *arg) {
    pthread_mutex_lock(&p_queue_mutex);
    while (1) {
        pthread_cond_wait(&p_queue_cond, &p_queue_mutex);
        while (!p_queue.empty()) {
            jack_port_t *port = p_queue.front();
            p_queue.pop_front();
            pthread_mutex_unlock(&p_queue_mutex);

            const char *port_name = jack_port_name(port);
            //printf("Got a port to connect to: %s\n", port_name);
            pthread_t tmp; pthread_attr_t attr;
			pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

            pthread_create(&tmp, &attr, go_sp, (void*)(port_name));
            sps.insert(pair<const char*, pthread_t>(port_name, tmp));

            pthread_mutex_lock(&p_queue_mutex);
        }
    }
};

void *go_sp(void *port_name_a) {
    // Call SoundPatty on this port
    char *port_name = (char*)port_name_a;

    FILE *fpipe;
    char command[300];
    sprintf(command, "%s %s %s jack \"%s\"", SP_EXEC, SP_CONF, SP_TRES, port_name);
    //printf("Launching %s\n", command);

    char line[256];
    if ( !(fpipe = (FILE*)popen(command,"r")) )
    {  // If fpipe is NULL
        fatal((void*)"Problems with pipe");
    }
	fgets( line, sizeof line, fpipe); pclose(fpipe);
    if (strstr(line, "FOUND") != NULL) {
        // Found... E-mail script output
        char command[300];
        sprintf(command, "%s \"%s\" \"%s\"", SP_OVER, port_name, line);
        system(command);
    }

    fpipe = popen("date \"+%F %T\" | tr -d '\n\'", "r"); // Date without ENDL
    char output[300]; int fd;
    fgets (output, sizeof output, fpipe); pclose(fpipe);

    printf("%s *** %s *** ::: %s", output, port_name, line);
    //printf(fd, output, strlen(output)+1);
    pthread_exit(NULL);
};

int main () {

    pthread_mutex_init(&p_queue_mutex, NULL);
    pthread_cond_init(&p_queue_cond, NULL);
    ostringstream dst_client_str;
    dst_client_str << "sp_manager_" << getpid();
    if ((client = jack_client_new (string(dst_client_str.str()).c_str())) == 0) {
        fatal ((void*)"jack server not running?\n");
    }
    dst_client_str.~ostringstream();

    jack_set_port_connect_callback(client, port_connect, NULL);
    if (jack_activate (client)) { fatal ((void*)"cannot activate client"); }

    pthread_t connector1;
    pthread_create(&connector1, NULL, connector, NULL);

    while (1) {
        sleep (1);
    }
    return 0;
}

void fatal(void * r) {
    char * msg = (char*) r;
    printf (msg);
    pthread_exit (NULL);
};

void fatal(char * msg) {
    printf (msg);
    pthread_exit (NULL);
};
<commit_msg>Code cleanup<commit_after>#include "controller.h"

void port_connect(jack_port_id_t a, jack_port_id_t b, int connect, void *arg) {
    if (!connect) return;
    // See if "dst" port does not begin with sp_client_
    jack_port_t *port_a = jack_port_by_id(client, a);
    jack_port_t *port_b = jack_port_by_id(client, b);
    if (strstr(jack_port_name(port_b), "sp_client_") == jack_port_name(port_b)) {
        return;
    }
    if (!(JackPortIsOutput & jack_port_flags(port_a))) return;
    //printf("Adding to stack a: %s (b: %s)\n", jack_port_name(port_a), jack_port_name(port_b));
    pthread_mutex_lock(&p_queue_mutex);
    p_queue.push_back(port_a);
    pthread_mutex_unlock(&p_queue_mutex);
    pthread_cond_signal(&p_queue_cond);
}

void *connector(void *arg) {
    pthread_mutex_lock(&p_queue_mutex);
    while (1) {
        pthread_cond_wait(&p_queue_cond, &p_queue_mutex);
        while (!p_queue.empty()) {
            jack_port_t *port = p_queue.front();
            p_queue.pop_front();
            pthread_mutex_unlock(&p_queue_mutex);

            const char *port_name = jack_port_name(port);
            //printf("Got a port to connect to: %s\n", port_name);
            pthread_t tmp; pthread_attr_t attr;
			pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

            pthread_create(&tmp, &attr, go_sp, (void*)(port_name));
            sps.insert(pair<const char*, pthread_t>(port_name, tmp));

            pthread_mutex_lock(&p_queue_mutex);
        }
    }
};

void *go_sp(void *port_name_a) {
    // Call SoundPatty on this port
    char *port_name = (char*)port_name_a;

    FILE *fpipe;
    char command[300];
    sprintf(command, "%s %s %s jack \"%s\"", SP_EXEC, SP_CONF, SP_TRES, port_name);
    //printf("Launching %s\n", command);

    char line[256];
    if ( !(fpipe = (FILE*)popen(command,"r")) )
    {  // If fpipe is NULL
        fatal((void*)"Problems with pipe");
    }
	fgets( line, sizeof line, fpipe); pclose(fpipe);
    if (strstr(line, "FOUND") != NULL) {
        // Found... E-mail script output
        char command[300];
        sprintf(command, "%s \"%s\" \"%s\"", SP_OVER, port_name, line);
        system(command);
    }

    fpipe = popen("date \"+%F %T\" | tr -d '\n\'", "r"); // Date without ENDL
    char output[300]; int fd;
    fgets (output, sizeof output, fpipe); pclose(fpipe);

    printf("%s *** %s *** ::: %s", output, port_name, line);
};

int main () {

    pthread_mutex_init(&p_queue_mutex, NULL);
    pthread_cond_init(&p_queue_cond, NULL);
    ostringstream dst_client_str;
    dst_client_str << "sp_manager_" << getpid();
    if ((client = jack_client_new (string(dst_client_str.str()).c_str())) == 0) {
        fatal ((void*)"jack server not running?\n");
    }
    dst_client_str.~ostringstream();

    jack_set_port_connect_callback(client, port_connect, NULL);
    if (jack_activate (client)) { fatal ((void*)"cannot activate client"); }

    pthread_t connector1;
    pthread_create(&connector1, NULL, connector, NULL);
	pthread_exit(NULL); // Pass to Jack and listener thread
}

void fatal(void * r) {
    char * msg = (char*) r;
    printf (msg);
    pthread_exit (NULL);
};

void fatal(char * msg) {
    printf (msg);
    pthread_exit (NULL);
};
<|endoftext|>


<commit_before>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALANARRAYALLOCATOR_HEADER_GUARD_1357924680)
#define XALANARRAYALLOCATOR_HEADER_GUARD_1357924680

#include <PlatformSupport/PlatformSupportDefinitions.hpp>

#include <cassert>
#include <list>
#include <utility>
#include <vector>

XALAN_CPP_NAMESPACE_BEGIN

template<class Type>
class XALAN_PLATFORMSUPPORT_EXPORT XalanArrayAllocator
{
public:

#if defined(XALAN_NO_STD_NAMESPACE)
	typedef vector<Type>					VectorType;
	typedef typename VectorType::size_type	size_type;
	typedef pair<size_type, VectorType>		ListEntryType;
	typedef list<ListEntryType>				ListType;
#else
	typedef std::vector<Type>					VectorType;
	typedef typename VectorType::size_type		size_type;
	typedef std::pair<size_type, VectorType>	ListEntryType;
	typedef std::list<ListEntryType>			ListType;
#endif

	typedef Type							value_type;

	typedef typename ListType::iterator		ListIteratorType;

    // Default size for vector allocation.
	enum { eDefaultBlockSize = 500 };

	/**
	 * Constructor.
	 *
	 * @param theBlockSize The block size when allocating.
	 */
	XalanArrayAllocator(size_type	theBlockSize = eDefaultBlockSize) :
		m_list(),
		m_blockSize(theBlockSize),
		m_lastEntryFound(0)
	{
	}

	~XalanArrayAllocator()
	{
	}

	/**
	 * Clear the instance, and release all allocated memory
	 */
	void
	clear()
	{
		m_list.clear();

		m_lastEntryFound = 0;
	}

	/**
	 * Reset the instance, but keep all memory so it can be
	 * reused for allocations.  This invalidates all previous
	 * allocations.
	 */
	void
	reset()
	{
		const ListIteratorType	theEnd = m_list.end();
		ListIteratorType		theCurrent = m_list.begin();

		while(theCurrent != theEnd)
		{
			(*theCurrent).first = (*theCurrent).second.size();

			++theCurrent;
		}

		m_lastEntryFound = &*m_list.begin();
	}

	/**
	 * Allocate slots for the given number of Types
	 * instance and return the address of the slots.
	 *
	 * @param theCount The number of slots to allocate
	 */
	Type*
	allocate(size_type	theCount)
	{
		// Handle the case of theCount being greater than the block size first...
		if (theCount >= m_blockSize)
		{
			return createEntry(theCount, theCount);
		}
		else
		{
			ListEntryType*	theEntry =
				findEntry(theCount);

			// Did we find a slot?
			if (theEntry == 0)
			{
				// Nope, create a new one...
				return createEntry(m_blockSize, theCount);
			}
			else
			{
				// The address we want is that of the first free element in the
				// vector...
				Type* const		thePointer =
					&*theEntry->second.begin() + (theEntry->second.size() - theEntry->first);

				// Resize the vector to the appropriate size...
				theEntry->first -= theCount;

				return thePointer;
			}
		}
	}

private:

	// Utility functions...
	Type*
	createEntry(
			size_type	theBlockSize,
			size_type	theCount)
	{
		assert(theBlockSize >= theCount);

		// Push on a new entry.  The entry has no open space,
		// since it's greater than our block size...
		m_list.push_back(ListEntryType(0, VectorType()));

		// Get the new entry...
		ListEntryType&	theNewEntry = m_list.back();

		// Resize the vector to the appropriate size...
		theNewEntry.second.resize(theBlockSize, VectorType::value_type(0));

		// Set the number of free spaces accordingly...
		theNewEntry.first = theBlockSize - theCount;

		if (theNewEntry.first != 0)
		{
			m_lastEntryFound = &theNewEntry;
		}

		// Return a pointer to the beginning of the allocated memory...
		return &*theNewEntry.second.begin();
	}

	ListEntryType*
	findEntry(size_type		theCount)
	{
		// Search for an entry that has some free space.

		if (m_lastEntryFound != 0 && m_lastEntryFound->first >= theCount)
		{
			return m_lastEntryFound;
		}
		else
		{
			const ListIteratorType	theEnd = m_list.end();
			ListIteratorType		theCurrent = m_list.begin();

			ListEntryType*	theEntry = 0;

			while(theCurrent != theEnd)
			{
				// We're looking for the best fit, so
				// if the free space and the count we're
				// looking for are equal, that's pretty
				// much the best we can do...
				if ((*theCurrent).first == theCount)
				{
					theEntry = &*theCurrent;

					break;
				}
				else if ((*theCurrent).first >= theCount)
				{
					// If we haven't found anything yet, the first
					// entry we find that's large enough becomes
					// our best fit.
					//
					// Otherwise, we'll assume that a smaller
					// slot is a better fit, though I may be
					// wrong about this...
					if (theEntry == 0 ||
						(*theCurrent).first < theEntry->first)
					{
						// Nope, so this becomes our best-fit so far.
						theEntry = &*theCurrent;
					}

					++theCurrent;
				}
				else
				{
					// Won't fit, so just continue...
					++theCurrent;
				}
			}

			m_lastEntryFound = theEntry;

			return theEntry;
		}
	}

	// Not implemented...
	XalanArrayAllocator(const XalanArrayAllocator<Type>&	theSource);

	XalanArrayAllocator<Type>&
	operator=(const XalanArrayAllocator<Type>&	theSource);

	bool
	operator==(const XalanArrayAllocator<Type>&	theRHS) const;

	// Data members...
	ListType			m_list;

	const size_type		m_blockSize;

	ListEntryType*		m_lastEntryFound;
};

XALAN_CPP_NAMESPACE_END

#endif	// !defined(XALANARRAYALLOCATOR_HEADER_GUARD_1357924680)
<commit_msg>Check for empty list before iterating it.<commit_after>/*
 * The Apache Software License, Version 1.1
 *
 *
 * Copyright (c) 1999-2002 The Apache Software Foundation.  All rights
 * reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by the
 *        Apache Software Foundation (http://www.apache.org/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Xalan" and "Apache Software Foundation" must
 *    not be used to endorse or promote products derived from this
 *    software without prior written permission. For written
 *    permission, please contact apache@apache.org.
 *
 * 5. Products derived from this software may not be called "Apache",
 *    nor may "Apache" appear in their name, without prior written
 *    permission of the Apache Software Foundation.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
 * USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
 * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
 * OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 * ====================================================================
 *
 * This software consists of voluntary contributions made by many
 * individuals on behalf of the Apache Software Foundation and was
 * originally based on software copyright (c) 1999, International
 * Business Machines, Inc., http://www.ibm.com.  For more
 * information on the Apache Software Foundation, please see
 * <http://www.apache.org/>.
 */
#if !defined(XALANARRAYALLOCATOR_HEADER_GUARD_1357924680)
#define XALANARRAYALLOCATOR_HEADER_GUARD_1357924680

#include <PlatformSupport/PlatformSupportDefinitions.hpp>

#include <cassert>
#include <list>
#include <utility>
#include <vector>

XALAN_CPP_NAMESPACE_BEGIN

template<class Type>
class XALAN_PLATFORMSUPPORT_EXPORT XalanArrayAllocator
{
public:

#if defined(XALAN_NO_STD_NAMESPACE)
	typedef vector<Type>					VectorType;
	typedef typename VectorType::size_type	size_type;
	typedef pair<size_type, VectorType>		ListEntryType;
	typedef list<ListEntryType>				ListType;
#else
	typedef std::vector<Type>					VectorType;
	typedef typename VectorType::size_type		size_type;
	typedef std::pair<size_type, VectorType>	ListEntryType;
	typedef std::list<ListEntryType>			ListType;
#endif

	typedef Type							value_type;

	typedef typename ListType::iterator		ListIteratorType;

    // Default size for vector allocation.
	enum { eDefaultBlockSize = 500 };

	/**
	 * Constructor.
	 *
	 * @param theBlockSize The block size when allocating.
	 */
	XalanArrayAllocator(size_type	theBlockSize = eDefaultBlockSize) :
		m_list(),
		m_blockSize(theBlockSize),
		m_lastEntryFound(0)
	{
	}

	~XalanArrayAllocator()
	{
	}

	/**
	 * Clear the instance, and release all allocated memory
	 */
	void
	clear()
	{
		m_list.clear();

		m_lastEntryFound = 0;
	}

	/**
	 * Reset the instance, but keep all memory so it can be
	 * reused for allocations.  This invalidates all previous
	 * allocations.
	 */
	void
	reset()
	{
		if (m_list.empty() == true)
		{
			m_lastEntryFound = 0;
		}
		else
		{
			const ListIteratorType	theEnd = m_list.end();
			ListIteratorType		theCurrent = m_list.begin();

			do
			{
				(*theCurrent).first = (*theCurrent).second.size();

				++theCurrent;
			} while(theCurrent != theEnd);

			m_lastEntryFound = &*m_list.begin();
		}
	}

	/**
	 * Allocate slots for the given number of Types
	 * instance and return the address of the slots.
	 *
	 * @param theCount The number of slots to allocate
	 */
	Type*
	allocate(size_type	theCount)
	{
		// Handle the case of theCount being greater than the block size first...
		if (theCount >= m_blockSize)
		{
			return createEntry(theCount, theCount);
		}
		else
		{
			ListEntryType*	theEntry =
				findEntry(theCount);

			// Did we find a slot?
			if (theEntry == 0)
			{
				// Nope, create a new one...
				return createEntry(m_blockSize, theCount);
			}
			else
			{
				// The address we want is that of the first free element in the
				// vector...
				Type* const		thePointer =
					&*theEntry->second.begin() + (theEntry->second.size() - theEntry->first);

				// Resize the vector to the appropriate size...
				theEntry->first -= theCount;

				return thePointer;
			}
		}
	}

private:

	// Utility functions...
	Type*
	createEntry(
			size_type	theBlockSize,
			size_type	theCount)
	{
		assert(theBlockSize >= theCount);

		// Push on a new entry.  The entry has no open space,
		// since it's greater than our block size...
		m_list.push_back(ListEntryType(0, VectorType()));

		// Get the new entry...
		ListEntryType&	theNewEntry = m_list.back();

		// Resize the vector to the appropriate size...
		theNewEntry.second.resize(theBlockSize, VectorType::value_type(0));

		// Set the number of free spaces accordingly...
		theNewEntry.first = theBlockSize - theCount;

		if (theNewEntry.first != 0)
		{
			m_lastEntryFound = &theNewEntry;
		}

		// Return a pointer to the beginning of the allocated memory...
		return &*theNewEntry.second.begin();
	}

	ListEntryType*
	findEntry(size_type		theCount)
	{
		// Search for an entry that has some free space.

		if (m_lastEntryFound != 0 && m_lastEntryFound->first >= theCount)
		{
			return m_lastEntryFound;
		}
		else
		{
			const ListIteratorType	theEnd = m_list.end();
			ListIteratorType		theCurrent = m_list.begin();

			ListEntryType*	theEntry = 0;

			while(theCurrent != theEnd)
			{
				// We're looking for the best fit, so
				// if the free space and the count we're
				// looking for are equal, that's pretty
				// much the best we can do...
				if ((*theCurrent).first == theCount)
				{
					theEntry = &*theCurrent;

					break;
				}
				else if ((*theCurrent).first >= theCount)
				{
					// If we haven't found anything yet, the first
					// entry we find that's large enough becomes
					// our best fit.
					//
					// Otherwise, we'll assume that a smaller
					// slot is a better fit, though I may be
					// wrong about this...
					if (theEntry == 0 ||
						(*theCurrent).first < theEntry->first)
					{
						// Nope, so this becomes our best-fit so far.
						theEntry = &*theCurrent;
					}

					++theCurrent;
				}
				else
				{
					// Won't fit, so just continue...
					++theCurrent;
				}
			}

			m_lastEntryFound = theEntry;

			return theEntry;
		}
	}

	// Not implemented...
	XalanArrayAllocator(const XalanArrayAllocator<Type>&	theSource);

	XalanArrayAllocator<Type>&
	operator=(const XalanArrayAllocator<Type>&	theSource);

	bool
	operator==(const XalanArrayAllocator<Type>&	theRHS) const;

	// Data members...
	ListType			m_list;

	const size_type		m_blockSize;

	ListEntryType*		m_lastEntryFound;
};

XALAN_CPP_NAMESPACE_END

#endif	// !defined(XALANARRAYALLOCATOR_HEADER_GUARD_1357924680)
<|endoftext|>


<commit_before>b728fd3a-2747-11e6-9a46-e0f84713e7b8<commit_msg>NO CHANGES<commit_after>b737d830-2747-11e6-87f5-e0f84713e7b8<|endoftext|>


<commit_before>#include <QApplication>
#include <QtDeclarative>
#include <QDeclarativeView>
#include <QDeclarativeContext>

#include "settingspersistor.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QSettings settings("qmltweeter.conf", QSettings::IniFormat);
    settings.sync();

    QDeclarativeView view;
    QDeclarativeContext *context = view.rootContext();

    SettingsPersistor settingsPersistor(context, &settings);
    context->setContextProperty("settings", &settingsPersistor);

    QString searchTerm = settings.value("searchTerm", QString("meego")).toString();
    context->setContextProperty("searchTerm", QVariant::fromValue(searchTerm));

    view.setSource(QUrl("qrc:///qml/qmltweeter.qml"));

    QObject *rootObject = dynamic_cast<QObject*>(view.rootObject());
    QObject::connect(&settingsPersistor, SIGNAL(settingsSaved(QVariant)), rootObject, SLOT(settingsSaved(QVariant)));

    view.show();

    return app.exec();
}
<commit_msg>Remove unnecessary dynamic_cast to base class<commit_after>#include <QApplication>
#include <QtDeclarative>
#include <QDeclarativeView>
#include <QDeclarativeContext>

#include "settingspersistor.h"

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    QSettings settings("qmltweeter.conf", QSettings::IniFormat);
    settings.sync();

    QDeclarativeView view;
    QDeclarativeContext *context = view.rootContext();

    SettingsPersistor settingsPersistor(context, &settings);
    context->setContextProperty("settings", &settingsPersistor);

    QString searchTerm = settings.value("searchTerm", QString("meego")).toString();
    context->setContextProperty("searchTerm", QVariant::fromValue(searchTerm));

    view.setSource(QUrl("qrc:///qml/qmltweeter.qml"));

    QObject *rootObject = view.rootObject();
    QObject::connect(&settingsPersistor, SIGNAL(settingsSaved(QVariant)), rootObject, SLOT(settingsSaved(QVariant)));

    view.show();

    return app.exec();
}
<|endoftext|>


<commit_before>#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <GL/glew.h>
#include <SDL/SDL.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <iostream>
#include <vector>
#include <chrono>
#include <algorithm>
#include <functional>
#include <numeric>
#include <signal.h>

#include "fractal_helpers.h"
#include "sierpinsky_tetrahedron.h"
#include "geometries.h"
#include "enums.h"
#include "options.h"
#include "stats.h"

SDL_Surface *surface;
bool vbo_capable;
bool done;
bool is_active;
GLfloat angle;

GLfloat *data;
size_t data_block_count;
size_t data_block_size;

enum Fractal fractal = SIERPINSKY_TETRAHEDRON;
unsigned int fractal_depth = 5;
enum DrawingMethod drawing_method = IMMEDIATE;
enum ShadingMethod shading_method = SMOOTH;
enum VertexBuffer vertex_buffer = SEPARATE;
bool light_flag = false;
bool wireframe_flag = false;
bool texture_flag = false;
bool blending_flag = false;
std::vector<long> draw_times;
std::vector<long> swap_times;

void
quit (int return_code)
{
  SDL_Quit();
	exit(return_code);
}

void
init_sdl ()
{
  const SDL_VideoInfo *video_info;

  if (SDL_Init( SDL_INIT_VIDEO ) < 0)
  {
    fprintf(stderr, "Video initialization failed: %s", SDL_GetError());
    quit(1);
  }

  video_info = SDL_GetVideoInfo();
  if (!video_info)
  {
    fprintf(stderr, "Video info query failed: %s", SDL_GetError());
    quit(1);
  }

  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 0);

  surface = SDL_SetVideoMode(600, 600, 32,
	    SDL_OPENGL | SDL_GL_DOUBLEBUFFER);

  if (!surface)
  {
    fprintf(stderr, "Video mode set failed: %s", SDL_GetError());
    quit(1);
  }
}

void
resize_viewport ()
{
  glViewport(0, 0, 600, 600);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(50.0f, 1.0f, 1.0f, 20.0f);
  glMatrixMode(GL_MODELVIEW);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
}

void
init_opengl ()
{
	glShadeModel(GL_SMOOTH);
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  glClearDepth(20.0f);
  glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
  glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);

	resize_viewport();

	if (blending_flag)
	{
		glDisable(GL_DEPTH_TEST);
		glEnable (GL_BLEND);
		glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}

	if (wireframe_flag)
	{
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	}

	if (light_flag)
	{
		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		glEnable(GL_COLOR_MATERIAL);
		glEnable(GL_NORMALIZE);
		glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);

		GLfloat ambientLight[] = { 0.1f, 0.1f, 0.1f, 1.0f };
		GLfloat diffuseLight[] = { 0.8f, 0.8f, 0.8, 1.0f };
		GLfloat specularLight[] = { 0.5f, 0.5f, 0.5f, 1.0f };
		GLfloat position[] = { 0.0f, 0.0f, 0.0f, 1.0f };

		glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
		glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
		glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);
		glLightfv(GL_LIGHT0, GL_POSITION, position);
	}

	/*
	if (texture_flag)
	{
		glEnable(GL_TEXTURE_2D);
	}
	*/

	switch (shading_method)
	{
		case FLAT:
			glShadeModel(GL_FLAT);
		break;

		case SMOOTH:
			glShadeModel(GL_SMOOTH);
		break;

		default:
		break;
	}
}

void
init_extensions ()
{
	vbo_capable = false;

  GLenum err = glewInit();
  if (err != GLEW_OK)
  {
    printf("GLEW initialization error: %s\n", glewGetErrorString(err));
    return;
  }

  vbo_capable = GL_ARB_vertex_buffer_object;
}

void
init_animation ()
{
	angle = 0.0f;
}

void
step_animation ()
{
	angle += 0.02f;
}

void
apply_animation ()
{
	glRotatef(angle, 0.0, 1.0, 0.0);
}

void
draw_scene ()
{
  glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
	glLoadIdentity();

	glTranslatef(0.0, 0.0, -10.0f + sin(angle/10.0) * 0.75);
	apply_animation();
	glScalef(2.6, 2.6, 2.6);

	glBegin(GL_TRIANGLES);
		for (unsigned int i = 0; i < data_block_count; i++)
		{
			unsigned int k = i * 36;

			glTexCoord2fv(data + k + 0);
			glColor4fv(data + k + 2);
			glNormal3fv(data + k + 6);
			glVertex3fv(data + k + 9);

			glTexCoord2fv(data + k + 12);
			glColor4fv(data + k + 14);
			glNormal3fv(data + k + 18);
			glVertex3fv(data + k + 21);

			glTexCoord2fv(data + k + 24);
			glColor4fv(data + k + 26);
			glNormal3fv(data + k + 30);
			glVertex3fv(data + k + 33);
		}
	glEnd();

  glFlush();
}

int
main_loop()
{
	is_active = true;
	SDL_Event event;

	while (!done)
	{
		while ( SDL_PollEvent( &event ) )
		{
			switch ( event.type )
			{
				case SDL_ACTIVEEVENT:
					if ( event.active.state == SDL_APPACTIVE )
						is_active = (event.active.gain != 0);
					break;

				case SDL_KEYDOWN:
					//handleKeyPress( &event.key.keysym );
					break;

				case SDL_QUIT:
					done = true;
					break;

				default:
					break;
			}
		}

		if (is_active)
		{
			step_animation();

			using namespace std::chrono;

			auto start = high_resolution_clock::now();
			draw_scene();
			auto end = high_resolution_clock::now();
			auto delta = duration_cast<microseconds>(end - start).count();
			draw_times.push_back(delta);

			start = high_resolution_clock::now();
			SDL_GL_SwapBuffers();
			end = high_resolution_clock::now();
			delta = duration_cast<microseconds>(end - start).count();
			swap_times.push_back(delta);
		}
	}

	return EXIT_SUCCESS;
}

void sigint_handler (int sig)
{
	(void) sig;

	print_stats(std::string("draw"), draw_times);
	print_stats(std::string("swap"), swap_times);
	done = true;
}

void catch_sigint()
{
	struct sigaction new_sa;
	struct sigaction old_sa;

	sigfillset(&new_sa.sa_mask);
	new_sa.sa_handler = sigint_handler;
	new_sa.sa_flags = 0;

	sigaction(SIGINT, &new_sa, 0);
}

// apply object flag
int
main (int argc, char *argv[])
{
	catch_sigint();
	parse_options(argc, argv);

	init_sdl();
	init_opengl();
	init_extensions();
	init_animation();

	Point a {{ 1.0,  1.0,  1.0}};
	Point b {{ 1.0, -1.0, -1.0}};
	Point c {{-1.0,  1.0, -1.0}};
	Point d {{-1.0, -1.0,  1.0}};

	struct Tetrahedron tetrahedron {a, b, c, d};
	std::vector<struct Triangle> triangles =
	    create_sierpinsky_tetrahedron(tetrahedron, fractal_depth);

	data = convert_to_arrayf(triangles);
	data_block_count = triangles.size();
	//data_block_size = 3 + 3 + 4 + 2;

	return main_loop();
}

<commit_msg>Small code style fix<commit_after>#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <GL/glew.h>
#include <SDL/SDL.h>
#include <OpenGL/gl.h>
#include <OpenGL/glu.h>
#include <iostream>
#include <vector>
#include <chrono>
#include <algorithm>
#include <functional>
#include <numeric>
#include <signal.h>

#include "fractal_helpers.h"
#include "sierpinsky_tetrahedron.h"
#include "geometries.h"
#include "enums.h"
#include "options.h"
#include "stats.h"

SDL_Surface *surface;
bool vbo_capable;
bool done;
bool is_active;
GLfloat angle;

GLfloat *data;
size_t data_block_count;
size_t data_block_size;

enum Fractal fractal = SIERPINSKY_TETRAHEDRON;
unsigned int fractal_depth = 5;
enum DrawingMethod drawing_method = IMMEDIATE;
enum ShadingMethod shading_method = SMOOTH;
enum VertexBuffer vertex_buffer = SEPARATE;
bool light_flag = false;
bool wireframe_flag = false;
bool texture_flag = false;
bool blending_flag = false;
std::vector<long> draw_times;
std::vector<long> swap_times;

void
quit (int return_code)
{
  SDL_Quit();
	exit(return_code);
}

void
init_sdl ()
{
  const SDL_VideoInfo *video_info;

  if (SDL_Init( SDL_INIT_VIDEO ) < 0)
  {
    fprintf(stderr, "Video initialization failed: %s", SDL_GetError());
    quit(1);
  }

  video_info = SDL_GetVideoInfo();
  if (!video_info)
  {
    fprintf(stderr, "Video info query failed: %s", SDL_GetError());
    quit(1);
  }

  SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
  SDL_GL_SetAttribute(SDL_GL_SWAP_CONTROL, 0);

  surface = SDL_SetVideoMode(600, 600, 32,
	    SDL_OPENGL | SDL_GL_DOUBLEBUFFER);

  if (!surface)
  {
    fprintf(stderr, "Video mode set failed: %s", SDL_GetError());
    quit(1);
  }
}

void
resize_viewport ()
{
  glViewport(0, 0, 600, 600);
  glMatrixMode(GL_PROJECTION);
  glLoadIdentity();
  gluPerspective(50.0f, 1.0f, 1.0f, 20.0f);
  glMatrixMode(GL_MODELVIEW);
  glEnable(GL_DEPTH_TEST);
  glDepthFunc(GL_LEQUAL);
}

void
init_opengl ()
{
	glShadeModel(GL_SMOOTH);
  glClearColor(0.0f, 0.0f, 0.0f, 0.0f);
  glClearDepth(20.0f);
  glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
  glHint(GL_POLYGON_SMOOTH_HINT, GL_NICEST);

	resize_viewport();

	if (blending_flag)
	{
		glDisable(GL_DEPTH_TEST);
		glEnable (GL_BLEND);
		glBlendFunc (GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
	}

	if (wireframe_flag)
	{
		glPolygonMode(GL_FRONT_AND_BACK, GL_LINE);
	}

	if (light_flag)
	{
		glEnable(GL_LIGHTING);
		glEnable(GL_LIGHT0);
		glEnable(GL_COLOR_MATERIAL);
		glEnable(GL_NORMALIZE);
		glLightModeli(GL_LIGHT_MODEL_TWO_SIDE, GL_TRUE);

		GLfloat ambientLight[] = { 0.1f, 0.1f, 0.1f, 1.0f };
		GLfloat diffuseLight[] = { 0.8f, 0.8f, 0.8, 1.0f };
		GLfloat specularLight[] = { 0.5f, 0.5f, 0.5f, 1.0f };
		GLfloat position[] = { 0.0f, 0.0f, 0.0f, 1.0f };

		glLightfv(GL_LIGHT0, GL_AMBIENT, ambientLight);
		glLightfv(GL_LIGHT0, GL_DIFFUSE, diffuseLight);
		glLightfv(GL_LIGHT0, GL_SPECULAR, specularLight);
		glLightfv(GL_LIGHT0, GL_POSITION, position);
	}

	/*
	if (texture_flag)
	{
		glEnable(GL_TEXTURE_2D);
	}
	*/

	switch (shading_method)
	{
		case FLAT:
			glShadeModel(GL_FLAT);
		break;

		case SMOOTH:
			glShadeModel(GL_SMOOTH);
		break;

		default:
		break;
	}
}

void
init_extensions ()
{
	vbo_capable = false;

  GLenum err = glewInit();
  if (err != GLEW_OK)
  {
    printf("GLEW initialization error: %s\n", glewGetErrorString(err));
    return;
  }

  vbo_capable = GL_ARB_vertex_buffer_object;
}

void
init_animation ()
{
	angle = 0.0f;
}

void
step_animation ()
{
	angle += 0.02f;
}

void
apply_animation ()
{
	glRotatef(angle, 0.0, 1.0, 0.0);
}

void
draw_scene ()
{
  glClear( GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT );
	glLoadIdentity();

	glTranslatef(0.0, 0.0, -10.0f + sin(angle/10.0) * 0.75);
	apply_animation();
	glScalef(2.6, 2.6, 2.6);

	glBegin(GL_TRIANGLES);
		for (unsigned int i = 0; i < data_block_count; i++)
		{
			unsigned int k = i * 36;

			glTexCoord2fv(data + k + 0);
			glColor4fv(data + k + 2);
			glNormal3fv(data + k + 6);
			glVertex3fv(data + k + 9);

			glTexCoord2fv(data + k + 12);
			glColor4fv(data + k + 14);
			glNormal3fv(data + k + 18);
			glVertex3fv(data + k + 21);

			glTexCoord2fv(data + k + 24);
			glColor4fv(data + k + 26);
			glNormal3fv(data + k + 30);
			glVertex3fv(data + k + 33);
		}
	glEnd();

  glFlush();
}

int
main_loop()
{
	is_active = true;
	SDL_Event event;

	while (!done)
	{
		while ( SDL_PollEvent( &event ) )
		{
			switch ( event.type )
			{
				case SDL_ACTIVEEVENT:
					if ( event.active.state == SDL_APPACTIVE )
						is_active = (event.active.gain != 0);
					break;

				case SDL_KEYDOWN:
					//handleKeyPress( &event.key.keysym );
					break;

				case SDL_QUIT:
					done = true;
					break;

				default:
					break;
			}
		}

		if (is_active)
		{
			step_animation();

			using namespace std::chrono;

			auto start = high_resolution_clock::now();
			draw_scene();
			auto end = high_resolution_clock::now();
			auto delta = duration_cast<microseconds>(end - start).count();
			draw_times.push_back(delta);

			start = high_resolution_clock::now();
			SDL_GL_SwapBuffers();
			end = high_resolution_clock::now();
			delta = duration_cast<microseconds>(end - start).count();
			swap_times.push_back(delta);
		}
	}

	return EXIT_SUCCESS;
}

void
sigint_handler (int sig)
{
	(void) sig;

	print_stats(std::string("draw"), draw_times);
	print_stats(std::string("swap"), swap_times);
	done = true;
}

void
catch_sigint()
{
	struct sigaction new_sa;
	struct sigaction old_sa;

	sigfillset(&new_sa.sa_mask);
	new_sa.sa_handler = sigint_handler;
	new_sa.sa_flags = 0;

	sigaction(SIGINT, &new_sa, 0);
}

// apply object flag
int
main (int argc, char *argv[])
{
	catch_sigint();
	parse_options(argc, argv);

	init_sdl();
	init_opengl();
	init_extensions();
	init_animation();

	Point a {{ 1.0,  1.0,  1.0}};
	Point b {{ 1.0, -1.0, -1.0}};
	Point c {{-1.0,  1.0, -1.0}};
	Point d {{-1.0, -1.0,  1.0}};

	struct Tetrahedron tetrahedron {a, b, c, d};
	std::vector<struct Triangle> triangles =
	    create_sierpinsky_tetrahedron(tetrahedron, fractal_depth);

	data = convert_to_arrayf(triangles);
	data_block_count = triangles.size();
	//data_block_size = 3 + 3 + 4 + 2;

	return main_loop();
}

<|endoftext|>


<commit_before><commit_msg>Add type int64 for Equal, float types for ReduceSum (ROCm) (#9010)<commit_after><|endoftext|>


<commit_before>afd800f8-2747-11e6-a516-e0f84713e7b8<commit_msg>fix for the previous fix<commit_after>afe8be21-2747-11e6-918e-e0f84713e7b8<|endoftext|>


<commit_before>7b21b385-ad58-11e7-ac17-ac87a332f658<commit_msg>lets try again<commit_after>7b781d97-ad58-11e7-a556-ac87a332f658<|endoftext|>


<commit_before>/*
 * cl_demo_handler.cpp - CL demo handler
 *
 *  Copyright (c) 2015 Intel Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: Wind Yuan <feng.yuan@intel.com>
 */
#include "xcam_utils.h"
#include "cl_demo_handler.h"

namespace XCam {

CLDemoImageKernel::CLDemoImageKernel (SmartPtr<CLContext> &context)
    : CLImageKernel (context, "kernel_demo")
{
}

XCamReturn
CLDemoImageKernel::prepare_arguments (
    SmartPtr<DrmBoBuffer> &input, SmartPtr<DrmBoBuffer> &output,
    CLArgument args[], uint32_t &arg_count,
    CLWorkSize &work_size)
{
    SmartPtr<CLContext> context = get_context ();
    const VideoBufferInfo & video_info = input->get_video_info ();
    cl_libva_image image_info;

    xcam_mem_clear (&image_info);
    image_info.fmt.image_channel_order = CL_R;
    image_info.fmt.image_channel_data_type = CL_UNORM_INT8;
    image_info.offset = 0;
    image_info.width = video_info.width;
    image_info.height = video_info.height;
    image_info.row_pitch = video_info.strides[0];

    _image_in = new CLVaImage (context, input, &image_info);
    _image_out = new CLVaImage (context, output, &image_info);

    XCAM_ASSERT (_image_in->is_valid () && _image_out->is_valid ());
    XCAM_FAIL_RETURN (
        WARNING,
        _image_in->is_valid () && _image_out->is_valid (),
        XCAM_RETURN_ERROR_MEM,
        "cl image kernel(%s) in/out memory not available", get_kernel_name ());

    //set args;
    args[0].arg_adress = &_image_in->get_mem_id ();
    args[0].arg_size = sizeof (cl_mem);
    args[1].arg_adress = &_image_out->get_mem_id ();
    args[1].arg_size = sizeof (cl_mem);
    arg_count = 2;

    work_size.dim = XCAM_DEFAULT_IMAGE_DIM;
    work_size.global[0] = image_info.row_pitch;
    work_size.global[1] = image_info.height;
    work_size.local[0] = 1;
    work_size.local[1] = 1;

    return XCAM_RETURN_NO_ERROR;
}

XCamReturn
CLDemoImageKernel::post_execute ()
{
    return CLImageKernel::post_execute ();
}

SmartPtr<CLImageHandler>
create_cl_demo_image_handler (SmartPtr<CLContext> &context)
{
    SmartPtr<CLImageHandler> demo_handler;
    SmartPtr<CLImageKernel> demo_kernel;
    XCamReturn ret = XCAM_RETURN_NO_ERROR;

    demo_kernel = new CLDemoImageKernel (context);
    {
        XCAM_CL_KERNEL_FUNC_SOURCE_BEGIN(kernel_demo)
#include "kernel_demo.cl"
        XCAM_CL_KERNEL_FUNC_END;
        ret = demo_kernel->load_from_source (kernel_demo_body, strlen (kernel_demo_body));
        XCAM_FAIL_RETURN (
            WARNING,
            ret == XCAM_RETURN_NO_ERROR,
            NULL,
            "CL image handler(%s) load source failed", demo_kernel->get_kernel_name());
    }
    XCAM_ASSERT (demo_kernel->is_valid ());
    demo_handler = new CLImageHandler ("cl_handler_demo");
    demo_handler->add_kernel  (demo_kernel);

    return demo_handler;
}

};
<commit_msg>cl_demo: correct demo for image copy<commit_after>/*
 * cl_demo_handler.cpp - CL demo handler
 *
 *  Copyright (c) 2015 Intel Corporation
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: Wind Yuan <feng.yuan@intel.com>
 */
#include "xcam_utils.h"
#include "cl_demo_handler.h"

namespace XCam {

CLDemoImageKernel::CLDemoImageKernel (SmartPtr<CLContext> &context)
    : CLImageKernel (context, "kernel_demo")
{
}

XCamReturn
CLDemoImageKernel::prepare_arguments (
    SmartPtr<DrmBoBuffer> &input, SmartPtr<DrmBoBuffer> &output,
    CLArgument args[], uint32_t &arg_count,
    CLWorkSize &work_size)
{
    SmartPtr<CLContext> context = get_context ();
    const VideoBufferInfo & video_info = input->get_video_info ();
    cl_libva_image image_info;

    xcam_mem_clear (&image_info);
    image_info.fmt.image_channel_order = CL_R;
    image_info.fmt.image_channel_data_type = CL_UNORM_INT8;
    image_info.offset = 0;
    image_info.width = video_info.width;
    image_info.height = (video_info.size / video_info.strides[0])/4*4;
    image_info.row_pitch = video_info.strides[0];

    _image_in = new CLVaImage (context, input, &image_info);
    _image_out = new CLVaImage (context, output, &image_info);

    XCAM_ASSERT (_image_in->is_valid () && _image_out->is_valid ());
    XCAM_FAIL_RETURN (
        WARNING,
        _image_in->is_valid () && _image_out->is_valid (),
        XCAM_RETURN_ERROR_MEM,
        "cl image kernel(%s) in/out memory not available", get_kernel_name ());

    //set args;
    args[0].arg_adress = &_image_in->get_mem_id ();
    args[0].arg_size = sizeof (cl_mem);
    args[1].arg_adress = &_image_out->get_mem_id ();
    args[1].arg_size = sizeof (cl_mem);
    arg_count = 2;

    work_size.dim = XCAM_DEFAULT_IMAGE_DIM;
    work_size.global[0] = image_info.row_pitch;
    work_size.global[1] = image_info.height;
    work_size.local[0] = 8;
    work_size.local[1] = 4;

    return XCAM_RETURN_NO_ERROR;
}

XCamReturn
CLDemoImageKernel::post_execute ()
{
    return CLImageKernel::post_execute ();
}

SmartPtr<CLImageHandler>
create_cl_demo_image_handler (SmartPtr<CLContext> &context)
{
    SmartPtr<CLImageHandler> demo_handler;
    SmartPtr<CLImageKernel> demo_kernel;
    XCamReturn ret = XCAM_RETURN_NO_ERROR;

    demo_kernel = new CLDemoImageKernel (context);
    {
        XCAM_CL_KERNEL_FUNC_SOURCE_BEGIN(kernel_demo)
#include "kernel_demo.cl"
        XCAM_CL_KERNEL_FUNC_END;
        ret = demo_kernel->load_from_source (kernel_demo_body, strlen (kernel_demo_body));
        XCAM_FAIL_RETURN (
            WARNING,
            ret == XCAM_RETURN_NO_ERROR,
            NULL,
            "CL image handler(%s) load source failed", demo_kernel->get_kernel_name());
    }
    XCAM_ASSERT (demo_kernel->is_valid ());
    demo_handler = new CLImageHandler ("cl_handler_demo");
    demo_handler->add_kernel  (demo_kernel);

    return demo_handler;
}

};
<|endoftext|>


<commit_before>#include "sgct.h"
#include "ParticleSystem.h"
#include "Snow.h"
#include "World.h"
#include "HelperFunctions.h"
#include "Field.h"
#include "DebugField.h"
#include "Gravity.h"
#include "Wind.h"
#include "ObjSystem.h"
#include "SoapBubble.h"
#include "Vortex.h"
#include <iostream>
#include "SimplexNoise.h"

//our beautiful global variables
sgct::Engine* gEngine;
Snow* gParticles;
World* gWorld;
Object* road;
Object* tree;
SoapBubble* gBubble;
Wind* gWind;
Gravity* gGrav;
Vortex* gTurbine;

bool gDisplayInfo;
bool gStatsGraph;
bool gWireframe;

sgct::SharedDouble curr_time(0.0);
sgct::SharedDouble sizeFactorX(0.0);
sgct::SharedDouble sizeFactorY(0.0);
sgct::SharedDouble sizeFactorZ(0.0);
sgct::SharedDouble vortFactorX(0.0);
sgct::SharedDouble vortFactorY(0.0);
sgct::SharedDouble vortFactorZ(0.0);
sgct::SharedDouble positionX(0.0);
sgct::SharedDouble positionZ(0.0);
sgct::SharedDouble radius(0.0);
sgct::SharedDouble fadeDistance(0.0);

void initialize();
void draw();
void myPreSyncFun();
void statsDrawFun();
void myEncodeFun();
void myDecodeFun();
void externalControlCallback(const char * receivedChars, int size, int clientId);
void sendMessageToExternalControl(void * data, int length);

int main(int argc, char *argv[])
{
	initRandom();

	gEngine = new sgct::Engine(argc, argv);

	gEngine->setInitOGLFunction(initialize);
	gEngine->setDrawFunction(draw);
	gEngine->setPreSyncFunction(myPreSyncFun);
	gEngine->setPostSyncPreDrawFunction(statsDrawFun);
	gEngine->setExternalControlCallback(externalControlCallback);
	sgct::SharedData::instance()->setEncodeFunction(myEncodeFun);
	sgct::SharedData::instance()->setDecodeFunction(myDecodeFun);

	gParticles = new Snow(gEngine);
	gWorld = new World(gEngine);

	gBubble = new SoapBubble(gEngine);

	road = new Object(gEngine);
	tree = new Object(gEngine);

	gGrav = new Gravity();
	gGrav->init(-9.81f);
	gParticles->addField(gGrav);

	gWind = new Wind();
	//wind->init(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2));
	gWind->setAcceleration(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2));
	//gParticles->addField(gWind);

	gTurbine = new Vortex();
	gTurbine->init(0.0f, 0.0f, 0.0f);
	// gParticles->addField(gTurbine);

	if(!gEngine->init(sgct::Engine::OpenGL_3_3_Core_Profile))
	{
		delete gEngine;
		return EXIT_FAILURE;
	}

	//Not working yet... :(
	SimplexNoise* noise = new SimplexNoise();
	noise->init(glm::vec3(0), glm::vec3(0), gEngine->getTime());

	// gParticles->addField(noise);

	cout << "---- Fields active on gParticles ----" << endl;
	gParticles->printFields();
	cout << "---------------" << endl << endl;

	gEngine->render();

	gParticles->destroy();
	road->deleteObject();
	delete road;
	delete gEngine;
	delete gParticles;
	delete gWorld;
	delete gBubble;
	delete gWind;
	delete gTurbine;

	exit(EXIT_SUCCESS);
}

void initialize()
{
	if(!gParticles->initialize())
	{
		std::cout << "Error Initialzing Particle System:" << std::endl;
		exit(EXIT_FAILURE);
	}
	gWorld->initializeWorld();

	road->loadObj("road/road.obj", "road/road.png");
	road->scale(0.2f,0.2f,0.2f);
	road->translate(0.0f, -2.0f, 5.0f);

	tree->loadObj("road/tree.obj","road/tree.png");
	tree->scale(0.05f,0.05f,0.05f);
	tree->translate(0.0f, -1.0f, -6.0f);

	gBubble->createSphere(1.5f, 100);

	gDisplayInfo = false;
	gStatsGraph = false;
	gWireframe = false;
}

void draw()
{
	double delta = gEngine->getDt();
	gWorld->drawWorld();
	gBubble->drawBubble();
	road->draw();
	tree->draw();
	gParticles->move(delta);
	gParticles->draw(delta);

	//if(gEngine->isExternalControlConnected())
	//	cout << "Connectad is very nice";
}

//Checking the time since the program started, not sure if we need this either.
void myPreSyncFun()
{
	//Checks so the gEnginenode is actually the master.
	if( gEngine->isMaster() )
	{
		//Sets the current time since the program started
		curr_time.setVal(sgct::Engine::getTime());
	}
}

void myEncodeFun()
{
	sgct::SharedData::instance()->writeDouble(&curr_time);
 	sgct::SharedData::instance()->writeDouble(&sizeFactorX);
 	sgct::SharedData::instance()->writeDouble(&sizeFactorY);
 	sgct::SharedData::instance()->writeDouble(&sizeFactorZ);
 	sgct::SharedData::instance()->writeDouble(&vortFactorX);
 	sgct::SharedData::instance()->writeDouble(&vortFactorY);
 	sgct::SharedData::instance()->writeDouble(&vortFactorZ);
 	sgct::SharedData::instance()->writeDouble(&positionX);
 	sgct::SharedData::instance()->writeDouble(&positionZ);
 	sgct::SharedData::instance()->writeDouble(&radius);
 	sgct::SharedData::instance()->writeDouble(&fadeDistance);

}

void myDecodeFun()
{
	sgct::SharedData::instance()->readDouble(&curr_time);
	sgct::SharedData::instance()->readDouble(&sizeFactorX);
	sgct::SharedData::instance()->readDouble(&sizeFactorY);
	sgct::SharedData::instance()->readDouble(&sizeFactorZ);
	sgct::SharedData::instance()->readDouble(&vortFactorX);
	sgct::SharedData::instance()->readDouble(&vortFactorY);
	sgct::SharedData::instance()->readDouble(&vortFactorZ);
	sgct::SharedData::instance()->readDouble(&positionX);
	sgct::SharedData::instance()->readDouble(&positionZ);
	sgct::SharedData::instance()->readDouble(&radius);
	sgct::SharedData::instance()->readDouble(&fadeDistance);
}

//Shows stats and graph depending on if the variables are true or not. Dont know if we need this? Currently set to false.
void statsDrawFun()
{
	gEngine->setDisplayInfoVisibility(gDisplayInfo);
	gEngine->setStatsGraphVisibility(gStatsGraph);
	gEngine->setWireframe(gWireframe);
}

//Used to alter certain values when sent from GUI. This way we can alter the fields or change gravity in realtime!
void externalControlCallback(const char * receivedChars, int size, int clientId)
{
	//Checks so the gEnginenode is actually the master.
	if(gEngine->isMaster())
	{
		if(size >= 6 && strncmp(receivedChars, "winX", 4) == 0)
		{
			//We need an int.
 			int tmpVal = atoi(receivedChars + 5);
 			sizeFactorX.setVal(tmpVal);
			gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));

		}

		else if(size >= 6 && strncmp(receivedChars, "winY", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
 			sizeFactorY.setVal(tmpVal);
			gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "winZ", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
 			sizeFactorZ.setVal(tmpVal);
			gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
		}
		else if(size >= 6 && strncmp(receivedChars, "vorX", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			gTurbine->setForce((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "vorY", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			vortFactorY.setVal(tmpVal);
			gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "vorZ", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			vortFactorZ.setVal(tmpVal);
			gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "posX", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			positionX.setVal(tmpVal);
			gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "posZ", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			positionZ.setVal(tmpVal);
			gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "radi", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			radius.setVal(tmpVal);
			gTurbine->setRadius(radius.getVal());
		}

		else if(size >= 6 && strncmp(receivedChars, "paus", 4) == 0)
		{
			gParticles->togglePause();
		}

		else if(size >= 6 && strncmp(receivedChars, "grav", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			gGrav->init(-tmpVal);
		}

		else if(strncmp(receivedChars, "fade", 1) == 0)
		{
			float tmpVal = atof(receivedChars + 5);
			fadeDistance.setVal(tmpVal);
			gParticles->setFadeDistance(fadeDistance.getVal());
		}

		else if(size >= 6 && strncmp(receivedChars, "disp", 4) == 0)
		{
			//gDisplayInfo = !gDisplayInfo;
		}

		else if(size >= 6 && strncmp(receivedChars, "stat", 4) == 0)
		{
			//gStatsGraph = !gStatsGraph;
		}

		else if(size >= 6 && strncmp(receivedChars, "wire", 4) == 0)
		{
			//gWireframe = !gWireframe;
		}
	}
}
<commit_msg>Added jquery<commit_after>#include "sgct.h"
#include "ParticleSystem.h"
#include "Snow.h"
#include "World.h"
#include "HelperFunctions.h"
#include "Field.h"
#include "DebugField.h"
#include "Gravity.h"
#include "Wind.h"
#include "ObjSystem.h"
#include "SoapBubble.h"
#include "Vortex.h"
#include <iostream>
#include "SimplexNoise.h"

//our beautiful global variables
sgct::Engine* gEngine;
Snow* gParticles;
World* gWorld;
Object* road;
Object* tree;
SoapBubble* gBubble;
Wind* gWind;
Gravity* gGrav;
Vortex* gTurbine;

bool gDisplayInfo;
bool gStatsGraph;
bool gWireframe;

sgct::SharedDouble curr_time(0.0);
sgct::SharedDouble sizeFactorX(0.0);
sgct::SharedDouble sizeFactorY(0.0);
sgct::SharedDouble sizeFactorZ(0.0);
sgct::SharedDouble vortFactorX(0.0);
sgct::SharedDouble vortFactorY(0.0);
sgct::SharedDouble vortFactorZ(0.0);
sgct::SharedDouble positionX(0.0);
sgct::SharedDouble positionZ(0.0);
sgct::SharedDouble radius(0.0);
sgct::SharedDouble fadeDistance(0.0);

void initialize();
void draw();
void myPreSyncFun();
void statsDrawFun();
void myEncodeFun();
void myDecodeFun();
void externalControlCallback(const char * receivedChars, int size, int clientId);
void sendMessageToExternalControl(void * data, int length);

int main(int argc, char *argv[])
{
	initRandom();

	gEngine = new sgct::Engine(argc, argv);

	// sgct setup and preparation
	gEngine->setInitOGLFunction(initialize);
	gEngine->setDrawFunction(draw);
	gEngine->setPreSyncFunction(myPreSyncFun);
	gEngine->setPostSyncPreDrawFunction(statsDrawFun);
	gEngine->setExternalControlCallback(externalControlCallback);
	sgct::SharedData::instance()->setEncodeFunction(myEncodeFun);
	sgct::SharedData::instance()->setDecodeFunction(myDecodeFun);

	gParticles = new Snow(gEngine);
	gWorld = new World(gEngine);

	// add some nice objects
	gBubble = new SoapBubble(gEngine);
	road = new Object(gEngine);
	tree = new Object(gEngine);

	// dem fields
	gGrav = new Gravity();
	gGrav->init(-9.81f);
	gParticles->addField(gGrav);

	gWind = new Wind();
	//wind->init(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2));
	gWind->setAcceleration(getRandom(-0.2, 0.2), 0.0f, getRandom(-0.2, 0.2));
	gParticles->addField(gWind);

	gTurbine = new Vortex();
	gTurbine->init(0.0f, 0.0f, 0.0f);
	gParticles->addField(gTurbine);

	//Not working yet... :(
	SimplexNoise* noise = new SimplexNoise();
	noise->init(glm::vec3(0), glm::vec3(0), gEngine->getTime());
	// gParticles->addField(noise);

	if(!gEngine->init(sgct::Engine::OpenGL_3_3_Core_Profile))
	{
		delete gEngine;
		return EXIT_FAILURE;
	}

	// tell user what field's are active
	cout << "---- Fields active on gParticles ----" << endl;
	gParticles->printFields();
	cout << "---------------" << endl << endl;

	// Let's get ready to rendeeeeeer!
	gEngine->render();

	// destroy everything and exit
	gParticles->destroy();
	road->deleteObject();
	delete road;
	delete gEngine;
	delete gParticles;
	delete gWorld;
	delete gBubble;
	delete gWind;
	delete gTurbine;

	exit(EXIT_SUCCESS);
}

void initialize()
{
	if(!gParticles->initialize())
	{
		std::cout << "Error Initialzing Particle System:" << std::endl;
		exit(EXIT_FAILURE);
	}
	gWorld->initializeWorld();

	road->loadObj("road/road.obj", "road/road.png");
	road->scale(0.2f,0.2f,0.2f);
	road->translate(0.0f, -2.0f, 5.0f);

	tree->loadObj("road/tree.obj","road/tree.png");
	tree->scale(0.05f,0.05f,0.05f);
	tree->translate(0.0f, -1.0f, -6.0f);

	gBubble->createSphere(1.5f, 100);

	// hide stats and such by default
	gDisplayInfo = false;
	gStatsGraph = false;
	gWireframe = false;
}

void draw()
{
	double delta = gEngine->getDt();
	gWorld->drawWorld();
	gBubble->drawBubble();
	road->draw();
	tree->draw();
	gParticles->move(delta);
	gParticles->draw(delta);

	//if(gEngine->isExternalControlConnected())
	//	cout << "Connectad is very nice";
}

//Checking the time since the program started, not sure if we need this either.
void myPreSyncFun()
{
	//Checks so the gEnginenode is actually the master.
	if( gEngine->isMaster() )
	{
		//Sets the current time since the program started
		curr_time.setVal(sgct::Engine::getTime());
	}
}

void myEncodeFun()
{
	sgct::SharedData::instance()->writeDouble(&curr_time);
 	sgct::SharedData::instance()->writeDouble(&sizeFactorX);
 	sgct::SharedData::instance()->writeDouble(&sizeFactorY);
 	sgct::SharedData::instance()->writeDouble(&sizeFactorZ);
 	sgct::SharedData::instance()->writeDouble(&vortFactorX);
 	sgct::SharedData::instance()->writeDouble(&vortFactorY);
 	sgct::SharedData::instance()->writeDouble(&vortFactorZ);
 	sgct::SharedData::instance()->writeDouble(&positionX);
 	sgct::SharedData::instance()->writeDouble(&positionZ);
 	sgct::SharedData::instance()->writeDouble(&radius);
 	sgct::SharedData::instance()->writeDouble(&fadeDistance);
}

void myDecodeFun()
{
	sgct::SharedData::instance()->readDouble(&curr_time);
	sgct::SharedData::instance()->readDouble(&sizeFactorX);
	sgct::SharedData::instance()->readDouble(&sizeFactorY);
	sgct::SharedData::instance()->readDouble(&sizeFactorZ);
	sgct::SharedData::instance()->readDouble(&vortFactorX);
	sgct::SharedData::instance()->readDouble(&vortFactorY);
	sgct::SharedData::instance()->readDouble(&vortFactorZ);
	sgct::SharedData::instance()->readDouble(&positionX);
	sgct::SharedData::instance()->readDouble(&positionZ);
	sgct::SharedData::instance()->readDouble(&radius);
	sgct::SharedData::instance()->readDouble(&fadeDistance);
}

//Shows stats and graph depending on if the variables are true or not. Dont know if we need this? Currently set to false.
void statsDrawFun()
{
	gEngine->setDisplayInfoVisibility(gDisplayInfo);
	gEngine->setStatsGraphVisibility(gStatsGraph);
	gEngine->setWireframe(gWireframe);
}

//Used to alter certain values when sent from GUI. This way we can alter the fields or change gravity in realtime!
void externalControlCallback(const char * receivedChars, int size, int clientId)
{
	//Checks so the gEnginenode is actually the master.
	if(gEngine->isMaster())
	{
		if(size >= 6 && strncmp(receivedChars, "winX", 4) == 0)
		{
			//We need an int.
 			int tmpVal = atoi(receivedChars + 5);
 			sizeFactorX.setVal(tmpVal);
			gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "winY", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
 			sizeFactorY.setVal(tmpVal);
			gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "winZ", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
 			sizeFactorZ.setVal(tmpVal);
			gWind->setAcceleration((sizeFactorX.getVal()*0.01f), (sizeFactorY.getVal()*0.01f), (sizeFactorZ.getVal()*0.01f));
		}
		else if(size >= 6 && strncmp(receivedChars, "vorX", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			gTurbine->setForce((tmpVal*0.01f), (tmpVal*0.01f), (tmpVal*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "vorY", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			vortFactorY.setVal(tmpVal);
			gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "vorZ", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			vortFactorZ.setVal(tmpVal);
			gTurbine->setForce((vortFactorX.getVal()*0.01f), (vortFactorY.getVal()*0.01f), (vortFactorZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "posX", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			positionX.setVal(tmpVal);
			gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "posZ", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			positionZ.setVal(tmpVal);
			gTurbine->setPosition((positionX.getVal()*0.01f),(positionZ.getVal()*0.01f));
		}

		else if(size >= 6 && strncmp(receivedChars, "radi", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			radius.setVal(tmpVal);
			gTurbine->setRadius(radius.getVal());
		}

		else if(size >= 6 && strncmp(receivedChars, "paus", 4) == 0)
		{
			gParticles->togglePause();
		}

		else if(size >= 6 && strncmp(receivedChars, "grav", 4) == 0)
		{
			//We need an int.
			int tmpVal = atoi(receivedChars + 5);
			gGrav->init(-tmpVal);
		}

		else if(strncmp(receivedChars, "fade", 1) == 0)
		{
			float tmpVal = atof(receivedChars + 5);
			fadeDistance.setVal(tmpVal);
			gParticles->setFadeDistance(fadeDistance.getVal());
		}

		else if(size >= 6 && strncmp(receivedChars, "disp", 4) == 0)
		{
			//gDisplayInfo = !gDisplayInfo;
		}

		else if(size >= 6 && strncmp(receivedChars, "stat", 4) == 0)
		{
			//gStatsGraph = !gStatsGraph;
		}

		else if(size >= 6 && strncmp(receivedChars, "wire", 4) == 0)
		{
			//gWireframe = !gWireframe;
		}
	}
}
<|endoftext|>


<commit_before>7dc324f3-4b02-11e5-991c-28cfe9171a43<commit_msg>more fixes<commit_after>7dcf03e3-4b02-11e5-b338-28cfe9171a43<|endoftext|>