<commit_before>/**
 * @file
 * @author  Mamadou Babaei <info@babaei.net>
 * @version 0.1.0
 *
 * @section LICENSE
 *
 * (The MIT License)
 *
 * Copyright (c) 2016 - 2020 Mamadou Babaei
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @section DESCRIPTION
 *
 * A (a)synchronous thread-safe mail class with a built-in queue system.
 */

#include <chrono>
#include <queue>
#include <boost/bind.hpp>
#include <boost/chrono/chrono.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread/lock_guard.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#if defined ( _WIN32 )
#include <vmime/platforms/windows/windowsHandler.hpp>
#else
#include <vmime/platforms/posix/posixHandler.hpp>
#include <vmime/vmime.hpp>
#endif  // defined (_WIN32 )
#include "make_unique.hpp"
#include "Log.hpp"
#include "Mail.hpp"
#include "Utility.hpp"

#define     WORKER_THREAD_STOP_IDLE_MILLISECONDS        10000.0
#define     UNKNOWN_ERROR                               "Unknown error!"

using namespace std;
using namespace boost;
using namespace CoreLib;

struct Mail::Impl
{
public:
    static std::queue<Mail *> MailQueue;
    static std::queue<Mail::SendCallback> MailCallbackQueue;
    static bool WorkerThreadIsRunning;
    static boost::mutex MailMutex;
    static boost::mutex WorkerMutex;
    static std::unique_ptr<boost::thread> WorkerThread;

public:
    static void DoWork();

public:
    std::string From;
    std::string To;
    std::string Subject;
    std::string Body;
    std::vector<std::string> Attachments;

    bool DeleteLater;

public:
    Impl();
    ~Impl();
};

std::queue<Mail *> Mail::Impl::MailQueue;
std::queue<Mail::SendCallback> Mail::Impl::MailCallbackQueue;
bool Mail::Impl::WorkerThreadIsRunning = false;
boost::mutex Mail::Impl::MailMutex;
boost::mutex Mail::Impl::WorkerMutex;
std::unique_ptr<boost::thread> Mail::Impl::WorkerThread;

void Mail::Impl::DoWork()
{
    LOG_INFO("Mail worker thread started");

    try {
        auto lastJobTime = std::chrono::high_resolution_clock::now();

        bool isMailQueueEmpty = false;
        Mail *mail = nullptr;
        Mail::SendCallback callback = nullptr;

        for (;;) {
            boost::this_thread::interruption_point();

            {
                boost::lock_guard<boost::mutex> lock(WorkerMutex);
                (void)lock;

                if (!WorkerThreadIsRunning)
                    break;
            }

            boost::this_thread::disable_interruption di;

            {
                boost::lock_guard<boost::mutex> lock(MailMutex);
                (void)lock;

                isMailQueueEmpty = !(MailQueue.size() > 0);

                if (!isMailQueueEmpty) {
                    mail = MailQueue.front();
                    callback = MailCallbackQueue.front();
                }
            }

            if (!isMailQueueEmpty) {
                string error;
                bool rc = mail->Send(error);
                if (callback != nullptr) {
                    callback(rc, error);
                }

                {
                    boost::lock_guard<boost::mutex> lock(MailMutex);
                    (void)lock;

                    MailQueue.pop();
                    MailCallbackQueue.pop();
                }

                if (mail->GetDeleteLater()) {
                    delete mail;
                }

                lastJobTime = std::chrono::high_resolution_clock::now();
            }

            boost::this_thread::restore_interruption ri(di);
            (void)ri;
            boost::this_thread::interruption_point();

            boost::this_thread::sleep_for(boost::chrono::nanoseconds(1));

            if (isMailQueueEmpty) {
                if ((std::chrono::duration<double, std::milli>(
                         std::chrono::high_resolution_clock::now() - lastJobTime)).count() // elapsed in milliseconds
                        > WORKER_THREAD_STOP_IDLE_MILLISECONDS) {
                    {
                        boost::lock_guard<boost::mutex> lock(WorkerMutex);
                        (void)lock;

                        WorkerThreadIsRunning = false;
                        break;
                    }
                }
            }
        }
    }

    catch (boost::exception &ex) {
        LOG_ERROR(boost::diagnostic_information(ex));
    }

    catch (std::exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (...) {
        LOG_ERROR(UNKNOWN_ERROR);
    }

    LOG_INFO("Mail worker thread stopped");
}

Mail::Mail()
    : m_pimpl(std::make_shared<Mail::Impl>())
{

}

Mail::Mail(const std::string &from, const std::string &to,
           const std::string &subject, const std::string &body,
           const std::vector<std::string> &attachments)
    : m_pimpl(std::make_shared<Mail::Impl>())
{
    m_pimpl->From = from;
    m_pimpl->To = to;
    m_pimpl->Subject = subject;
    m_pimpl->Body = body;
    SetAttachments(attachments);
}

Mail::~Mail() = default;

std::string Mail::GetFrom()
{
    return m_pimpl->From;
}

std::string Mail::GetTo()
{
    return m_pimpl->To;
}

std::string Mail::GetSubject()
{
    return m_pimpl->Subject;
}

std::string Mail::GetBody()
{
    return m_pimpl->Body;
}

const std::vector<std::string> &Mail::GetAttachments()
{
    return m_pimpl->Attachments;
}

void Mail::SetFrom(const std::string &from)
{
    m_pimpl->From = from;
}

void Mail::SetTo(const std::string &to)
{
    m_pimpl->To = to;
}

void Mail::SetSubject(const std::string &subject)
{
    m_pimpl->Subject = subject;
}

void Mail::SetBody(const std::string &body)
{
    m_pimpl->Body = body;
}

void Mail::SetAttachments(const std::vector<std::string> &attachments)
{
    m_pimpl->Attachments.clear();
    for (auto a : attachments) {
        m_pimpl->Attachments.push_back(a);
    }
}

bool Mail::GetDeleteLater() const
{
    return m_pimpl->DeleteLater;
}

void Mail::SetDeleteLater(const bool del) const
{
    m_pimpl->DeleteLater = del;
}

bool Mail::Send() const
{
    string err;
    return Send(err);
}

bool Mail::Send(std::string &out_error) const
{
    try {
#if defined (_WIN32)
        vmime::platform::setHandler<vmime::platforms::windows::windowsHandler>();
#else
        vmime::platform::setHandler<vmime::platforms::posix::posixHandler>();
#endif /* defined (_WIN32) */

        vmime::messageBuilder mb;

        mb.setExpeditor(vmime::mailbox(m_pimpl->From));
        mb.getRecipients().appendAddress(vmime::make_shared<vmime::mailbox>(m_pimpl->To));

        mb.setSubject(*vmime::text::newFromString(m_pimpl->Subject, vmime::charsets::UTF_8));

        mb.constructTextPart(vmime::mediaType(vmime::mediaTypes::TEXT, vmime::mediaTypes::TEXT_HTML));
        mb.getTextPart()->setCharset(vmime::charsets::UTF_8);
        mb.getTextPart()->setText(vmime::make_shared<vmime::stringContentHandler>(m_pimpl->Body));

        if (m_pimpl->Attachments.size() > 0) {
            for (auto a : m_pimpl->Attachments) {
                vmime::shared_ptr <vmime::attachment> att = vmime::make_shared <vmime::fileAttachment>
                        (a, vmime::mediaType("application/octet-stream"),
                         vmime::text(filesystem::path(a).stem().string()));
                mb.appendAttachment(att);
            }
        }

        vmime::shared_ptr<vmime::message> msg = mb.construct();

        vmime::utility::url url("smtp://localhost");
#if VMIME_API_MODE == VMIME_LEGACY_API
        vmime::shared_ptr<vmime::net::session> sess = vmime::make_shared<vmime::net::session>();
#else
        vmime::shared_ptr<vmime::net::session> sess = vmime::net::session::create();
#endif  // VMIME_API_MODE == VMIME_LEGACY_API
        vmime::shared_ptr<vmime::net::transport> tr = sess->getTransport(url);

        tr->connect();
        tr->send(msg);
        tr->disconnect();

        return true;
    }

    catch (vmime::exception &ex) {
        out_error.assign(ex.what());
    }

    catch(std::exception &ex) {
        out_error.assign(ex.what());
    }

    catch (...) {
        out_error.assign(UNKNOWN_ERROR);
    }

    return false;
}

void Mail::SendAsync(const SendCallback callback)
{
    try {
        {
            boost::lock_guard<boost::mutex> lock(Impl::MailMutex);
            (void)lock;

            Impl::MailQueue.push(this);
            Impl::MailCallbackQueue.push(callback);
        }

        {
            boost::lock_guard<boost::mutex> lock(Impl::WorkerMutex);
            (void)lock;

            if (!Impl::WorkerThreadIsRunning) {
                Impl::WorkerThreadIsRunning = true;

                Impl::WorkerThread = make_unique<boost::thread>(Mail::Impl::DoWork);
                Impl::WorkerThread->detach();
            }
        }
    }

    catch (boost::exception &ex) {
        LOG_ERROR(boost::diagnostic_information(ex));
    }

    catch (std::exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (...) {
        LOG_ERROR(UNKNOWN_ERROR);
    }
}

Mail::Impl::Impl()
    : DeleteLater(false)
{

}

Mail::Impl::~Impl() = default;
<commit_msg>add boost prefix to filesystem in order to avoid build issues in c++17 mode on clang<commit_after>/**
 * @file
 * @author  Mamadou Babaei <info@babaei.net>
 * @version 0.1.0
 *
 * @section LICENSE
 *
 * (The MIT License)
 *
 * Copyright (c) 2016 - 2020 Mamadou Babaei
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
 * THE SOFTWARE.
 *
 * @section DESCRIPTION
 *
 * A (a)synchronous thread-safe mail class with a built-in queue system.
 */

#include <chrono>
#include <queue>
#include <boost/bind.hpp>
#include <boost/chrono/chrono.hpp>
#include <boost/exception/diagnostic_information.hpp>
#include <boost/filesystem.hpp>
#include <boost/thread/lock_guard.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/thread.hpp>
#if defined ( _WIN32 )
#include <vmime/platforms/windows/windowsHandler.hpp>
#else
#include <vmime/platforms/posix/posixHandler.hpp>
#include <vmime/vmime.hpp>
#endif  // defined (_WIN32 )
#include "make_unique.hpp"
#include "Log.hpp"
#include "Mail.hpp"
#include "Utility.hpp"

#define     WORKER_THREAD_STOP_IDLE_MILLISECONDS        10000.0
#define     UNKNOWN_ERROR                               "Unknown error!"

using namespace std;
using namespace boost;
using namespace CoreLib;

struct Mail::Impl
{
public:
    static std::queue<Mail *> MailQueue;
    static std::queue<Mail::SendCallback> MailCallbackQueue;
    static bool WorkerThreadIsRunning;
    static boost::mutex MailMutex;
    static boost::mutex WorkerMutex;
    static std::unique_ptr<boost::thread> WorkerThread;

public:
    static void DoWork();

public:
    std::string From;
    std::string To;
    std::string Subject;
    std::string Body;
    std::vector<std::string> Attachments;

    bool DeleteLater;

public:
    Impl();
    ~Impl();
};

std::queue<Mail *> Mail::Impl::MailQueue;
std::queue<Mail::SendCallback> Mail::Impl::MailCallbackQueue;
bool Mail::Impl::WorkerThreadIsRunning = false;
boost::mutex Mail::Impl::MailMutex;
boost::mutex Mail::Impl::WorkerMutex;
std::unique_ptr<boost::thread> Mail::Impl::WorkerThread;

void Mail::Impl::DoWork()
{
    LOG_INFO("Mail worker thread started");

    try {
        auto lastJobTime = std::chrono::high_resolution_clock::now();

        bool isMailQueueEmpty = false;
        Mail *mail = nullptr;
        Mail::SendCallback callback = nullptr;

        for (;;) {
            boost::this_thread::interruption_point();

            {
                boost::lock_guard<boost::mutex> lock(WorkerMutex);
                (void)lock;

                if (!WorkerThreadIsRunning)
                    break;
            }

            boost::this_thread::disable_interruption di;

            {
                boost::lock_guard<boost::mutex> lock(MailMutex);
                (void)lock;

                isMailQueueEmpty = !(MailQueue.size() > 0);

                if (!isMailQueueEmpty) {
                    mail = MailQueue.front();
                    callback = MailCallbackQueue.front();
                }
            }

            if (!isMailQueueEmpty) {
                string error;
                bool rc = mail->Send(error);
                if (callback != nullptr) {
                    callback(rc, error);
                }

                {
                    boost::lock_guard<boost::mutex> lock(MailMutex);
                    (void)lock;

                    MailQueue.pop();
                    MailCallbackQueue.pop();
                }

                if (mail->GetDeleteLater()) {
                    delete mail;
                }

                lastJobTime = std::chrono::high_resolution_clock::now();
            }

            boost::this_thread::restore_interruption ri(di);
            (void)ri;
            boost::this_thread::interruption_point();

            boost::this_thread::sleep_for(boost::chrono::nanoseconds(1));

            if (isMailQueueEmpty) {
                if ((std::chrono::duration<double, std::milli>(
                         std::chrono::high_resolution_clock::now() - lastJobTime)).count() // elapsed in milliseconds
                        > WORKER_THREAD_STOP_IDLE_MILLISECONDS) {
                    {
                        boost::lock_guard<boost::mutex> lock(WorkerMutex);
                        (void)lock;

                        WorkerThreadIsRunning = false;
                        break;
                    }
                }
            }
        }
    }

    catch (boost::exception &ex) {
        LOG_ERROR(boost::diagnostic_information(ex));
    }

    catch (std::exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (...) {
        LOG_ERROR(UNKNOWN_ERROR);
    }

    LOG_INFO("Mail worker thread stopped");
}

Mail::Mail()
    : m_pimpl(std::make_shared<Mail::Impl>())
{

}

Mail::Mail(const std::string &from, const std::string &to,
           const std::string &subject, const std::string &body,
           const std::vector<std::string> &attachments)
    : m_pimpl(std::make_shared<Mail::Impl>())
{
    m_pimpl->From = from;
    m_pimpl->To = to;
    m_pimpl->Subject = subject;
    m_pimpl->Body = body;
    SetAttachments(attachments);
}

Mail::~Mail() = default;

std::string Mail::GetFrom()
{
    return m_pimpl->From;
}

std::string Mail::GetTo()
{
    return m_pimpl->To;
}

std::string Mail::GetSubject()
{
    return m_pimpl->Subject;
}

std::string Mail::GetBody()
{
    return m_pimpl->Body;
}

const std::vector<std::string> &Mail::GetAttachments()
{
    return m_pimpl->Attachments;
}

void Mail::SetFrom(const std::string &from)
{
    m_pimpl->From = from;
}

void Mail::SetTo(const std::string &to)
{
    m_pimpl->To = to;
}

void Mail::SetSubject(const std::string &subject)
{
    m_pimpl->Subject = subject;
}

void Mail::SetBody(const std::string &body)
{
    m_pimpl->Body = body;
}

void Mail::SetAttachments(const std::vector<std::string> &attachments)
{
    m_pimpl->Attachments.clear();
    for (auto a : attachments) {
        m_pimpl->Attachments.push_back(a);
    }
}

bool Mail::GetDeleteLater() const
{
    return m_pimpl->DeleteLater;
}

void Mail::SetDeleteLater(const bool del) const
{
    m_pimpl->DeleteLater = del;
}

bool Mail::Send() const
{
    string err;
    return Send(err);
}

bool Mail::Send(std::string &out_error) const
{
    try {
#if defined (_WIN32)
        vmime::platform::setHandler<vmime::platforms::windows::windowsHandler>();
#else
        vmime::platform::setHandler<vmime::platforms::posix::posixHandler>();
#endif /* defined (_WIN32) */

        vmime::messageBuilder mb;

        mb.setExpeditor(vmime::mailbox(m_pimpl->From));
        mb.getRecipients().appendAddress(vmime::make_shared<vmime::mailbox>(m_pimpl->To));

        mb.setSubject(*vmime::text::newFromString(m_pimpl->Subject, vmime::charsets::UTF_8));

        mb.constructTextPart(vmime::mediaType(vmime::mediaTypes::TEXT, vmime::mediaTypes::TEXT_HTML));
        mb.getTextPart()->setCharset(vmime::charsets::UTF_8);
        mb.getTextPart()->setText(vmime::make_shared<vmime::stringContentHandler>(m_pimpl->Body));

        if (m_pimpl->Attachments.size() > 0) {
            for (auto a : m_pimpl->Attachments) {
                vmime::shared_ptr <vmime::attachment> att = vmime::make_shared <vmime::fileAttachment>
                        (a, vmime::mediaType("application/octet-stream"),
                         vmime::text(boost::filesystem::path(a).stem().string()));
                mb.appendAttachment(att);
            }
        }

        vmime::shared_ptr<vmime::message> msg = mb.construct();

        vmime::utility::url url("smtp://localhost");
#if VMIME_API_MODE == VMIME_LEGACY_API
        vmime::shared_ptr<vmime::net::session> sess = vmime::make_shared<vmime::net::session>();
#else
        vmime::shared_ptr<vmime::net::session> sess = vmime::net::session::create();
#endif  // VMIME_API_MODE == VMIME_LEGACY_API
        vmime::shared_ptr<vmime::net::transport> tr = sess->getTransport(url);

        tr->connect();
        tr->send(msg);
        tr->disconnect();

        return true;
    }

    catch (vmime::exception &ex) {
        out_error.assign(ex.what());
    }

    catch(std::exception &ex) {
        out_error.assign(ex.what());
    }

    catch (...) {
        out_error.assign(UNKNOWN_ERROR);
    }

    return false;
}

void Mail::SendAsync(const SendCallback callback)
{
    try {
        {
            boost::lock_guard<boost::mutex> lock(Impl::MailMutex);
            (void)lock;

            Impl::MailQueue.push(this);
            Impl::MailCallbackQueue.push(callback);
        }

        {
            boost::lock_guard<boost::mutex> lock(Impl::WorkerMutex);
            (void)lock;

            if (!Impl::WorkerThreadIsRunning) {
                Impl::WorkerThreadIsRunning = true;

                Impl::WorkerThread = make_unique<boost::thread>(Mail::Impl::DoWork);
                Impl::WorkerThread->detach();
            }
        }
    }

    catch (boost::exception &ex) {
        LOG_ERROR(boost::diagnostic_information(ex));
    }

    catch (std::exception &ex) {
        LOG_ERROR(ex.what());
    }

    catch (...) {
        LOG_ERROR(UNKNOWN_ERROR);
    }
}

Mail::Impl::Impl()
    : DeleteLater(false)
{

}

Mail::Impl::~Impl() = default;
<|endoftext|>


<commit_before>/**
 * @file Cosa/Periodic.hh
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2012, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 *
 * @section Description
 * Periodic function handler. Syntactic sugar for watchdog timeout
 * event handlers. Subclass and implement the virtual method run()
 * as the function to be executed periodically.
 *
 * @section Limitations
 * Avoid setting period to the same value in the run method as this
 * will force the function to be executed twice in the same time frame.
 *
 * @section See Also
 * For details on time period handling see Watchdog.hh. This execution
 * pattern is also available in the FSM (Finite State Machine) class.
 * See FSM.hh.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#ifndef __COSA_PERIODIC_HH__
#define __COSA_PERIODIC_HH__

#include "Cosa/Types.h"
#include "Cosa/Linkage.hh"
#include "Cosa/Watchdog.hh"

class Periodic : public Link {
private:
  /**
   * @override
   * Periodic event handler; dispatch the run() function on
   * timeout events.
   * @param[in] type the type of event.
   * @param[in] value the event value.
   */
  virtual void on_event(uint8_t type, uint16_t value)
  {
    if (type != Event::TIMEOUT_TYPE) return;
    run();
  }

public:
  /**
   * Construct a periodic function handler.
   * @param[in] ms period of timeout.
   */
  Periodic(uint16_t ms) :
    Link()
  {
    set_period(ms);
  }

  /**
   * Set timeout period.
   * @param[in] ms period of timeout.
   */
  void set_period(uint16_t ms)
  {
    Watchdog::attach(this, ms);
  }

  /**
   * The default null function.
   */
  virtual void run() {}
};

#endif
<commit_msg>Making Periodic an abstract class.<commit_after>/**
 * @file Cosa/Periodic.hh
 * @version 1.0
 *
 * @section License
 * Copyright (C) 2012-2013, Mikael Patel
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or (at your option) any later version.
 *
 * 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
 *
 * @section Description
 * Periodic function handler. Syntactic sugar for watchdog timeout
 * event handlers. Subclass and implement the virtual method run()
 * as the function to be executed periodically.
 *
 * @section Limitations
 * Avoid setting period to the same value in the run method as this
 * will force the function to be executed twice in the same time frame.
 *
 * @section See Also
 * For details on time period handling see Watchdog.hh. This execution
 * pattern is also available in the FSM (Finite State Machine) class.
 * See FSM.hh.
 *
 * This file is part of the Arduino Che Cosa project.
 */

#ifndef __COSA_PERIODIC_HH__
#define __COSA_PERIODIC_HH__

#include "Cosa/Types.h"
#include "Cosa/Linkage.hh"
#include "Cosa/Watchdog.hh"

class Periodic : public Link {
private:
  /**
   * @override
   * Periodic event handler; dispatch the run() function on
   * timeout events.
   * @param[in] type the type of event.
   * @param[in] value the event value.
   */
  virtual void on_event(uint8_t type, uint16_t value)
  {
    if (type != Event::TIMEOUT_TYPE) return;
    run();
  }

public:
  /**
   * Construct a periodic function handler.
   * @param[in] ms period of timeout.
   */
  Periodic(uint16_t ms) :
    Link()
  {
    set_period(ms);
  }

  /**
   * Set timeout period.
   * @param[in] ms period of timeout.
   */
  void set_period(uint16_t ms)
  {
    Watchdog::attach(this, ms);
  }

  /**
   * The default null function.
   */
  virtual void run() = 0;
};

#endif
<|endoftext|>


<commit_before>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/app_mode/kiosk_mode_idle_app_name_notification.h"

#include "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "chrome/browser/chromeos/ui/idle_app_name_notification_view.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_switches.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "components/user_manager/user_manager.h"
#include "extensions/browser/extension_system.h"
#include "ui/base/user_activity/user_activity_detector.h"

namespace chromeos {

namespace {

// The timeout in ms before the message shows up.
const int kIdleAppNameNotificationTimeoutMs = 2 * 60 * 1000;

// The duration of visibility for the message.
const int kMessageVisibilityTimeMs = 3000;

// The anomation time to show / hide the message.
const int kMessageAnimationTimeMs = 200;

// Our global instance of the Kiosk mode message.
KioskModeIdleAppNameNotification* g_kiosk_mode_idle_app_message = NULL;

}  // namespace

// static
void KioskModeIdleAppNameNotification::Initialize() {
  DCHECK(!g_kiosk_mode_idle_app_message);
  g_kiosk_mode_idle_app_message = new KioskModeIdleAppNameNotification();
}

// static
void KioskModeIdleAppNameNotification::Shutdown() {
  if (g_kiosk_mode_idle_app_message) {
    delete g_kiosk_mode_idle_app_message;
    g_kiosk_mode_idle_app_message = NULL;
  }
}

KioskModeIdleAppNameNotification::KioskModeIdleAppNameNotification()
    : show_notification_upon_next_user_activity_(false) {
  // Note: The timeout is currently fixed. If that changes we need to check if
  // the KioskModeSettings were already initialized.
  Setup();
}

KioskModeIdleAppNameNotification::~KioskModeIdleAppNameNotification() {
  ui::UserActivityDetector* user_activity_detector =
      ui::UserActivityDetector::Get();
  if (user_activity_detector && user_activity_detector->HasObserver(this)) {
    user_activity_detector->RemoveObserver(this);
    // At this time the DBusThreadManager might already be gone.
    if (chromeos::DBusThreadManager::IsInitialized())
      chromeos::DBusThreadManager::Get()->GetPowerManagerClient(
          )->RemoveObserver(this);
  }
}

void KioskModeIdleAppNameNotification::Setup() {
  DCHECK(user_manager::UserManager::Get()->IsUserLoggedIn());
  Start();
}

void KioskModeIdleAppNameNotification::OnUserActivity(const ui::Event* event) {
  if (show_notification_upon_next_user_activity_) {
    base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
    const std::string app_id =
        command_line->GetSwitchValueASCII(::switches::kAppId);
    Profile* profile = ProfileManager::GetActiveUserProfile();
    notification_.reset(
        new IdleAppNameNotificationView(
            kMessageVisibilityTimeMs,
            kMessageAnimationTimeMs,
            extensions::ExtensionSystem::Get(profile
                )->extension_service()->GetInstalledExtension(app_id)));
    show_notification_upon_next_user_activity_ = false;
  }
  ResetTimer();
}

void KioskModeIdleAppNameNotification::SuspendDone(
    const base::TimeDelta& sleep_duration) {
  // When we come back from a system resume we stop the timer and show the
  // message.
  timer_.Stop();
  OnTimeout();
}

void KioskModeIdleAppNameNotification::Start() {
  if (!ui::UserActivityDetector::Get()->HasObserver(this)) {
    ui::UserActivityDetector::Get()->AddObserver(this);
    chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(
        this);
  }
  ResetTimer();
}

void KioskModeIdleAppNameNotification::ResetTimer() {
  if (timer_.IsRunning()) {
    timer_.Reset();
  } else {
    // OneShotTimer destroys the posted task after running it, so Reset()
    // isn't safe to call on a timer that's already fired.
    timer_.Start(
        FROM_HERE,
        base::TimeDelta::FromMilliseconds(kIdleAppNameNotificationTimeoutMs),
        base::Bind(&KioskModeIdleAppNameNotification::OnTimeout,
                   base::Unretained(this)));
  }
}

void KioskModeIdleAppNameNotification::OnTimeout() {
  show_notification_upon_next_user_activity_ = true;
}

}  // namespace chromeos
<commit_msg>Disable return from idle notification on external displays and increase the idle timeout to 20 minutes.<commit_after>// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/chromeos/app_mode/kiosk_mode_idle_app_name_notification.h"

#include "ash/shell.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/logging.h"
#include "chrome/browser/chromeos/ui/idle_app_name_notification_view.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/common/chrome_switches.h"
#include "chromeos/dbus/dbus_thread_manager.h"
#include "components/user_manager/user_manager.h"
#include "extensions/browser/extension_system.h"
#include "ui/base/user_activity/user_activity_detector.h"
#include "ui/gfx/display.h"
#include "ui/gfx/screen.h"

namespace chromeos {

namespace {

// The timeout in ms before the message shows up.
const int kIdleAppNameNotificationTimeoutMs = 20 * 60 * 1000;

// The duration of visibility for the message.
const int kMessageVisibilityTimeMs = 3000;

// The anomation time to show / hide the message.
const int kMessageAnimationTimeMs = 200;

// Our global instance of the Kiosk mode message.
KioskModeIdleAppNameNotification* g_kiosk_mode_idle_app_message = NULL;

}  // namespace

// static
void KioskModeIdleAppNameNotification::Initialize() {
  DCHECK(!g_kiosk_mode_idle_app_message);
  g_kiosk_mode_idle_app_message = new KioskModeIdleAppNameNotification();
}

// static
void KioskModeIdleAppNameNotification::Shutdown() {
  if (g_kiosk_mode_idle_app_message) {
    delete g_kiosk_mode_idle_app_message;
    g_kiosk_mode_idle_app_message = NULL;
  }
}

KioskModeIdleAppNameNotification::KioskModeIdleAppNameNotification()
    : show_notification_upon_next_user_activity_(false) {
  // Note: The timeout is currently fixed. If that changes we need to check if
  // the KioskModeSettings were already initialized.
  Setup();
}

KioskModeIdleAppNameNotification::~KioskModeIdleAppNameNotification() {
  ui::UserActivityDetector* user_activity_detector =
      ui::UserActivityDetector::Get();
  if (user_activity_detector && user_activity_detector->HasObserver(this)) {
    user_activity_detector->RemoveObserver(this);
    // At this time the DBusThreadManager might already be gone.
    if (chromeos::DBusThreadManager::IsInitialized())
      chromeos::DBusThreadManager::Get()->GetPowerManagerClient(
          )->RemoveObserver(this);
  }
}

void KioskModeIdleAppNameNotification::Setup() {
  DCHECK(user_manager::UserManager::Get()->IsUserLoggedIn());
  Start();
}

void KioskModeIdleAppNameNotification::OnUserActivity(const ui::Event* event) {
  if (show_notification_upon_next_user_activity_) {
    gfx::Display display = ash::Shell::GetScreen()->GetPrimaryDisplay();
    // Display the notification only on internal display.
    if (display.IsInternal()) {
      base::CommandLine* command_line = base::CommandLine::ForCurrentProcess();
      const std::string app_id =
          command_line->GetSwitchValueASCII(::switches::kAppId);
      Profile* profile = ProfileManager::GetActiveUserProfile();
      notification_.reset(
          new IdleAppNameNotificationView(
              kMessageVisibilityTimeMs,
              kMessageAnimationTimeMs,
              extensions::ExtensionSystem::Get(profile
                  )->extension_service()->GetInstalledExtension(app_id)));
    }
    show_notification_upon_next_user_activity_ = false;
  }
  ResetTimer();
}

void KioskModeIdleAppNameNotification::SuspendDone(
    const base::TimeDelta& sleep_duration) {
  // When we come back from a system resume we stop the timer and show the
  // message.
  timer_.Stop();
  OnTimeout();
}

void KioskModeIdleAppNameNotification::Start() {
  if (!ui::UserActivityDetector::Get()->HasObserver(this)) {
    ui::UserActivityDetector::Get()->AddObserver(this);
    chromeos::DBusThreadManager::Get()->GetPowerManagerClient()->AddObserver(
        this);
  }
  ResetTimer();
}

void KioskModeIdleAppNameNotification::ResetTimer() {
  if (timer_.IsRunning()) {
    timer_.Reset();
  } else {
    // OneShotTimer destroys the posted task after running it, so Reset()
    // isn't safe to call on a timer that's already fired.
    timer_.Start(
        FROM_HERE,
        base::TimeDelta::FromMilliseconds(kIdleAppNameNotificationTimeoutMs),
        base::Bind(&KioskModeIdleAppNameNotification::OnTimeout,
                   base::Unretained(this)));
  }
}

void KioskModeIdleAppNameNotification::OnTimeout() {
  show_notification_upon_next_user_activity_ = true;
}

}  // namespace chromeos
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/cache/p9_hcd_cache_stopclocks.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,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_hcd_cache_stopclocks.H
/// @brief Quad Clock Stop
///

// *HWP HWP Owner          : David Du       <daviddu@us.ibm.com>
// *HWP Backup HWP Owner   : Greg Still     <stillgs@us.ibm.com>
// *HWP FW Owner           : Sangeetha T S  <sangeet2@in.ibm.com>
// *HWP Team               : PM
// *HWP Consumed by        : HB:PERV
// *HWP Level              : 2

#ifndef __P9_HCD_CACHE_STOPCLOCKS_H__
#define __P9_HCD_CACHE_STOPCLOCKS_H__

#include <fapi2.H>
#include <p9_hcd_common.H>

/// @typedef p9_hcd_cache_stopclocks_FP_t
/// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_hcd_cache_stopclocks_FP_t) (
    const fapi2::Target<fapi2::TARGET_TYPE_EQ>&,
    const p9hcd::P9_HCD_CLK_CTRL_CONSTANTS,
    const p9hcd::P9_HCD_EX_CTRL_CONSTANTS,
    const bool);

extern "C"
{

/// @brief Quad Clock Stop
/// @param [in] i_target TARGET_TYPE_EQ target
/// @param [in] i_select_regions select clk regions on stopclocks
/// @param [in] i_select_ex select ex's on stopclocks
/// @param [in] i_sync_stop_quad_clk to stop CACHE & CORE chiplet clocks synchronously
/// @return FAPI2_RC_SUCCESS if success, else error code
    fapi2::ReturnCode
    p9_hcd_cache_stopclocks(
        const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
        const p9hcd::P9_HCD_CLK_CTRL_CONSTANTS      i_select_regions,
        const p9hcd::P9_HCD_EX_CTRL_CONSTANTS       i_select_ex,
        const bool i_sync_stop_quad_clk = false);

}

#endif  // __P9_HCD_CACHE_STOPCLOCKS_H__
<commit_msg>L3 Update - p9_hcd_cache_stopclocks HWP<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/cache/p9_hcd_cache_stopclocks.H $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,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_hcd_cache_stopclocks.H
/// @brief Quad Clock Stop
///

// *HWP HWP Owner          : David Du       <daviddu@us.ibm.com>
// *HWP Backup HWP Owner   : Greg Still     <stillgs@us.ibm.com>
// *HWP FW Owner           : Amit Tendolkar <amit.tendolkar@in.ibm.com>
// *HWP Team               : PM
// *HWP Consumed by        : HB:PERV
// *HWP Level              : 3

#ifndef __P9_HCD_CACHE_STOPCLOCKS_H__
#define __P9_HCD_CACHE_STOPCLOCKS_H__

#include <fapi2.H>
#include <p9_hcd_common.H>

/// @typedef p9_hcd_cache_stopclocks_FP_t
/// function pointer typedef definition for HWP call support
typedef fapi2::ReturnCode (*p9_hcd_cache_stopclocks_FP_t) (
    const fapi2::Target<fapi2::TARGET_TYPE_EQ>&,
    const p9hcd::P9_HCD_CLK_CTRL_CONSTANTS,
    const p9hcd::P9_HCD_EX_CTRL_CONSTANTS,
    const bool);

extern "C"
{

/// @brief Quad Clock Stop
/// @param [in] i_target TARGET_TYPE_EQ target
/// @param [in] i_select_regions select clk regions on stopclocks
/// @param [in] i_select_ex select ex's on stopclocks
/// @param [in] i_sync_stop_quad_clk to stop CACHE & CORE chiplet clocks synchronously
/// @return FAPI2_RC_SUCCESS if success, else error code
    fapi2::ReturnCode
    p9_hcd_cache_stopclocks(
        const fapi2::Target<fapi2::TARGET_TYPE_EQ>& i_target,
        const p9hcd::P9_HCD_CLK_CTRL_CONSTANTS      i_select_regions,
        const p9hcd::P9_HCD_EX_CTRL_CONSTANTS       i_select_ex,
        const bool i_sync_stop_quad_clk = false);

}

#endif  // __P9_HCD_CACHE_STOPCLOCKS_H__
<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief X11 Platform.
 *//*--------------------------------------------------------------------*/

#include "tcuX11Platform.hpp"

#include "deUniquePtr.hpp"
#include "gluPlatform.hpp"
#include "vkPlatform.hpp"
#include "tcuX11.hpp"
#include "tcuFunctionLibrary.hpp"
#include "deMemory.h"

#if defined (DEQP_SUPPORT_GLX)
#	include "tcuX11GlxPlatform.hpp"
#endif
#if defined (DEQP_SUPPORT_EGL)
#	include "tcuX11EglPlatform.hpp"
#endif

#include <sys/utsname.h>

namespace tcu
{
namespace x11
{

class X11GLPlatform : public glu::Platform
{
public:
	void		registerFactory	(de::MovePtr<glu::ContextFactory> factory)
	{
		m_contextFactoryRegistry.registerFactory(factory.release());
	}
};

class VulkanLibrary : public vk::Library
{
public:
	VulkanLibrary (void)
		: m_library	("libvulkan.so.1")
		, m_driver	(m_library)
	{
	}

	const vk::PlatformInterface& getPlatformInterface (void) const
	{
		return m_driver;
	}

private:
	const tcu::DynamicFunctionLibrary	m_library;
	const vk::PlatformDriver			m_driver;
};

class X11VulkanPlatform : public vk::Platform
{
public:
	vk::Library* createLibrary (void) const
	{
		return new VulkanLibrary();
	}

	void describePlatform (std::ostream& dst) const
	{
		utsname		sysInfo;

		deMemset(&sysInfo, 0, sizeof(sysInfo));

		if (uname(&sysInfo) != 0)
			throw std::runtime_error("uname() failed");

		dst << "OS: " << sysInfo.sysname << " " << sysInfo.release << " " << sysInfo.version << "\n";
		dst << "CPU: " << sysInfo.machine << "\n";
	}

	void getMemoryLimits (vk::PlatformMemoryLimits& limits) const
	{
		limits.totalSystemMemory					= 256*1024*1024;
		limits.totalDeviceLocalMemory				= 128*1024*1024;
		limits.deviceMemoryAllocationGranularity	= 64*1024;
		limits.devicePageSize						= 4096;
		limits.devicePageTableEntrySize				= 8;
		limits.devicePageTableHierarchyLevels		= 3;
	}
};

class X11Platform : public tcu::Platform
{
public:
							X11Platform			(void);
	bool					processEvents		(void) { return !m_eventState.getQuitFlag(); }
	const glu::Platform&	getGLPlatform		(void) const { return m_glPlatform; }

#if defined (DEQP_SUPPORT_EGL)
	const eglu::Platform&	getEGLPlatform		(void) const { return m_eglPlatform; }
#endif // DEQP_SUPPORT_EGL

	const vk::Platform&		getVulkanPlatform	(void) const { return m_vkPlatform; }

private:
	EventState				m_eventState;
#if defined (DEQP_SUPPORT_EGL)
	x11::egl::Platform		m_eglPlatform;
#endif // DEQP_SPPORT_EGL
	X11GLPlatform			m_glPlatform;
	X11VulkanPlatform		m_vkPlatform;
};

X11Platform::X11Platform (void)
#if defined (DEQP_SUPPORT_EGL)
	: m_eglPlatform	(m_eventState)
#endif // DEQP_SUPPORT_EGL
{
#if defined (DEQP_SUPPORT_GLX)
	m_glPlatform.registerFactory(glx::createContextFactory(m_eventState));
#endif // DEQP_SUPPORT_GLX
#if defined (DEQP_SUPPORT_EGL)
	m_glPlatform.registerFactory(m_eglPlatform.createContextFactory());
#endif // DEQP_SUPPORT_EGL
}

} // x11
} // tcu

tcu::Platform* createPlatform (void)
{
	return new tcu::x11::X11Platform();
}
<commit_msg>x11: Call XInitThreads() am: 5d11c9d2c0 am: 0fe4efcfa8 am: 8c04df2e48 am: c6bf22467b<commit_after>/*-------------------------------------------------------------------------
 * drawElements Quality Program Tester Core
 * ----------------------------------------
 *
 * Copyright 2014 The Android Open Source Project
 *
 * 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.
 *
 *//*!
 * \file
 * \brief X11 Platform.
 *//*--------------------------------------------------------------------*/

#include "tcuX11Platform.hpp"

#include "deUniquePtr.hpp"
#include "gluPlatform.hpp"
#include "vkPlatform.hpp"
#include "tcuX11.hpp"
#include "tcuFunctionLibrary.hpp"
#include "deMemory.h"

#if defined (DEQP_SUPPORT_GLX)
#	include "tcuX11GlxPlatform.hpp"
#endif
#if defined (DEQP_SUPPORT_EGL)
#	include "tcuX11EglPlatform.hpp"
#endif

#include <sys/utsname.h>

namespace tcu
{
namespace x11
{

class X11GLPlatform : public glu::Platform
{
public:
	void		registerFactory	(de::MovePtr<glu::ContextFactory> factory)
	{
		m_contextFactoryRegistry.registerFactory(factory.release());
	}
};

class VulkanLibrary : public vk::Library
{
public:
	VulkanLibrary (void)
		: m_library	("libvulkan.so.1")
		, m_driver	(m_library)
	{
	}

	const vk::PlatformInterface& getPlatformInterface (void) const
	{
		return m_driver;
	}

private:
	const tcu::DynamicFunctionLibrary	m_library;
	const vk::PlatformDriver			m_driver;
};

class X11VulkanPlatform : public vk::Platform
{
public:
	vk::Library* createLibrary (void) const
	{
		return new VulkanLibrary();
	}

	void describePlatform (std::ostream& dst) const
	{
		utsname		sysInfo;

		deMemset(&sysInfo, 0, sizeof(sysInfo));

		if (uname(&sysInfo) != 0)
			throw std::runtime_error("uname() failed");

		dst << "OS: " << sysInfo.sysname << " " << sysInfo.release << " " << sysInfo.version << "\n";
		dst << "CPU: " << sysInfo.machine << "\n";
	}

	void getMemoryLimits (vk::PlatformMemoryLimits& limits) const
	{
		limits.totalSystemMemory					= 256*1024*1024;
		limits.totalDeviceLocalMemory				= 128*1024*1024;
		limits.deviceMemoryAllocationGranularity	= 64*1024;
		limits.devicePageSize						= 4096;
		limits.devicePageTableEntrySize				= 8;
		limits.devicePageTableHierarchyLevels		= 3;
	}
};

class X11Platform : public tcu::Platform
{
public:
							X11Platform			(void);
	bool					processEvents		(void) { return !m_eventState.getQuitFlag(); }
	const glu::Platform&	getGLPlatform		(void) const { return m_glPlatform; }

#if defined (DEQP_SUPPORT_EGL)
	const eglu::Platform&	getEGLPlatform		(void) const { return m_eglPlatform; }
#endif // DEQP_SUPPORT_EGL

	const vk::Platform&		getVulkanPlatform	(void) const { return m_vkPlatform; }

private:
	EventState				m_eventState;
#if defined (DEQP_SUPPORT_EGL)
	x11::egl::Platform		m_eglPlatform;
#endif // DEQP_SPPORT_EGL
	X11GLPlatform			m_glPlatform;
	X11VulkanPlatform		m_vkPlatform;
};

X11Platform::X11Platform (void)
#if defined (DEQP_SUPPORT_EGL)
	: m_eglPlatform	(m_eventState)
#endif // DEQP_SUPPORT_EGL
{
#if defined (DEQP_SUPPORT_GLX)
	m_glPlatform.registerFactory(glx::createContextFactory(m_eventState));
#endif // DEQP_SUPPORT_GLX
#if defined (DEQP_SUPPORT_EGL)
	m_glPlatform.registerFactory(m_eglPlatform.createContextFactory());
#endif // DEQP_SUPPORT_EGL
}

} // x11
} // tcu

tcu::Platform* createPlatform (void)
{
	// From man:XinitThreads(3):
	//
	//     The XInitThreads function initializes Xlib support for concurrent
	//     threads.  This function must be the first Xlib function
	//     a multi-threaded program calls, and it must complete before any other
	//     Xlib call is made.
	DE_CHECK_RUNTIME_ERR(XInitThreads() != 0);

	return new tcu::x11::X11Platform();
}
<|endoftext|>


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

  Program:   Visualization Toolkit
  Module:    vtkFrustumCoverageCuller.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * 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.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS 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 AUTHORS OR 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.

=========================================================================*/
#include "vtkFrustumCoverageCuller.h"
#include "vtkProp.h"
#include "vtkRenderer.h"
#include "vtkObjectFactory.h"

//------------------------------------------------------------------------------
vtkFrustumCoverageCuller* vtkFrustumCoverageCuller::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkFrustumCoverageCuller");
  if(ret)
    {
    return (vtkFrustumCoverageCuller*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkFrustumCoverageCuller;
}

// Create a frustum coverage culler with default values
vtkFrustumCoverageCuller::vtkFrustumCoverageCuller()
{
  this->MinimumCoverage = 0.0001;
  this->MaximumCoverage = 1.0;
  this->SortingStyle    = VTK_CULLER_SORT_NONE;
}

// The coverage is computed for each prop, and a resulting allocated
// render time is computed. This is multiplied by the current allocated
// render time of the prop. After this, props with no allocated time are
// removed from the list (and the list length is shortened) to make sure
// that they are not considered again by another culler or for rendering.
float vtkFrustumCoverageCuller::Cull( vtkRenderer *ren,
				      vtkProp **propList,
				      int& listLength,
				      int& initialized )
{
  vtkProp            *prop;
  float               total_time;
  float               *bounds, center[3];
  float               radius = 0.0;
  float               planes[24], d;
  float               coverage, screen_bounds[4];
  float               previous_time;
  int                 i, propLoop;
  float               full_w, full_h, part_w, part_h;
  float               *allocatedTimeList;
  float               *distanceList;
  int                 index1, index2;
  float               tmp;
  float               aspect[2];

  // We will create a center distance entry for each prop in the list
  // If SortingStyle is set to BackToFront or FrontToBack we will then
  // sort the props that have a non-zero AllocatedRenderTime by their
  // center distance
  distanceList = new float[listLength];

  // We will return the total time of all props. This is used for
  // normalization.
  total_time  = 0;

  ren->GetAspect( aspect );
  // Get the view frustum planes from the active camera
  ren->GetActiveCamera()->GetFrustumPlanes( (aspect[0] / aspect[1]), planes );

  // Keep a list of allocated times to help with sorting / removing
  // props later
  allocatedTimeList = new float[listLength];

  // For each prop, compute coverage
  for ( propLoop = 0; propLoop < listLength; propLoop++ )
    {
    // Get the prop out of the list
    prop = propList[propLoop];

    // If allocated render time has not been initialized yet (if this
    // is the first culler, it hasn't) then the previous time is set
    // to 0.0
    if ( !initialized )
      {
      previous_time = 1.0;
      }
    else
      {
      previous_time = prop->GetRenderTimeMultiplier();
      }

    // Get the bounds of the prop and compute an enclosing sphere
    bounds = prop->GetBounds();

    // We start with a coverage of 1.0 and set it to zero if the prop
    // is culled during the plane tests
    coverage = 1.0;
    // make sure the bounds are defined - they won't be for a 2D prop which
    // means that they will never be culled. Maybe this should be changed in
    // the future?
    if (bounds)
      {
      // a duff dataset like a polydata with no cells will have bad bounds
      if ((bounds[0] == -VTK_LARGE_FLOAT) || (bounds[0] == VTK_LARGE_FLOAT))
        {
	      coverage = 0.0;
	      i = 7;
        }
      else
        {
        center[0] = (bounds[0] + bounds[1]) / 2.0;
        center[1] = (bounds[2] + bounds[3]) / 2.0;
        center[2] = (bounds[4] + bounds[5]) / 2.0;
        radius = 0.5 * sqrt( (double)
			   ( bounds[1] - bounds[0] ) *
			   ( bounds[1] - bounds[0] ) +
			   ( bounds[3] - bounds[2] ) *
			   ( bounds[3] - bounds[2] ) +
			   ( bounds[5] - bounds[4] ) *
			   ( bounds[5] - bounds[4] ) );
        for ( i = 0; i < 6; i++ )
          {
          // Compute how far the center of the sphere is from this plane
          d =
          planes[i*4 + 0] * center[0] +
          planes[i*4 + 1] * center[1] +
          planes[i*4 + 2] * center[2] +
          planes[i*4 + 3];
          // If d < -radius the prop is not within the view frustum
	      if ( d < -radius )
	        {
	        coverage = 0.0;
	        i = 7;
	        }
        // The first four planes are the ones bounding the edges of the
        // view plane (the last two are the near and far planes) The
        // distance from the edge of the sphere to these planes is stored
        // to compute coverage.
        if ( i < 4 )
          {
            screen_bounds[i] = d - radius;
          }
	      // The fifth plane is the near plane - use the distance to
        // the center (d) as the value to sort by
	      if ( i == 4 )
	        {
	        distanceList[propLoop] = d;
	        }
        }
      }
      // If the prop wasn't culled during the plane tests...
      if ( coverage > 0.0 )
	      {
        // Compute the width and height of this slice through the
        // view frustum that contains the center of the sphere
	      full_w = screen_bounds[0] + screen_bounds[1] + 2.0 * radius;
	      full_h = screen_bounds[2] + screen_bounds[3] + 2.0 * radius;
        // Subtract from the full width to get the width of the square
        // enclosing the circle slice from the sphere in the plane
        // through the center of the sphere. If the screen bounds for
        // the left and right planes (0,1) are greater than zero, then
        // the edge of the sphere was a positive distance away from the
        // plane, so there is a gap between the edge of the plane and
        // the edge of the box.
        part_w = full_w;
        if ( screen_bounds[0] > 0.0 )
          {
          part_w -= screen_bounds[0];
          }
        if ( screen_bounds[1] > 0.0 )
          {
          part_w -= screen_bounds[1];
          }
        // Do the same thing for the height with the top and bottom
        // planes (2,3).
        part_h = full_h;
        if ( screen_bounds[2] > 0.0 )
          {
          part_h -= screen_bounds[2];
          }
        if ( screen_bounds[3] > 0.0 )
          {
          part_h -= screen_bounds[3];
          }

        // Compute the fraction of coverage
        coverage = (part_w * part_h) / (full_w * full_h);
        // Convert this to an allocated render time - coverage less than
        // the minumum result in 0.0 time, greater than the maximum result in
        // 1.0 time, and in between a linear ramp is used
        if ( coverage < this->MinimumCoverage )
          {
          coverage = 0;
          }
        else if ( coverage > this->MaximumCoverage )
          {
          coverage = 1.0;
          }
        else
          {
          coverage = (coverage-this->MinimumCoverage) /
          this->MaximumCoverage;
          }
        }
      }
    // This is a 2D prop - keep them at the beginning of the list in the same
    // order they came in (by giving them all the same distance) and set
    // the coverage to something small so that they won't get much
    // allocated render time (because they aren't LOD it doesn't matter,
    // and they generally do draw fast so you don't want to take too much
    // time away from the 3D prop because you added a title to your
    // window for example) They are put at the beginning of the list so
    // that when sorted back to front they will be rendered last.
    else
      {
      distanceList[propLoop] = -VTK_LARGE_FLOAT;
      coverage = 0.001;
      }
    // Multiply the new allocated time by the previous allocated time
    coverage *= previous_time;
    prop->SetRenderTimeMultiplier( coverage );

    // Save this in our array of allocated times which matches the
    // prop array. Also save the center distance
    allocatedTimeList[propLoop] = coverage;

    // Add the time for this prop to the total time
    total_time += coverage;
    }

  // Now traverse the list from the beginning, swapping any zero entries back
  // in the list, while preserving the order of the non-zero entries. This
  // requires two indices for the two items we are comparing at any step.
  // The second index always moves back by one, but the first index moves back
  // by one only when it is pointing to something that has a non-zero value.
  index1 = 0;
  for ( index2 = 1; index2 < listLength; index2++ )
    {
    if ( allocatedTimeList[index1] == 0.0 )
      {
      if ( allocatedTimeList[index2] != 0.0 )
        {
        allocatedTimeList[index1] = allocatedTimeList[index2];
        distanceList[index1]      = distanceList[index2];
        propList[index1]          = propList[index2];
        propList[index2]          = NULL;
        allocatedTimeList[index2] = 0.0;
        distanceList[index2]      = 0.0;
        }
      else
        {
        propList[index1]          = propList[index2]           = NULL;
        allocatedTimeList[index1] = allocatedTimeList[index2]  = 0.0;
        distanceList[index1]      = distanceList[index2]       = 0.0;
        }
      }
    if ( allocatedTimeList[index1] != 0.0 )
      {
      index1++;
      }
    }

  // Compute the new list length - index1 is always pointing to the
  // first 0.0 entry or the last entry if none were zero (in which case
  // we won't change the list length)
  listLength = (allocatedTimeList[index1] == 0.0)?(index1):listLength;

  // Now reorder the list if sorting is on
  // Do it by a simple bubble sort - there probably aren't that
  // many props....

  if ( this->SortingStyle == VTK_CULLER_SORT_FRONT_TO_BACK )
    {
    for ( propLoop = 1; propLoop < listLength; propLoop++ )
      {
      index1 = propLoop;
      while ( (index1 - 1) >= 0 &&
        distanceList[index1] < distanceList[index1-1] )
        {
        tmp = distanceList[index1-1];
        distanceList[index1-1] = distanceList[index1];
        distanceList[index1] = tmp;
        prop = propList[index1-1];
        propList[index1-1] = propList[index1];
        propList[index1] = prop;
        index1--;
        }
      }
    }
  if ( this->SortingStyle == VTK_CULLER_SORT_BACK_TO_FRONT )
    {
    for ( propLoop = 1; propLoop < listLength; propLoop++ )
      {
      index1 = propLoop;
      while ( (index1 - 1) >= 0 &&
        distanceList[index1] > distanceList[index1-1] )
        {
        tmp = distanceList[index1-1];
        distanceList[index1-1] = distanceList[index1];
        distanceList[index1] = tmp;
        prop = propList[index1-1];
        propList[index1-1] = propList[index1];
        propList[index1] = prop;
        index1--;
        }
      }
    }
  // The allocated render times are now initialized
  initialized = 1;
  delete [] allocatedTimeList;
  delete [] distanceList;
  return total_time;
}

// Description:
// Return the sorting style as a descriptive character string.
const char *vtkFrustumCoverageCuller::GetSortingStyleAsString(void)
{
  if( this->SortingStyle == VTK_CULLER_SORT_NONE )
    {
    return "None";
    }
  if( this->SortingStyle == VTK_CULLER_SORT_FRONT_TO_BACK )
    {
    return "Front To Back";
    }
  if( this->SortingStyle == VTK_CULLER_SORT_BACK_TO_FRONT )
    {
    return "Back To Front";
    }
  else
    {
    return "Unknown";
    }
}

void vtkFrustumCoverageCuller::PrintSelf(ostream& os, vtkIndent indent)
{
  this->vtkCuller::PrintSelf(os,indent);

  os << indent << "Minimum Coverage: "
     << this->MinimumCoverage << endl;

  os << indent << "Maximum Coverage: "
     << this->MaximumCoverage << endl;

  os << indent << "Sorting Style: "
     << this->GetSortingStyleAsString() << endl;

}
<commit_msg>ERR: Divide by zero when zooming lots<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkFrustumCoverageCuller.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

Copyright (c) 1993-2001 Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

 * Redistributions of source code must retain the above copyright notice,
   this list of conditions and the following disclaimer.

 * 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.

 * Neither name of Ken Martin, Will Schroeder, or Bill Lorensen nor the names
   of any contributors may be used to endorse or promote products derived
   from this software without specific prior written permission.

 * Modified source versions must be plainly marked as such, and must not be
   misrepresented as being the original software.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS ``AS IS''
AND ANY EXPRESS 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 AUTHORS OR 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.

=========================================================================*/
#include "vtkFrustumCoverageCuller.h"
#include "vtkProp.h"
#include "vtkRenderer.h"
#include "vtkObjectFactory.h"

//------------------------------------------------------------------------------
vtkFrustumCoverageCuller* vtkFrustumCoverageCuller::New()
{
  // First try to create the object from the vtkObjectFactory
  vtkObject* ret = vtkObjectFactory::CreateInstance("vtkFrustumCoverageCuller");
  if(ret)
    {
    return (vtkFrustumCoverageCuller*)ret;
    }
  // If the factory was unable to create the object, then create it here.
  return new vtkFrustumCoverageCuller;
}

// Create a frustum coverage culler with default values
vtkFrustumCoverageCuller::vtkFrustumCoverageCuller()
{
  this->MinimumCoverage = 0.0001;
  this->MaximumCoverage = 1.0;
  this->SortingStyle    = VTK_CULLER_SORT_NONE;
}

// The coverage is computed for each prop, and a resulting allocated
// render time is computed. This is multiplied by the current allocated
// render time of the prop. After this, props with no allocated time are
// removed from the list (and the list length is shortened) to make sure
// that they are not considered again by another culler or for rendering.
float vtkFrustumCoverageCuller::Cull( vtkRenderer *ren,
				      vtkProp **propList,
				      int& listLength,
				      int& initialized )
{
  vtkProp            *prop;
  float               total_time;
  float               *bounds, center[3];
  float               radius = 0.0;
  float               planes[24], d;
  float               coverage, screen_bounds[4];
  float               previous_time;
  int                 i, propLoop;
  float               full_w, full_h, part_w, part_h;
  float               *allocatedTimeList;
  float               *distanceList;
  int                 index1, index2;
  float               tmp;
  float               aspect[2];

  // We will create a center distance entry for each prop in the list
  // If SortingStyle is set to BackToFront or FrontToBack we will then
  // sort the props that have a non-zero AllocatedRenderTime by their
  // center distance
  distanceList = new float[listLength];

  // We will return the total time of all props. This is used for
  // normalization.
  total_time  = 0;

  ren->GetAspect( aspect );
  // Get the view frustum planes from the active camera
  ren->GetActiveCamera()->GetFrustumPlanes( (aspect[0] / aspect[1]), planes );

  // Keep a list of allocated times to help with sorting / removing
  // props later
  allocatedTimeList = new float[listLength];

  // For each prop, compute coverage
  for ( propLoop = 0; propLoop < listLength; propLoop++ )
    {
    // Get the prop out of the list
    prop = propList[propLoop];

    // If allocated render time has not been initialized yet (if this
    // is the first culler, it hasn't) then the previous time is set
    // to 0.0
    if ( !initialized )
      {
      previous_time = 1.0;
      }
    else
      {
      previous_time = prop->GetRenderTimeMultiplier();
      }

    // Get the bounds of the prop and compute an enclosing sphere
    bounds = prop->GetBounds();

    // We start with a coverage of 1.0 and set it to zero if the prop
    // is culled during the plane tests
    coverage = 1.0;
    // make sure the bounds are defined - they won't be for a 2D prop which
    // means that they will never be culled. Maybe this should be changed in
    // the future?
    if (bounds)
      {
      // a duff dataset like a polydata with no cells will have bad bounds
      if ((bounds[0] == -VTK_LARGE_FLOAT) || (bounds[0] == VTK_LARGE_FLOAT))
        {
	      coverage = 0.0;
	      i = 7;
        }
      else
        {
        center[0] = (bounds[0] + bounds[1]) / 2.0;
        center[1] = (bounds[2] + bounds[3]) / 2.0;
        center[2] = (bounds[4] + bounds[5]) / 2.0;
        radius = 0.5 * sqrt( (double)
			   ( bounds[1] - bounds[0] ) *
			   ( bounds[1] - bounds[0] ) +
			   ( bounds[3] - bounds[2] ) *
			   ( bounds[3] - bounds[2] ) +
			   ( bounds[5] - bounds[4] ) *
			   ( bounds[5] - bounds[4] ) );
        for ( i = 0; i < 6; i++ )
          {
          // Compute how far the center of the sphere is from this plane
          d =
          planes[i*4 + 0] * center[0] +
          planes[i*4 + 1] * center[1] +
          planes[i*4 + 2] * center[2] +
          planes[i*4 + 3];
          // If d < -radius the prop is not within the view frustum
	      if ( d < -radius )
	        {
	        coverage = 0.0;
	        i = 7;
	        }
        // The first four planes are the ones bounding the edges of the
        // view plane (the last two are the near and far planes) The
        // distance from the edge of the sphere to these planes is stored
        // to compute coverage.
        if ( i < 4 )
          {
            screen_bounds[i] = d - radius;
          }
	      // The fifth plane is the near plane - use the distance to
        // the center (d) as the value to sort by
	      if ( i == 4 )
	        {
	        distanceList[propLoop] = d;
	        }
        }
      }
      // If the prop wasn't culled during the plane tests...
      if ( coverage > 0.0 )
	      {
        // Compute the width and height of this slice through the
        // view frustum that contains the center of the sphere
	      full_w = screen_bounds[0] + screen_bounds[1] + 2.0 * radius;
	      full_h = screen_bounds[2] + screen_bounds[3] + 2.0 * radius;
        // Subtract from the full width to get the width of the square
        // enclosing the circle slice from the sphere in the plane
        // through the center of the sphere. If the screen bounds for
        // the left and right planes (0,1) are greater than zero, then
        // the edge of the sphere was a positive distance away from the
        // plane, so there is a gap between the edge of the plane and
        // the edge of the box.
        part_w = full_w;
        if ( screen_bounds[0] > 0.0 )
          {
          part_w -= screen_bounds[0];
          }
        if ( screen_bounds[1] > 0.0 )
          {
          part_w -= screen_bounds[1];
          }
        // Do the same thing for the height with the top and bottom
        // planes (2,3).
        part_h = full_h;
        if ( screen_bounds[2] > 0.0 )
          {
          part_h -= screen_bounds[2];
          }
        if ( screen_bounds[3] > 0.0 )
          {
          part_h -= screen_bounds[3];
          }

        // Compute the fraction of coverage
        if ((full_w * full_h)!=0.0)
          {
          coverage = (part_w * part_h) / (full_w * full_h);
          }
        else
          {
          coverage = 0;
          }
        // Convert this to an allocated render time - coverage less than
        // the minumum result in 0.0 time, greater than the maximum result in
        // 1.0 time, and in between a linear ramp is used
        if ( coverage < this->MinimumCoverage )
          {
          coverage = 0;
          }
        else if ( coverage > this->MaximumCoverage )
          {
          coverage = 1.0;
          }
        else
          {
          coverage = (coverage-this->MinimumCoverage) /
          this->MaximumCoverage;
          }
        }
      }
    // This is a 2D prop - keep them at the beginning of the list in the same
    // order they came in (by giving them all the same distance) and set
    // the coverage to something small so that they won't get much
    // allocated render time (because they aren't LOD it doesn't matter,
    // and they generally do draw fast so you don't want to take too much
    // time away from the 3D prop because you added a title to your
    // window for example) They are put at the beginning of the list so
    // that when sorted back to front they will be rendered last.
    else
      {
      distanceList[propLoop] = -VTK_LARGE_FLOAT;
      coverage = 0.001;
      }
    // Multiply the new allocated time by the previous allocated time
    coverage *= previous_time;
    prop->SetRenderTimeMultiplier( coverage );

    // Save this in our array of allocated times which matches the
    // prop array. Also save the center distance
    allocatedTimeList[propLoop] = coverage;

    // Add the time for this prop to the total time
    total_time += coverage;
    }

  // Now traverse the list from the beginning, swapping any zero entries back
  // in the list, while preserving the order of the non-zero entries. This
  // requires two indices for the two items we are comparing at any step.
  // The second index always moves back by one, but the first index moves back
  // by one only when it is pointing to something that has a non-zero value.
  index1 = 0;
  for ( index2 = 1; index2 < listLength; index2++ )
    {
    if ( allocatedTimeList[index1] == 0.0 )
      {
      if ( allocatedTimeList[index2] != 0.0 )
        {
        allocatedTimeList[index1] = allocatedTimeList[index2];
        distanceList[index1]      = distanceList[index2];
        propList[index1]          = propList[index2];
        propList[index2]          = NULL;
        allocatedTimeList[index2] = 0.0;
        distanceList[index2]      = 0.0;
        }
      else
        {
        propList[index1]          = propList[index2]           = NULL;
        allocatedTimeList[index1] = allocatedTimeList[index2]  = 0.0;
        distanceList[index1]      = distanceList[index2]       = 0.0;
        }
      }
    if ( allocatedTimeList[index1] != 0.0 )
      {
      index1++;
      }
    }

  // Compute the new list length - index1 is always pointing to the
  // first 0.0 entry or the last entry if none were zero (in which case
  // we won't change the list length)
  listLength = (allocatedTimeList[index1] == 0.0)?(index1):listLength;

  // Now reorder the list if sorting is on
  // Do it by a simple bubble sort - there probably aren't that
  // many props....

  if ( this->SortingStyle == VTK_CULLER_SORT_FRONT_TO_BACK )
    {
    for ( propLoop = 1; propLoop < listLength; propLoop++ )
      {
      index1 = propLoop;
      while ( (index1 - 1) >= 0 &&
        distanceList[index1] < distanceList[index1-1] )
        {
        tmp = distanceList[index1-1];
        distanceList[index1-1] = distanceList[index1];
        distanceList[index1] = tmp;
        prop = propList[index1-1];
        propList[index1-1] = propList[index1];
        propList[index1] = prop;
        index1--;
        }
      }
    }
  if ( this->SortingStyle == VTK_CULLER_SORT_BACK_TO_FRONT )
    {
    for ( propLoop = 1; propLoop < listLength; propLoop++ )
      {
      index1 = propLoop;
      while ( (index1 - 1) >= 0 &&
        distanceList[index1] > distanceList[index1-1] )
        {
        tmp = distanceList[index1-1];
        distanceList[index1-1] = distanceList[index1];
        distanceList[index1] = tmp;
        prop = propList[index1-1];
        propList[index1-1] = propList[index1];
        propList[index1] = prop;
        index1--;
        }
      }
    }
  // The allocated render times are now initialized
  initialized = 1;
  delete [] allocatedTimeList;
  delete [] distanceList;
  return total_time;
}

// Description:
// Return the sorting style as a descriptive character string.
const char *vtkFrustumCoverageCuller::GetSortingStyleAsString(void)
{
  if( this->SortingStyle == VTK_CULLER_SORT_NONE )
    {
    return "None";
    }
  if( this->SortingStyle == VTK_CULLER_SORT_FRONT_TO_BACK )
    {
    return "Front To Back";
    }
  if( this->SortingStyle == VTK_CULLER_SORT_BACK_TO_FRONT )
    {
    return "Back To Front";
    }
  else
    {
    return "Unknown";
    }
}

void vtkFrustumCoverageCuller::PrintSelf(ostream& os, vtkIndent indent)
{
  this->vtkCuller::PrintSelf(os,indent);

  os << indent << "Minimum Coverage: "
     << this->MinimumCoverage << endl;

  os << indent << "Maximum Coverage: "
     << this->MaximumCoverage << endl;

  os << indent << "Sorting Style: "
     << this->GetSortingStyleAsString() << endl;

}
<|endoftext|>