<commit_before>

#include <iostream>
#include <cstring>

#include "RTOSCListener.h"
#include "oscpack/osc/OscReceivedElements.h"
#include "oscpack/osc/OscPacketListener.h"
#include "oscpack/ip/UdpSocket.h"
#include "rtcmix_parse.h"

int parse_score_buffer(const char *buffer, int buflen);

void RTOSCListener::ProcessMessage(const osc::ReceivedMessage& m,
                              const IpEndpointName& remoteEndpoint){

    (void) remoteEndpoint; // suppress unused parameter warning

    int status;
    if(std::strcmp(m.AddressPattern(), "/RTcmix/ScoreCommands") == 0){
        osc::ReceivedMessageArgumentStream args = m.ArgumentStream();
        const char *rtScript;
        args >> rtScript >> osc::EndMessage;

        std::cout << rtScript << std::endl;

        status = parse_score_buffer(rtScript, std::strlen(rtScript));

    }
}

<commit_msg>Added print message on receiving script from osc server<commit_after>

#include <iostream>
#include <cstring>

#include "RTOSCListener.h"
#include "oscpack/osc/OscReceivedElements.h"
#include "oscpack/osc/OscPacketListener.h"
#include "oscpack/ip/UdpSocket.h"
#include "rtcmix_parse.h"

int parse_score_buffer(const char *buffer, int buflen);

void RTOSCListener::ProcessMessage(const osc::ReceivedMessage& m,
                              const IpEndpointName& remoteEndpoint){

    (void) remoteEndpoint; // suppress unused parameter warning

    int status;
    if(std::strcmp(m.AddressPattern(), "/RTcmix/ScoreCommands") == 0){
        osc::ReceivedMessageArgumentStream args = m.ArgumentStream();
        const char *rtScript;
        args >> rtScript >> osc::EndMessage;

        std::cout << "<<< OSC Server Recieved Script >>>" << std::endl;
        std::cout << rtScript << std::endl;

        status = parse_score_buffer(rtScript, std::strlen(rtScript));

    }
}

<|endoftext|>


<commit_before>// Copyright (c) 2012 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 "xwalk/application/common/application_manifest_constants.h"

namespace xwalk {

namespace application_manifest_keys {
const char kAppKey[] = "app";
const char kAppMainKey[] = "app.main";
const char kAppMainScriptsKey[] = "app.main.scripts";
const char kAppMainSourceKey[] = "app.main.source";
const char kCSPKey[] = "content_security_policy";
const char kDescriptionKey[] = "description";
const char kDisplay[] = "display";
const char kLaunchLocalPathKey[] = "app.launch.local_path";
const char kLaunchScreen[] = "launch_screen";
const char kLaunchScreenDefault[] = "launch_screen.default";
const char kLaunchScreenImageBorderDefault[] =
    "launch_screen.default.image_border";
const char kLaunchScreenImageBorderLandscape[] =
    "launch_screen.landscape.image_border";
const char kLaunchScreenImageBorderPortrait[] =
    "launch_screen.portrait.image_border";
const char kLaunchScreenLandscape[] = "launch_screen.landscape";
const char kLaunchScreenPortrait[] = "launch_screen.portrait";
const char kLaunchScreenReadyWhen[] = "launch_screen.ready_when";
const char kLaunchWebURLKey[] = "app.launch.web_url";
const char kManifestVersionKey[] = "manifest_version";
const char kNameKey[] = "name";
const char kPermissionsKey[] = "permissions";
const char kURLKey[] = "url";
const char kVersionKey[] = "version";
const char kWebURLsKey[] = "app.urls";
const char kXWalkHostsKey[] = "xwalk_hosts";

#if defined(OS_TIZEN)
const char kTizenAppIdKey[] = "tizen_app_id";
const char kIcon128Key[] = "icons.128";
#endif

}  // namespace application_manifest_keys

// manifest keys for widget applications.
namespace application_widget_keys {
const char kNamespaceKey[] = "@namespace";
const char kXmlLangKey[] = "@lang";
const char kDefaultLocaleKey[] = "widget.@defaultlocale";
const char kNameKey[] = "widget.name.#text";
const char kVersionKey[] = "widget.@version";
const char kWidgetKey[] = "widget";
const char kLaunchLocalPathKey[] = "widget.content.@src";
const char kWebURLsKey[] = "widget.@id";
const char kAuthorKey[] = "widget.author.#text";
const char kDescriptionKey[] = "widget.description.#text";
const char kShortNameKey[] = "widget.name.@short";
const char kIDKey[] = "widget.@id";
const char kAuthorEmailKey[] = "widget.author.@email";
const char kAuthorHrefKey[] = "widget.author.@href";
const char kHeightKey[] = "widget.@height";
const char kWidthKey[] = "widget.@width";
const char kPreferencesKey[] = "widget.preference";
const char kCSPKey[] = "widget.content-security-policy.#text";
const char kAccessKey[] = "widget.access";

// Child keys inside 'kPreferencesKey'.
const char kPreferencesNameKey[] = "@name";
const char kPreferencesValueKey[] = "@value";
const char kPreferencesReadonlyKey[] = "@readonly";

// Child keys inside 'kAccessKey'.
const char kAccessOriginKey[] = "@origin";
const char kAccessSubdomainsKey[] = "@subdomains";

#if defined(OS_TIZEN)
const char kIcon128Key[] = "widget.icon.@src";
const char kTizenApplicationKey[] = "widget.application";
// Child keys inside 'kTizenApplicationKey'
const char kTizenApplicationIdKey[] = "@id";
const char kTizenApplicationPackageKey[] = "@package";
const char kTizenApplicationRequiredVersionKey[] = "@required_version";

const char kTizenAppIdKey[] = "widget.application.@package";
const char kAllowNavigationKey[] = "widget.allow-navigation.#text";
const char kCSPReportOnlyKey[] =
    "widget.content-security-policy-report-only.#text";
const char kTizenSettingKey[] = "widget.setting";
const char kTizenHardwareKey[] = "widget.setting.@hwkey";
const char kTizenMetaDataKey[] = "widget.metadata";
// Child keys inside 'kTizenMetaDataKey'
const char kTizenMetaDataNameKey[] = "@key";
const char kTizenMetaDataValueKey[] = "@value";
#endif
}  // namespace application_widget_keys

#if defined(OS_TIZEN)
const char kTizenNamespacePrefix[] = "http://tizen.org/ns/widgets";
#endif

namespace application_manifest_errors {
const char kInvalidDescription[] =
    "Invalid value for 'description'.";
const char kInvalidKey[] =
    "Value 'key' is missing or invalid.";
const char kInvalidManifestVersion[] =
    "Invalid value for 'manifest_version'. Must be an integer greater than "
    "zero.";
const char kInvalidName[] =
    "Required value 'name' is missing or invalid.";
const char kInvalidVersion[] =
    "Required value 'version' is missing or invalid. It must be between 1-4 "
    "dot-separated integers each between 0 and 65536.";
const char kManifestParseError[] =
    "Manifest is not valid JSON.";
const char kManifestUnreadable[] =
    "Manifest file is missing or unreadable.";
const char kPlatformAppNeedsManifestVersion2[] =
    "Packaged apps need manifest_version set to >= 2";
}  // namespace application_manifest_errors

namespace application {

const char* GetNameKey(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kNameKey;

  return application_manifest_keys::kNameKey;
}

const char* GetVersionKey(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kVersionKey;

  return application_manifest_keys::kVersionKey;
}

const char* GetWebURLsKey(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kWebURLsKey;

  return application_manifest_keys::kWebURLsKey;
}

const char* GetLaunchLocalPathKey(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kLaunchLocalPathKey;

  return application_manifest_keys::kLaunchLocalPathKey;
}

const char* GetCSPKey(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kCSPKey;

  return application_manifest_keys::kCSPKey;
}

#if defined(OS_TIZEN)
const char* GetTizenAppIdKey(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kTizenAppIdKey;

  return application_manifest_keys::kTizenAppIdKey;
}

const char* GetIcon128Key(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kIcon128Key;

  return application_manifest_keys::kIcon128Key;
}
#endif
}  // namespace application
}  // namespace xwalk
<commit_msg>[Tizen][Runtime] Fix using the wrong attribute name for hardware key setting.<commit_after>// Copyright (c) 2012 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 "xwalk/application/common/application_manifest_constants.h"

namespace xwalk {

namespace application_manifest_keys {
const char kAppKey[] = "app";
const char kAppMainKey[] = "app.main";
const char kAppMainScriptsKey[] = "app.main.scripts";
const char kAppMainSourceKey[] = "app.main.source";
const char kCSPKey[] = "content_security_policy";
const char kDescriptionKey[] = "description";
const char kDisplay[] = "display";
const char kLaunchLocalPathKey[] = "app.launch.local_path";
const char kLaunchScreen[] = "launch_screen";
const char kLaunchScreenDefault[] = "launch_screen.default";
const char kLaunchScreenImageBorderDefault[] =
    "launch_screen.default.image_border";
const char kLaunchScreenImageBorderLandscape[] =
    "launch_screen.landscape.image_border";
const char kLaunchScreenImageBorderPortrait[] =
    "launch_screen.portrait.image_border";
const char kLaunchScreenLandscape[] = "launch_screen.landscape";
const char kLaunchScreenPortrait[] = "launch_screen.portrait";
const char kLaunchScreenReadyWhen[] = "launch_screen.ready_when";
const char kLaunchWebURLKey[] = "app.launch.web_url";
const char kManifestVersionKey[] = "manifest_version";
const char kNameKey[] = "name";
const char kPermissionsKey[] = "permissions";
const char kURLKey[] = "url";
const char kVersionKey[] = "version";
const char kWebURLsKey[] = "app.urls";
const char kXWalkHostsKey[] = "xwalk_hosts";

#if defined(OS_TIZEN)
const char kTizenAppIdKey[] = "tizen_app_id";
const char kIcon128Key[] = "icons.128";
#endif

}  // namespace application_manifest_keys

// manifest keys for widget applications.
namespace application_widget_keys {
const char kNamespaceKey[] = "@namespace";
const char kXmlLangKey[] = "@lang";
const char kDefaultLocaleKey[] = "widget.@defaultlocale";
const char kNameKey[] = "widget.name.#text";
const char kVersionKey[] = "widget.@version";
const char kWidgetKey[] = "widget";
const char kLaunchLocalPathKey[] = "widget.content.@src";
const char kWebURLsKey[] = "widget.@id";
const char kAuthorKey[] = "widget.author.#text";
const char kDescriptionKey[] = "widget.description.#text";
const char kShortNameKey[] = "widget.name.@short";
const char kIDKey[] = "widget.@id";
const char kAuthorEmailKey[] = "widget.author.@email";
const char kAuthorHrefKey[] = "widget.author.@href";
const char kHeightKey[] = "widget.@height";
const char kWidthKey[] = "widget.@width";
const char kPreferencesKey[] = "widget.preference";
const char kCSPKey[] = "widget.content-security-policy.#text";
const char kAccessKey[] = "widget.access";

// Child keys inside 'kPreferencesKey'.
const char kPreferencesNameKey[] = "@name";
const char kPreferencesValueKey[] = "@value";
const char kPreferencesReadonlyKey[] = "@readonly";

// Child keys inside 'kAccessKey'.
const char kAccessOriginKey[] = "@origin";
const char kAccessSubdomainsKey[] = "@subdomains";

#if defined(OS_TIZEN)
const char kIcon128Key[] = "widget.icon.@src";
const char kTizenApplicationKey[] = "widget.application";
// Child keys inside 'kTizenApplicationKey'
const char kTizenApplicationIdKey[] = "@id";
const char kTizenApplicationPackageKey[] = "@package";
const char kTizenApplicationRequiredVersionKey[] = "@required_version";

const char kTizenAppIdKey[] = "widget.application.@package";
const char kAllowNavigationKey[] = "widget.allow-navigation.#text";
const char kCSPReportOnlyKey[] =
    "widget.content-security-policy-report-only.#text";
const char kTizenSettingKey[] = "widget.setting";
const char kTizenHardwareKey[] = "widget.setting.@hwkey-event";
const char kTizenMetaDataKey[] = "widget.metadata";
// Child keys inside 'kTizenMetaDataKey'
const char kTizenMetaDataNameKey[] = "@key";
const char kTizenMetaDataValueKey[] = "@value";
#endif
}  // namespace application_widget_keys

#if defined(OS_TIZEN)
const char kTizenNamespacePrefix[] = "http://tizen.org/ns/widgets";
#endif

namespace application_manifest_errors {
const char kInvalidDescription[] =
    "Invalid value for 'description'.";
const char kInvalidKey[] =
    "Value 'key' is missing or invalid.";
const char kInvalidManifestVersion[] =
    "Invalid value for 'manifest_version'. Must be an integer greater than "
    "zero.";
const char kInvalidName[] =
    "Required value 'name' is missing or invalid.";
const char kInvalidVersion[] =
    "Required value 'version' is missing or invalid. It must be between 1-4 "
    "dot-separated integers each between 0 and 65536.";
const char kManifestParseError[] =
    "Manifest is not valid JSON.";
const char kManifestUnreadable[] =
    "Manifest file is missing or unreadable.";
const char kPlatformAppNeedsManifestVersion2[] =
    "Packaged apps need manifest_version set to >= 2";
}  // namespace application_manifest_errors

namespace application {

const char* GetNameKey(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kNameKey;

  return application_manifest_keys::kNameKey;
}

const char* GetVersionKey(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kVersionKey;

  return application_manifest_keys::kVersionKey;
}

const char* GetWebURLsKey(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kWebURLsKey;

  return application_manifest_keys::kWebURLsKey;
}

const char* GetLaunchLocalPathKey(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kLaunchLocalPathKey;

  return application_manifest_keys::kLaunchLocalPathKey;
}

const char* GetCSPKey(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kCSPKey;

  return application_manifest_keys::kCSPKey;
}

#if defined(OS_TIZEN)
const char* GetTizenAppIdKey(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kTizenAppIdKey;

  return application_manifest_keys::kTizenAppIdKey;
}

const char* GetIcon128Key(Manifest::PackageType package_type) {
  if (package_type == Manifest::TYPE_WGT)
    return application_widget_keys::kIcon128Key;

  return application_manifest_keys::kIcon128Key;
}
#endif
}  // namespace application
}  // namespace xwalk
<|endoftext|>


<commit_before>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/

#include <OpenThreads/ScopedLock>
#include <osg/ImageSequence>
#include <osg/Notify>
#include <osg/Camera>
#include <osg/NodeVisitor>
#include <osg/Texture2D>

#include <math.h>

using namespace osg;

void ImageSequence::UpdateCallback::operator () (osg::StateAttribute* attr, osg::NodeVisitor* nv)
{
    osg::Texture* texture = attr ? attr->asTexture() : 0;

    // osg::notify(osg::NOTICE)<<"ImageSequence::UpdateCallback::"<<texture<<std::endl;
    if (texture)
    {
        for(unsigned int i=0; i<texture->getNumImages(); ++i)
        {
            texture->getImage(i)->update(nv);
        }
    }
}

ImageSequence::ImageSequence()
{
    _referenceTime = DBL_MAX;
    _timeMultiplier = 1.0;

    _mode = PRE_LOAD_ALL_IMAGES;
    _length = 1.0;
    _timePerImage = 1.0;

    _fileNamesIterator = _fileNames.end();
    _fileNamesIteratorTime = 0.0;

    _imageIterator = _images.end();
    _imageIteratorTime = 0.0;

    _seekTime = 0.0;
    _seekTimeSet = false;
}

ImageSequence::ImageSequence(const ImageSequence& is,const CopyOp& copyop):
    osg::ImageStream(is,copyop),
    _referenceTime(is._referenceTime),
    _timeMultiplier(is._timeMultiplier),
    _mode(is._mode),
    _length(is._length),
    _timePerImage(is._timePerImage)
{
    _fileNamesIterator = _fileNames.end();
    _fileNamesIteratorTime = 0.0;

    _imageIterator = _images.end();
    _imageIteratorTime = 0.0;

    _seekTime = is._seekTime;
    _seekTimeSet = is._seekTimeSet;
}

int ImageSequence::compare(const Image& rhs) const
{
    return ImageStream::compare(rhs);
}

void ImageSequence::seek(double time)
{
    _seekTime = time;
    _seekTimeSet = true;
}

void ImageSequence::play()
{
    _status=PLAYING;
}

void ImageSequence::pause()
{
    _status=PAUSED;
}

void ImageSequence::rewind()
{
    seek(0.0f);
}

void ImageSequence::setMode(Mode mode)
{
    _mode = mode;
}

void ImageSequence::setLength(double length)
{
    _length = length;
    computeTimePerImage();
}

void ImageSequence::computeTimePerImage()
{
    if (!_fileNames.empty()) _timePerImage = _length / double(_fileNames.size());
    else if (!_images.empty()) _timePerImage = _length / double(_images.size());
    else _timePerImage = _length;
}

void ImageSequence::addImageFile(const std::string& fileName)
{
    OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
    _fileNames.push_back(fileName);
    computeTimePerImage();

    if (_fileNamesIterator==_fileNames.end())
    {
        _fileNamesIterator = _fileNames.begin();
        _fileNamesIteratorTime = _referenceTime;
    }
}

void ImageSequence::addImage(osg::Image* image)
{
    OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);

    if (!_filesRequested.empty())
    {
        // follows is a mechanism that ensures that requested images
        // get merged in the correct time order.
        if (_filesRequested.front().first != image->getFileName())
        {
            for(FileNameImageList::iterator itr = _filesRequested.begin();
                itr != _filesRequested.end();
                ++itr)
            {
                if (itr->first == image->getFileName())
                {
                    osg::notify(osg::NOTICE)<<"inserting image into waiting stake : "<<image->getFileName()<<std::endl;
                    itr->second = image;
                    return;
                }
            }
            // osg::notify(osg::NOTICE)<<"image not expected : "<<image->getFileName()<<std::endl;
            _images.push_back(image);
        }
        else
        {
            // osg::notify(osg::NOTICE)<<"merging image in order expected : "<<image->getFileName()<<std::endl;
            _images.push_back(image);

            _filesRequested.pop_front();

            FileNameImageList::iterator itr;
            for(itr = _filesRequested.begin();
                itr != _filesRequested.end() && itr->second.valid();
                ++itr)
            {
                // osg::notify(osg::NOTICE)<<"   merging previously loaded, but out of order file : "<<itr->first<<std::endl;
                _images.push_back(itr->second);
            }

            _filesRequested.erase(_filesRequested.begin(), itr);
        }
    }
    else
    {
        _images.push_back(image);
    }

    computeTimePerImage();

    if (data()==0)
    {
        _imageIterator = _images.begin();
        _imageIteratorTime = 0.0;
        setImageToChild(_imageIterator->get());
    }
}

void ImageSequence::setImageToChild(const osg::Image* image)
{
    // osg::notify(osg::NOTICE)<<"setImageToChild("<<image<<")"<<std::endl;

    if (image==0) return;

    setImage(image->s(),image->t(),image->r(),
             image->getInternalTextureFormat(),
             image->getPixelFormat(),image->getDataType(),
             const_cast<unsigned char*>(image->data()),
             osg::Image::NO_DELETE,
             image->getPacking());
}

void ImageSequence::update(osg::NodeVisitor* nv)
{
    OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);

    osg::NodeVisitor::ImageRequestHandler* irh = nv->getImageRequestHandler();
    const osg::FrameStamp* fs = nv->getFrameStamp();

    // osg::notify(osg::NOTICE)<<"ImageSequence::update("<<fs<<", "<<irh<<")"<<std::endl;

    if (_referenceTime == DBL_MAX)
    {
        _referenceTime = fs->getSimulationTime();
    }

    bool looping = getLoopingMode()==LOOPING;
    double time = (fs->getSimulationTime() - _referenceTime)*_timeMultiplier;

    if (_seekTimeSet || _status==PAUSED || _status==INVALID)
    {
        time = _seekTime;
        _referenceTime =  fs->getSimulationTime() - time/_timeMultiplier;
    }

    if (time>_length)
    {
        time -= floor(time/_length)*_length;
    }

    _seekTime = time;
    _seekTimeSet = false;

    FileNames::iterator previous_fileNamesIterator = _fileNamesIterator;
    Images::iterator previous_imageIterator = _imageIterator;

    bool pruneOldImages = false;

    switch(_mode)
    {
        case(PRE_LOAD_ALL_IMAGES):
        {
            if (_fileNames.size()>_images.size())
            {
                FileNames::iterator itr = _fileNames.begin();
                for(unsigned int i=0;i<_images.size();++i) ++itr;

                for(; itr!=_fileNames.end(); ++itr)
                {
                    osg::Image* image = irh->readImageFile(*itr);
                    _images.push_back(image);
                }
            }

            irh = 0;
            break;
        }
        case(PAGE_AND_RETAIN_IMAGES):
        {
            break;
        }
        case(PAGE_AND_DISCARD_USED_IMAGES):
        {
            pruneOldImages = true;
            break;
        }
    }

    // osg::notify(osg::NOTICE)<<"time = "<<time<<std::endl;

    if (irh && _images.size()<_fileNames.size())
    {
        double preLoadTime = time + osg::minimum(irh->getPreLoadTime()*_timeMultiplier, _length);

        if (preLoadTime>=_length)
        {
            //
            // Advance fileNameIterator to end and wrap around
            //
            for(;
                _fileNamesIterator != _fileNames.end();
                ++_fileNamesIterator)
            {
                _fileNamesIteratorTime += _timePerImage;

                double effectTime = fs->getSimulationTime() + (preLoadTime - _fileNamesIteratorTime);
                _filesRequested.push_back(FileNameImagePair(*_fileNamesIterator,0));
                irh->requestImageFile(*_fileNamesIterator, this, effectTime, fs);

            }

            preLoadTime -= _length;

            if (looping)
            {
                _fileNamesIterator = _fileNames.begin();
                _fileNamesIteratorTime = 0.0;
            }
        }

        if (_fileNamesIterator!=_fileNames.end())
        {
            //
            // Advance fileNameIterator to encmpass preLoadTime
            //

            //osg::notify(osg::NOTICE)<<"   _fileNamesIteratorTime = "<<_fileNamesIteratorTime<<" "<<_timePerImage<<std::endl;
            while(preLoadTime > (_fileNamesIteratorTime + _timePerImage))
            {
                _fileNamesIteratorTime += _timePerImage;
                //osg::notify(osg::NOTICE)<<"   _fileNamesIteratorTime = "<<_fileNamesIteratorTime<<std::endl;
                //osg::notify(osg::NOTICE)<<"   need to preLoad = "<<*_fileNamesIterator<<std::endl;
                ++_fileNamesIterator;

                if (previous_fileNamesIterator==_fileNamesIterator) break;

                if (_fileNamesIterator ==_fileNames.end())
                {
                    // return iterator to begining of set.
                    if (looping) _fileNamesIterator = _fileNames.begin();
                    else break;
                }

                double effectTime = fs->getSimulationTime() + (preLoadTime - _fileNamesIteratorTime);
                _filesRequested.push_back(FileNameImagePair(*_fileNamesIterator,0));
                irh->requestImageFile(*_fileNamesIterator, this, effectTime, fs);
            }
        }

        if (looping && _fileNamesIterator==_fileNames.end())
        {
            _fileNamesIterator = _fileNames.begin();
            _fileNamesIteratorTime = 0.0;
        }
    }

    {
        //
        // Advance imageIterator
        //

        if (time<_imageIteratorTime)
        {
            _imageIterator = _images.begin();
            _imageIteratorTime = 0.0;
        }

        if (_imageIterator!=_images.end())
        {
            // osg::notify(osg::NOTICE)<<"   _imageIteratorTime = "<<_imageIteratorTime<<std::endl;
            while(time > (_imageIteratorTime + _timePerImage))
            {
                _imageIteratorTime += _timePerImage;
                // osg::notify(osg::NOTICE)<<"   _imageIteratorTime = "<<_imageIteratorTime<<std::endl;
                ++_imageIterator;

                if (_imageIterator ==_images.end())
                {

                    if (pruneOldImages)
                    {
                        _images.erase(previous_imageIterator, _imageIterator);
                        previous_imageIterator = _images.begin();
                    }

                    if (looping)
                    {
                        // return iterator to begining of set.
                        _imageIterator = _images.begin();
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        if (looping && _imageIterator==_images.end())
        {
            _imageIterator = _images.begin();
        }
    }

    if (_imageIterator!=_images.end() && previous_imageIterator != _imageIterator)
    {
        if (pruneOldImages)
        {
            _images.erase(previous_imageIterator, _imageIterator);
        }

        setImageToChild(_imageIterator->get());
    }
}
<commit_msg>Fix for when looping is is disabled<commit_after>/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield
 *
 * This library is open source and may be redistributed and/or modified under
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 *
 * 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
 * OpenSceneGraph Public License for more details.
*/

#include <OpenThreads/ScopedLock>
#include <osg/ImageSequence>
#include <osg/Notify>
#include <osg/Camera>
#include <osg/NodeVisitor>
#include <osg/Texture2D>

#include <math.h>

using namespace osg;

void ImageSequence::UpdateCallback::operator () (osg::StateAttribute* attr, osg::NodeVisitor* nv)
{
    osg::Texture* texture = attr ? attr->asTexture() : 0;

    // osg::notify(osg::NOTICE)<<"ImageSequence::UpdateCallback::"<<texture<<std::endl;
    if (texture)
    {
        for(unsigned int i=0; i<texture->getNumImages(); ++i)
        {
            texture->getImage(i)->update(nv);
        }
    }
}

ImageSequence::ImageSequence()
{
    _referenceTime = DBL_MAX;
    _timeMultiplier = 1.0;

    _mode = PRE_LOAD_ALL_IMAGES;
    _length = 1.0;
    _timePerImage = 1.0;

    _fileNamesIterator = _fileNames.end();
    _fileNamesIteratorTime = 0.0;

    _imageIterator = _images.end();
    _imageIteratorTime = 0.0;

    _seekTime = 0.0;
    _seekTimeSet = false;
}

ImageSequence::ImageSequence(const ImageSequence& is,const CopyOp& copyop):
    osg::ImageStream(is,copyop),
    _referenceTime(is._referenceTime),
    _timeMultiplier(is._timeMultiplier),
    _mode(is._mode),
    _length(is._length),
    _timePerImage(is._timePerImage)
{
    _fileNamesIterator = _fileNames.end();
    _fileNamesIteratorTime = 0.0;

    _imageIterator = _images.end();
    _imageIteratorTime = 0.0;

    _seekTime = is._seekTime;
    _seekTimeSet = is._seekTimeSet;
}

int ImageSequence::compare(const Image& rhs) const
{
    return ImageStream::compare(rhs);
}

void ImageSequence::seek(double time)
{
    _seekTime = time;
    _seekTimeSet = true;
}

void ImageSequence::play()
{
    _status=PLAYING;
}

void ImageSequence::pause()
{
    _status=PAUSED;
}

void ImageSequence::rewind()
{
    seek(0.0f);
}

void ImageSequence::setMode(Mode mode)
{
    _mode = mode;
}

void ImageSequence::setLength(double length)
{
    _length = length;
    computeTimePerImage();
}

void ImageSequence::computeTimePerImage()
{
    if (!_fileNames.empty()) _timePerImage = _length / double(_fileNames.size());
    else if (!_images.empty()) _timePerImage = _length / double(_images.size());
    else _timePerImage = _length;
}

void ImageSequence::addImageFile(const std::string& fileName)
{
    OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);
    _fileNames.push_back(fileName);
    computeTimePerImage();

    if (_fileNamesIterator==_fileNames.end())
    {
        _fileNamesIterator = _fileNames.begin();
        _fileNamesIteratorTime = _referenceTime;
    }
}

void ImageSequence::addImage(osg::Image* image)
{
    OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);

    if (!_filesRequested.empty())
    {
        // follows is a mechanism that ensures that requested images
        // get merged in the correct time order.
        if (_filesRequested.front().first != image->getFileName())
        {
            for(FileNameImageList::iterator itr = _filesRequested.begin();
                itr != _filesRequested.end();
                ++itr)
            {
                if (itr->first == image->getFileName())
                {
                    osg::notify(osg::NOTICE)<<"inserting image into waiting stake : "<<image->getFileName()<<std::endl;
                    itr->second = image;
                    return;
                }
            }
            // osg::notify(osg::NOTICE)<<"image not expected : "<<image->getFileName()<<std::endl;
            _images.push_back(image);
        }
        else
        {
            // osg::notify(osg::NOTICE)<<"merging image in order expected : "<<image->getFileName()<<std::endl;
            _images.push_back(image);

            _filesRequested.pop_front();

            FileNameImageList::iterator itr;
            for(itr = _filesRequested.begin();
                itr != _filesRequested.end() && itr->second.valid();
                ++itr)
            {
                // osg::notify(osg::NOTICE)<<"   merging previously loaded, but out of order file : "<<itr->first<<std::endl;
                _images.push_back(itr->second);
            }

            _filesRequested.erase(_filesRequested.begin(), itr);
        }
    }
    else
    {
        _images.push_back(image);
    }

    computeTimePerImage();

    if (data()==0)
    {
        _imageIterator = _images.begin();
        _imageIteratorTime = 0.0;
        setImageToChild(_imageIterator->get());
    }
}

void ImageSequence::setImageToChild(const osg::Image* image)
{
    // osg::notify(osg::NOTICE)<<"setImageToChild("<<image<<")"<<std::endl;

    if (image==0) return;

    setImage(image->s(),image->t(),image->r(),
             image->getInternalTextureFormat(),
             image->getPixelFormat(),image->getDataType(),
             const_cast<unsigned char*>(image->data()),
             osg::Image::NO_DELETE,
             image->getPacking());
}

void ImageSequence::update(osg::NodeVisitor* nv)
{
    OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);

    osg::NodeVisitor::ImageRequestHandler* irh = nv->getImageRequestHandler();
    const osg::FrameStamp* fs = nv->getFrameStamp();

    // osg::notify(osg::NOTICE)<<"ImageSequence::update("<<fs<<", "<<irh<<")"<<std::endl;

    if (_referenceTime == DBL_MAX)
    {
        _referenceTime = fs->getSimulationTime();
    }

    bool looping = getLoopingMode()==LOOPING;
    double time = (fs->getSimulationTime() - _referenceTime)*_timeMultiplier;

    if (_seekTimeSet || _status==PAUSED || _status==INVALID)
    {
        time = _seekTime;
        _referenceTime =  fs->getSimulationTime() - time/_timeMultiplier;
    }

    if (time>_length)
    {
        time -= floor(time/_length)*_length;
    }

    _seekTime = time;
//    _seekTimeSet = false;

    FileNames::iterator previous_fileNamesIterator = _fileNamesIterator;
    Images::iterator previous_imageIterator = _imageIterator;

    bool pruneOldImages = false;

    switch(_mode)
    {
        case(PRE_LOAD_ALL_IMAGES):
        {
            if (_fileNames.size()>_images.size())
            {
                FileNames::iterator itr = _fileNames.begin();
                for(unsigned int i=0;i<_images.size();++i) ++itr;

                for(; itr!=_fileNames.end(); ++itr)
                {
                    osg::Image* image = irh->readImageFile(*itr);
                    _images.push_back(image);
                }
            }

            irh = 0;
            break;
        }
        case(PAGE_AND_RETAIN_IMAGES):
        {
            break;
        }
        case(PAGE_AND_DISCARD_USED_IMAGES):
        {
            pruneOldImages = true;
            break;
        }
    }

    // osg::notify(osg::NOTICE)<<"time = "<<time<<std::endl;

    if (irh && _images.size()<_fileNames.size())
    {
        double preLoadTime = time + osg::minimum(irh->getPreLoadTime()*_timeMultiplier, _length);

        if (preLoadTime>=_length)
        {
            //
            // Advance fileNameIterator to end and wrap around
            //
            for(;
                _fileNamesIterator != _fileNames.end();
                ++_fileNamesIterator)
            {
                _fileNamesIteratorTime += _timePerImage;

                double effectTime = fs->getSimulationTime() + (preLoadTime - _fileNamesIteratorTime);
                _filesRequested.push_back(FileNameImagePair(*_fileNamesIterator,0));
                irh->requestImageFile(*_fileNamesIterator, this, effectTime, fs);

            }

            preLoadTime -= _length;

            if (looping)
            {
                _fileNamesIterator = _fileNames.begin();
                _fileNamesIteratorTime = 0.0;
            }
        }

        if (_fileNamesIterator!=_fileNames.end())
        {
            //
            // Advance fileNameIterator to encmpass preLoadTime
            //

            //osg::notify(osg::NOTICE)<<"   _fileNamesIteratorTime = "<<_fileNamesIteratorTime<<" "<<_timePerImage<<std::endl;
            while(preLoadTime > (_fileNamesIteratorTime + _timePerImage))
            {
                _fileNamesIteratorTime += _timePerImage;
                //osg::notify(osg::NOTICE)<<"   _fileNamesIteratorTime = "<<_fileNamesIteratorTime<<std::endl;
                //osg::notify(osg::NOTICE)<<"   need to preLoad = "<<*_fileNamesIterator<<std::endl;
                ++_fileNamesIterator;

                if (previous_fileNamesIterator==_fileNamesIterator) break;

                if (_fileNamesIterator ==_fileNames.end())
                {
                    // return iterator to begining of set.
                    if (looping) _fileNamesIterator = _fileNames.begin();
                    else break;
                }

                double effectTime = fs->getSimulationTime() + (preLoadTime - _fileNamesIteratorTime);
                _filesRequested.push_back(FileNameImagePair(*_fileNamesIterator,0));
                irh->requestImageFile(*_fileNamesIterator, this, effectTime, fs);
            }
        }

        if (looping && _fileNamesIterator==_fileNames.end())
        {
            _fileNamesIterator = _fileNames.begin();
            _fileNamesIteratorTime = 0.0;
        }
    }

    {
        //
        // Advance imageIterator
        //

        if ((looping || _seekTimeSet) && time<_imageIteratorTime)
        {
            _imageIterator = _images.begin();
            _imageIteratorTime = 0.0;
        }

        if (_imageIterator!=_images.end())
        {
            // osg::notify(osg::NOTICE)<<"   _imageIteratorTime = "<<_imageIteratorTime<<std::endl;
            while(time > (_imageIteratorTime + _timePerImage))
            {
                _imageIteratorTime += _timePerImage;
                // osg::notify(osg::NOTICE)<<"   _imageIteratorTime = "<<_imageIteratorTime<<std::endl;
                ++_imageIterator;

                if (_imageIterator ==_images.end())
                {

                    if (pruneOldImages)
                    {
                        _images.erase(previous_imageIterator, _imageIterator);
                        previous_imageIterator = _images.begin();
                    }

                    if (looping)
                    {
                        // return iterator to begining of set.
                        _imageIterator = _images.begin();
                    }
                    else
                    {
                        break;
                    }
                }
            }
        }

        if (looping && _imageIterator==_images.end())
        {
            _imageIterator = _images.begin();
        }
    }

    if (_imageIterator!=_images.end() && previous_imageIterator != _imageIterator)
    {
        if (pruneOldImages)
        {
            _images.erase(previous_imageIterator, _imageIterator);
        }

        setImageToChild(_imageIterator->get());
    }
    _seekTimeSet = false;
}
<|endoftext|>


<commit_before>/*
    WireS - Slave only I2C library for ATtiny1634 and ATtiny841
    Copyright (c) 2015 by Hisashi Ito (info at mewpro.cc)

    ------------------------------------------------------------------------------------------------------
    Some code segments derived from:
    i2c_t3 - I2C library for Teensy 3.0/3.1/LC

    - (v8) Modified 02Apr15 by Brian (nox771 at gmail.com)

    and

    TwoWire.cpp - TWI/I2C library for Wiring & Arduino
    Copyright (c) 2006 Nicholas Zambetti.  All right reserved.
    Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts
    ------------------------------------------------------------------------------------------------------
    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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

// This library should work with the following AVR microcontrollers
// having an I2C compatible, two-wire slave only interface.

#if defined(__AVR_ATtiny1634__) || defined(__AVR_ATtiny841__) || defined(__AVR_ATtiny441__) || defined(__AVR_ATtiny828__) || defined(__AVR_ATtiny40__) || defined(__AVR_ATtiny20__)

// Disclaimer: The author only confirmed the library to work with ATtiny1634 and ATtiny841.

#include <avr/io.h>
#include "WireS.h"

//#define TWI_HIGH_NOISE_MODE _BV(TWHNM) // only for ATtiny441/841 or ATtiny828
#define TWI_HIGH_NOISE_MODE 0

#ifndef TWAE // avr/iotn1634.h doesn't define
#define TWAE 0
#endif

// use MSB of i2c->Addr as a flag to indicate 10-bit slave address is on receiving
#define SET_TENBIT   do { i2c->Addr |= 0x8000; } while(0)
#define CLEAR_TENBIT do { i2c->Addr &= 0x7FFF; } while(0)
#define IS_TENBIT (i2c->Addr & 0x8000)

struct i2cStruct i2c_tinyS::i2cData;

// ------------------------------------------------------------------------------------------------------
// Constructor/Destructor
//
i2c_tinyS::i2c_tinyS()
{
    i2c = &i2cData;
}

i2c_tinyS::~i2c_tinyS()
{
}

// ------------------------------------------------------------------------------------------------------
// Initialize I2C - initializes I2C as two address or address range Slave
// return: none
// parameters:
//      address = 7bit address for specifying 1st Slave address
//      mask = 8bit integer;
//             if bit[0]==1 then bit[7:1] 2nd Slave address
//             if bit[0]==0 then bit[7:1] mask bits for address
//
void i2c_tinyS::begin_(struct i2cStruct* i2c, uint8_t address, uint8_t mask)
{
    I2C_INTR_FLAG_INIT; // init I2C interrupt flag if used
    TWSA = (address << 1);
    TWSAM = mask; // if mask == 0 then only one address
    i2c->startCount = -1;
    TWSCRA = (_BV(TWSHE) | _BV(TWDIE) | _BV(TWASIE) | _BV(TWEN) | _BV(TWSIE));
}

// ------------------------------------------------------------------------------------------------------
// Write - write data to Tx buffer
// return: 1=success, 0=fail
// parameters:
//      data = data byte
//
size_t i2c_tinyS::write(uint8_t data)
{
    if(i2c->txBufferLength < I2C_BUFFER_LENGTH)
    {
        i2c->Buffer[i2c->txBufferLength++] = data;
        return 1;
    }
    return 0;
}

// ------------------------------------------------------------------------------------------------------
// Write Array - write length number of bytes from data array to Tx buffer
// parameters:
//      data = pointer to uint8_t array of data
//      length = number of bytes to write
//
size_t i2c_tinyS::write(const uint8_t* data, size_t quantity)
{
    if(i2c->txBufferLength < I2C_BUFFER_LENGTH)
    {
        size_t avail = I2C_BUFFER_LENGTH - i2c->txBufferLength;
        uint8_t* dest = i2c->Buffer + i2c->txBufferLength;

        if(quantity > avail)
        {
            quantity = avail; // truncate to space avail if needed
        }
        for(size_t count=quantity; count; count--)
            *dest++ = *data++;
        i2c->txBufferLength += quantity;
    }
}

// ------------------------------------------------------------------------------------------------------
// Read - returns next data byte (signed int) from Rx buffer
// return: data, -1 if buffer empty
//
int i2c_tinyS::read_(struct i2cStruct* i2c)
{
    if(i2c->rxBufferIndex >= i2c->rxBufferLength) return -1;
    return i2c->Buffer[i2c->rxBufferIndex++];
}

// ------------------------------------------------------------------------------------------------------
// Peek - returns next data byte (signed int) from Rx buffer without removing it from Rx buffer
// return: data, -1 if buffer empty
//
int i2c_tinyS::peek_(struct i2cStruct* i2c)
{
    if(i2c->rxBufferIndex >= i2c->rxBufferLength) return -1;
    return i2c->Buffer[i2c->rxBufferIndex];
}

// ------------------------------------------------------------------------------------------------------
// Read Byte - returns next data byte (uint8_t) from Rx buffer
// return: data, 0 if buffer empty
//
uint8_t i2c_tinyS::readByte_(struct i2cStruct* i2c)
{
    if(i2c->rxBufferIndex >= i2c->rxBufferLength) return 0;
    return i2c->Buffer[i2c->rxBufferIndex++];
}

// ------------------------------------------------------------------------------------------------------
// Peek Byte - returns next data byte (uint8_t) from Rx buffer without removing it from Rx buffer
// return: data, 0 if buffer empty
//
uint8_t i2c_tinyS::peekByte_(struct i2cStruct* i2c)
{
    if(i2c->rxBufferIndex >= i2c->rxBufferLength) return 0;
    return i2c->Buffer[i2c->rxBufferIndex];
}

// ======================================================================================================
// ------------------------------------------------------------------------------------------------------
// I2C Interrupt Service Routine
// ------------------------------------------------------------------------------------------------------
// ======================================================================================================

void i2c_isr_handler()
{
    struct i2cStruct *i2c = &(i2c_tinyS::i2cData);
    byte status = TWSSRA;
    if ((status & (_BV(TWC) | _BV(TWBE)))) {
        // Bus error or transmit collision
        i2c->startCount = -1;
        CLEAR_TENBIT;
        TWSSRA |= (_BV(TWASIF) | _BV(TWDIF) | _BV(TWBE)); // Release hold
        return;
    }
    if ((status & _BV(TWASIF)) || IS_TENBIT) {
        if ((status & _BV(TWAS))) {
            // A valid address has been received
            if (IS_TENBIT) {
                i2c->Addr = (((i2c->Addr & B110) << 7) | TWSD);
                // CLEAR_TENBIT;
            } else {
                i2c->Addr = TWSD;
                i2c->startCount++;
                if ((i2c->Addr & B11111001) == B11110000) {
                    SET_TENBIT;
                    TWSCRB = (B0011 | TWI_HIGH_NOISE_MODE); // Send ACK
                    return;
                }
            }
            if (i2c->user_onAddrReceive != (void *)NULL) {
                i2c->rxBufferIndex = 0;
                if (!i2c->user_onAddrReceive(i2c->Addr, i2c->startCount)) {
                    TWSCRB = (B0111 | TWI_HIGH_NOISE_MODE); // Send NACK
                    return;
                }
            }
            if ((status & _BV(TWDIR))) {
                // A master read operation is in progress
                i2c->txBufferLength = 0;
                if (i2c->user_onRequest != (void *)NULL) {
                    i2c->user_onRequest(); // load Tx buffer with data
                }
                i2c->txBufferIndex = 0;
            } else {
                // A master write operation is in progress
                i2c->rxBufferLength = 0;
            }
        } else {
            // Stop condition is detected
            if ((status & _BV(TWDIR))) {
                if (i2c->user_onStop != (void *)NULL) {
                    i2c->user_onStop();
                }
            } else {
                if (i2c->user_onReceive != (void *)NULL) {
                    i2c->rxBufferIndex = 0;
                    i2c->user_onReceive(i2c->rxBufferLength);
                }
            }
            i2c->startCount = -1;
            CLEAR_TENBIT;
            TWSSRA = _BV(TWASIF); // clear interrupt
            return;
        }
    } else if ((status & _BV(TWDIF))) {
        if ((status & _BV(TWDIR))) {
            // Send a data byte to master
            if (i2c->txBufferIndex < i2c->txBufferLength) {
                TWSD = i2c->Buffer[i2c->txBufferIndex++];
            } else {
                // buffer overrun
                TWSCRB = (B0010 | TWI_HIGH_NOISE_MODE); // Wait for any START condition
                return;
            }
        } else {
            // A data byte has been received
            if (i2c->rxBufferLength < I2C_BUFFER_LENGTH) {
                i2c->Buffer[i2c->rxBufferLength++] = TWSD;
            } else {
                // buffer overrun
                TWSCRB = (B0110 | TWI_HIGH_NOISE_MODE); // Send NACK and wait for any START condition
                return;
            }
        }
    }
    TWSCRB = (B0011 | TWI_HIGH_NOISE_MODE);
}

ISR(TWI_SLAVE_vect)
{
    I2C_INTR_FLAG_ON;
    i2c_isr_handler();
    I2C_INTR_FLAG_OFF;
}

// ------------------------------------------------------------------------------------------------------
// Instantiate
//
i2c_tinyS Wire  = i2c_tinyS();

#endif
<commit_msg>ATtiny828 support<commit_after>/*
    WireS - Slave only I2C library for ATtiny1634, ATtiny441/841, and ATtiny828.
    Copyright (c) 2015 by Hisashi Ito (info at mewpro.cc)

    ------------------------------------------------------------------------------------------------------
    Some code segments derived from:
    i2c_t3 - I2C library for Teensy 3.0/3.1/LC

    - (v8) Modified 02Apr15 by Brian (nox771 at gmail.com)

    and

    TwoWire.cpp - TWI/I2C library for Wiring & Arduino
    Copyright (c) 2006 Nicholas Zambetti.  All right reserved.
    Modified 2012 by Todd Krein (todd@krein.org) to implement repeated starts
    ------------------------------------------------------------------------------------------------------
    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., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

// This library should work with the following AVR microcontrollers
// having an I2C compatible, two-wire slave only interface.

#if defined(__AVR_ATtiny1634__) || defined(__AVR_ATtiny841__) || defined(__AVR_ATtiny441__) || defined(__AVR_ATtiny828__) || defined(__AVR_ATtiny40__) || defined(__AVR_ATtiny20__)

// Disclaimer: The author only confirmed the library to work with ATtiny1634, ATtiny841, and ATtiny828.

#include <avr/io.h>
#include "WireS.h"

//#define TWI_HIGH_NOISE_MODE _BV(TWHNM) // only for ATtiny441/841 or ATtiny828
#define TWI_HIGH_NOISE_MODE 0

#ifndef TWAE // avr/iotn1634.h doesn't define
#define TWAE 0
#endif

// use MSB of i2c->Addr as a flag to indicate 10-bit slave address is on receiving
#define SET_TENBIT   do { i2c->Addr |= 0x8000; } while(0)
#define CLEAR_TENBIT do { i2c->Addr &= 0x7FFF; } while(0)
#define IS_TENBIT (i2c->Addr & 0x8000)

struct i2cStruct i2c_tinyS::i2cData;

// ------------------------------------------------------------------------------------------------------
// Constructor/Destructor
//
i2c_tinyS::i2c_tinyS()
{
    i2c = &i2cData;
}

i2c_tinyS::~i2c_tinyS()
{
}

// ------------------------------------------------------------------------------------------------------
// Initialize I2C - initializes I2C as two address or address range Slave
// return: none
// parameters:
//      address = 7bit address for specifying 1st Slave address
//      mask = 8bit integer;
//             if bit[0]==1 then bit[7:1] 2nd Slave address
//             if bit[0]==0 then bit[7:1] mask bits for address
//
void i2c_tinyS::begin_(struct i2cStruct* i2c, uint8_t address, uint8_t mask)
{
    I2C_INTR_FLAG_INIT; // init I2C interrupt flag if used
    TWSA = (address << 1);
    TWSAM = mask; // if mask == 0 then only one address
    i2c->startCount = -1;
    TWSCRA = (_BV(TWSHE) | _BV(TWDIE) | _BV(TWASIE) | _BV(TWEN) | _BV(TWSIE));
}

// ------------------------------------------------------------------------------------------------------
// Write - write data to Tx buffer
// return: 1=success, 0=fail
// parameters:
//      data = data byte
//
size_t i2c_tinyS::write(uint8_t data)
{
    if(i2c->txBufferLength < I2C_BUFFER_LENGTH)
    {
        i2c->Buffer[i2c->txBufferLength++] = data;
        return 1;
    }
    return 0;
}

// ------------------------------------------------------------------------------------------------------
// Write Array - write length number of bytes from data array to Tx buffer
// parameters:
//      data = pointer to uint8_t array of data
//      length = number of bytes to write
//
size_t i2c_tinyS::write(const uint8_t* data, size_t quantity)
{
    if(i2c->txBufferLength < I2C_BUFFER_LENGTH)
    {
        size_t avail = I2C_BUFFER_LENGTH - i2c->txBufferLength;
        uint8_t* dest = i2c->Buffer + i2c->txBufferLength;

        if(quantity > avail)
        {
            quantity = avail; // truncate to space avail if needed
        }
        for(size_t count=quantity; count; count--)
            *dest++ = *data++;
        i2c->txBufferLength += quantity;
    }
}

// ------------------------------------------------------------------------------------------------------
// Read - returns next data byte (signed int) from Rx buffer
// return: data, -1 if buffer empty
//
int i2c_tinyS::read_(struct i2cStruct* i2c)
{
    if(i2c->rxBufferIndex >= i2c->rxBufferLength) return -1;
    return i2c->Buffer[i2c->rxBufferIndex++];
}

// ------------------------------------------------------------------------------------------------------
// Peek - returns next data byte (signed int) from Rx buffer without removing it from Rx buffer
// return: data, -1 if buffer empty
//
int i2c_tinyS::peek_(struct i2cStruct* i2c)
{
    if(i2c->rxBufferIndex >= i2c->rxBufferLength) return -1;
    return i2c->Buffer[i2c->rxBufferIndex];
}

// ------------------------------------------------------------------------------------------------------
// Read Byte - returns next data byte (uint8_t) from Rx buffer
// return: data, 0 if buffer empty
//
uint8_t i2c_tinyS::readByte_(struct i2cStruct* i2c)
{
    if(i2c->rxBufferIndex >= i2c->rxBufferLength) return 0;
    return i2c->Buffer[i2c->rxBufferIndex++];
}

// ------------------------------------------------------------------------------------------------------
// Peek Byte - returns next data byte (uint8_t) from Rx buffer without removing it from Rx buffer
// return: data, 0 if buffer empty
//
uint8_t i2c_tinyS::peekByte_(struct i2cStruct* i2c)
{
    if(i2c->rxBufferIndex >= i2c->rxBufferLength) return 0;
    return i2c->Buffer[i2c->rxBufferIndex];
}

// ======================================================================================================
// ------------------------------------------------------------------------------------------------------
// I2C Interrupt Service Routine
// ------------------------------------------------------------------------------------------------------
// ======================================================================================================

void i2c_isr_handler()
{
    struct i2cStruct *i2c = &(i2c_tinyS::i2cData);
    byte status = TWSSRA;
    if ((status & (_BV(TWC) | _BV(TWBE)))) {
        // Bus error or transmit collision
        i2c->startCount = -1;
        CLEAR_TENBIT;
        TWSSRA |= (_BV(TWASIF) | _BV(TWDIF) | _BV(TWBE)); // Release hold
        return;
    }
    if ((status & _BV(TWASIF)) || IS_TENBIT) {
        if ((status & _BV(TWAS))) {
            // A valid address has been received
            if (IS_TENBIT) {
                i2c->Addr = (((i2c->Addr & B110) << 7) | TWSD);
                // CLEAR_TENBIT;
            } else {
                i2c->Addr = TWSD;
                i2c->startCount++;
                if ((i2c->Addr & B11111001) == B11110000) {
                    SET_TENBIT;
                    TWSCRB = (B0011 | TWI_HIGH_NOISE_MODE); // Send ACK
                    return;
                }
            }
            if (i2c->user_onAddrReceive != (void *)NULL) {
                i2c->rxBufferIndex = 0;
                if (!i2c->user_onAddrReceive(i2c->Addr, i2c->startCount)) {
                    TWSCRB = (B0111 | TWI_HIGH_NOISE_MODE); // Send NACK
                    return;
                }
            }
            if ((status & _BV(TWDIR))) {
                // A master read operation is in progress
                i2c->txBufferLength = 0;
                if (i2c->user_onRequest != (void *)NULL) {
                    i2c->user_onRequest(); // load Tx buffer with data
                }
                i2c->txBufferIndex = 0;
            } else {
                // A master write operation is in progress
                i2c->rxBufferLength = 0;
            }
        } else {
            // Stop condition is detected
            if ((status & _BV(TWDIR))) {
                if (i2c->user_onStop != (void *)NULL) {
                    i2c->user_onStop();
                }
            } else {
                if (i2c->user_onReceive != (void *)NULL) {
                    i2c->rxBufferIndex = 0;
                    i2c->user_onReceive(i2c->rxBufferLength);
                }
            }
            i2c->startCount = -1;
            CLEAR_TENBIT;
            TWSSRA = _BV(TWASIF); // clear interrupt
            return;
        }
    } else if ((status & _BV(TWDIF))) {
        if ((status & _BV(TWDIR))) {
            // Send a data byte to master
            if (i2c->txBufferIndex < i2c->txBufferLength) {
                TWSD = i2c->Buffer[i2c->txBufferIndex++];
            } else {
                // buffer overrun
                TWSCRB = (B0010 | TWI_HIGH_NOISE_MODE); // Wait for any START condition
                return;
            }
        } else {
            // A data byte has been received
            if (i2c->rxBufferLength < I2C_BUFFER_LENGTH) {
                i2c->Buffer[i2c->rxBufferLength++] = TWSD;
            } else {
                // buffer overrun
                TWSCRB = (B0110 | TWI_HIGH_NOISE_MODE); // Send NACK and wait for any START condition
                return;
            }
        }
    }
    TWSCRB = (B0011 | TWI_HIGH_NOISE_MODE);
}

ISR(TWI_SLAVE_vect)
{
    I2C_INTR_FLAG_ON;
    i2c_isr_handler();
    I2C_INTR_FLAG_OFF;
}

// ------------------------------------------------------------------------------------------------------
// Instantiate
//
i2c_tinyS Wire  = i2c_tinyS();

#endif
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/common/include/p9_frequency_buckets.H $   */
/*                                                                        */
/* 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                                                     */

// constant defining number of NEST PLL frequency options ('buckets')
// to be built into unsigned HW image
const uint8_t NEST_PLL_FREQ_BUCKETS = 5;

// Nest PLL frequency in MHZ
// index is bucket number
const uint32_t NEST_PLL_FREQ_LIST[NEST_PLL_FREQ_BUCKETS] =
{
    1600,
    1866,
    2000,
    2133,
    2400
};

// I2C bus divisor
// index is bucket number
// The values in this list will be factor of 1:64 to the NEST_PLL_FREQ_LIST
const uint32_t NEST_PLL_FREQ_I2CDIV_LIST[NEST_PLL_FREQ_BUCKETS] =
{
    25,
    29,
    31,
    33,
    37
};

// constant defining number of MEM PLL frequency options ('buckets')
// to be built into unsigned HW image
const uint8_t MEM_PLL_FREQ_BUCKETS = 5;

// MEM PLL frequency in MHz
// index is bucket number
const uint32_t MEM_PLL_FREQ_LIST[MEM_PLL_FREQ_BUCKETS] =
{
    1866,
    2133,
    2400,
    2666,
    2666
};

// constant definining number of OBUS PLL frequency options ('buckets')
// to be built into unsigned HW image
const uint8_t OBUS_PLL_FREQ_BUCKETS = 3;

// OBUS PLL frequency in MHz
// index is bucket number
const uint32_t OBUS_PLL_FREQ_LIST_P9N_10[OBUS_PLL_FREQ_BUCKETS] =
{
    1250,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_20[OBUS_PLL_FREQ_BUCKETS] =
{
    1563,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_21[OBUS_PLL_FREQ_BUCKETS] =
{
    1563,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_22[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1563
};

const uint32_t OBUS_PLL_FREQ_LIST_P9C_10[OBUS_PLL_FREQ_BUCKETS] =
{
    1601,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9C_11[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1601
};

const uint32_t OBUS_PLL_FREQ_LIST_P9A_10[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9A_11[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1611
};
<commit_msg>Add support for p9c 1.2<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/common/include/p9_frequency_buckets.H $   */
/*                                                                        */
/* 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                                                     */

// constant defining number of NEST PLL frequency options ('buckets')
// to be built into unsigned HW image
const uint8_t NEST_PLL_FREQ_BUCKETS = 5;

// Nest PLL frequency in MHZ
// index is bucket number
const uint32_t NEST_PLL_FREQ_LIST[NEST_PLL_FREQ_BUCKETS] =
{
    1600,
    1866,
    2000,
    2133,
    2400
};

// I2C bus divisor
// index is bucket number
// The values in this list will be factor of 1:64 to the NEST_PLL_FREQ_LIST
const uint32_t NEST_PLL_FREQ_I2CDIV_LIST[NEST_PLL_FREQ_BUCKETS] =
{
    25,
    29,
    31,
    33,
    37
};

// constant defining number of MEM PLL frequency options ('buckets')
// to be built into unsigned HW image
const uint8_t MEM_PLL_FREQ_BUCKETS = 5;

// MEM PLL frequency in MHz
// index is bucket number
const uint32_t MEM_PLL_FREQ_LIST[MEM_PLL_FREQ_BUCKETS] =
{
    1866,
    2133,
    2400,
    2666,
    2666
};

// constant definining number of OBUS PLL frequency options ('buckets')
// to be built into unsigned HW image
const uint8_t OBUS_PLL_FREQ_BUCKETS = 3;

// OBUS PLL frequency in MHz
// index is bucket number
const uint32_t OBUS_PLL_FREQ_LIST_P9N_10[OBUS_PLL_FREQ_BUCKETS] =
{
    1250,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_20[OBUS_PLL_FREQ_BUCKETS] =
{
    1563,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_21[OBUS_PLL_FREQ_BUCKETS] =
{
    1563,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9N_22[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1563
};

const uint32_t OBUS_PLL_FREQ_LIST_P9C_10[OBUS_PLL_FREQ_BUCKETS] =
{
    1601,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9C_11[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1601
};

const uint32_t OBUS_PLL_FREQ_LIST_P9C_12[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1601
};

const uint32_t OBUS_PLL_FREQ_LIST_P9A_10[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1611
};

const uint32_t OBUS_PLL_FREQ_LIST_P9A_11[OBUS_PLL_FREQ_BUCKETS] =
{
    1611,
    1250,
    1611
};
<|endoftext|>


<commit_before>#include "stdafx.h"
#include "EntryList.h"
#include "String.h"

EntryList::EntryList()
{
	m_EntryCount = 0;
	m_Pad = 0;
}

void EntryList::Parse()
{
	m_EntryCount = m_Parser.Get<DWORD>();
	m_Pad = m_Parser.Get<DWORD>();

	if (m_EntryCount && m_EntryCount < _MaxEntriesLarge)
	{
		{
			for (DWORD i = 0; i < m_EntryCount; i++)
			{
				EntryListEntryStruct entryListEntryStruct;
				entryListEntryStruct.EntryLength = m_Parser.Get<DWORD>();
				entryListEntryStruct.EntryLengthPad = m_Parser.Get<DWORD>();
				m_Entry.push_back(entryListEntryStruct);
			}

			for (DWORD i = 0; i < m_EntryCount; i++)
			{
				size_t cbRemainingBytes = min(m_Entry[i].EntryLength, m_Parser.RemainingBytes());
				m_Entry[i].EntryId.Init(cbRemainingBytes, m_Parser.GetCurrentAddress());
				m_Parser.Advance(cbRemainingBytes);
			}
		}
	}
}

_Check_return_ wstring EntryList::ToStringInternal()
{
	auto szEntryList = formatmessage(IDS_ENTRYLISTDATA,
		m_EntryCount,
		m_Pad);

	for (DWORD i = 0; i < m_EntryCount; i++)
	{
		szEntryList += formatmessage(IDS_ENTRYLISTENTRYID,
			i,
			m_Entry[i].EntryLength,
			m_Entry[i].EntryLengthPad);

		szEntryList += m_Entry[i].EntryId.ToString();
	}

	return szEntryList;
}<commit_msg>bad array count in EntryList::ToStringInternal<commit_after>#include "stdafx.h"
#include "EntryList.h"
#include "String.h"

EntryList::EntryList()
{
	m_EntryCount = 0;
	m_Pad = 0;
}

void EntryList::Parse()
{
	m_EntryCount = m_Parser.Get<DWORD>();
	m_Pad = m_Parser.Get<DWORD>();

	if (m_EntryCount && m_EntryCount < _MaxEntriesLarge)
	{
		{
			for (DWORD i = 0; i < m_EntryCount; i++)
			{
				EntryListEntryStruct entryListEntryStruct;
				entryListEntryStruct.EntryLength = m_Parser.Get<DWORD>();
				entryListEntryStruct.EntryLengthPad = m_Parser.Get<DWORD>();
				m_Entry.push_back(entryListEntryStruct);
			}

			for (DWORD i = 0; i < m_EntryCount; i++)
			{
				size_t cbRemainingBytes = min(m_Entry[i].EntryLength, m_Parser.RemainingBytes());
				m_Entry[i].EntryId.Init(cbRemainingBytes, m_Parser.GetCurrentAddress());
				m_Parser.Advance(cbRemainingBytes);
			}
		}
	}
}

_Check_return_ wstring EntryList::ToStringInternal()
{
	auto szEntryList = formatmessage(IDS_ENTRYLISTDATA,
		m_EntryCount,
		m_Pad);

	for (DWORD i = 0; i < m_Entry.size(); i++)
	{
		szEntryList += formatmessage(IDS_ENTRYLISTENTRYID,
			i,
			m_Entry[i].EntryLength,
			m_Entry[i].EntryLengthPad);

		szEntryList += m_Entry[i].EntryId.ToString();
	}

	return szEntryList;
}<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_lpc_init.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_sbe_lpc_init.H
///
/// @brief procedure to initialize LPC to enable communictation to PNOR
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : sunil kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 3
// *HWP Consumed by     : SBE
//------------------------------------------------------------------------------

#ifndef _P9_SBE_LPC_INIT_H_
#define _P9_SBE_LPC_INIT_H_

#include <fapi2.H>

typedef fapi2::ReturnCode (*p9_sbe_lpc_init_FP_t)(const
        fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

/// @brief LPC init to enable connection to PNOR
///
/// @param[in]     i_target_chip   Reference to TARGET_TYPE_PROC_CHIP target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
    const uint64_t LPC_LRESET_OE = 23;
    const uint64_t LPC_LRESET_OUT = 22;
    const uint32_t LPC_LRESET_DELAY_NS = 200000;
    const uint64_t LPCM_OPB_MASTER_CONTROL_REG = 0xC0010008;
    const uint32_t CPLT_CONF1_TC_LP_RESET = 12;
    fapi2::ReturnCode p9_sbe_lpc_init(const
                                      fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}

#endif
<commit_msg>p9_sbe_lpc_init: Fix timeout setup<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/perv/p9_sbe_lpc_init.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_sbe_lpc_init.H
///
/// @brief procedure to initialize LPC to enable communictation to PNOR
//------------------------------------------------------------------------------
// *HWP HW Owner        : Abhishek Agarwal <abagarw8@in.ibm.com>
// *HWP HW Backup Owner : Srinivas V Naga <srinivan@in.ibm.com>
// *HWP FW Owner        : sunil kumar <skumar8j@in.ibm.com>
// *HWP Team            : Perv
// *HWP Level           : 3
// *HWP Consumed by     : SBE
//------------------------------------------------------------------------------

#ifndef _P9_SBE_LPC_INIT_H_
#define _P9_SBE_LPC_INIT_H_

#include <fapi2.H>

typedef fapi2::ReturnCode (*p9_sbe_lpc_init_FP_t)(const
        fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>&);

/// @brief LPC init to enable connection to PNOR
///
/// @param[in]     i_target_chip   Reference to TARGET_TYPE_PROC_CHIP target
/// @return  FAPI2_RC_SUCCESS if success, else error code.
extern "C"
{
    const uint64_t LPC_LRESET_OE = 23;
    const uint64_t LPC_LRESET_OUT = 22;
    const uint32_t LPC_LRESET_DELAY_NS = 200000;
    const uint32_t LPCM_OPB_MASTER_CONTROL_REG = 0xC0010008;
    const uint32_t LPCM_OPB_MASTER_CONTROL_REG_TIMEOUT_ENABLE = 2;
    const uint32_t LPCM_OPB_MASTER_TIMEOUT_REG = 0xC0010040;
    const uint32_t LPCM_OPB_MASTER_TIMEOUT_VALUE = 0x01312D00;  // 50ms at 1600MHz Nest / 400MHz OPB
    const uint32_t LPCM_LPC_MASTER_TIMEOUT_REG = 0xC001202C;
    const uint32_t LPCM_LPC_MASTER_TIMEOUT_VALUE = 0xFE000000;
    const uint32_t CPLT_CONF1_TC_LP_RESET = 12;
    fapi2::ReturnCode p9_sbe_lpc_init(const
                                      fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target_chip);
}

#endif
<|endoftext|>


<commit_before>#include <eosio/chain_api_plugin/chain_api_plugin.hpp>
#include <eosio/chain/exceptions.hpp>

#include <fc/io/json.hpp>

namespace eosio {

static appbase::abstract_plugin& _chain_api_plugin = app().register_plugin<chain_api_plugin>();

using namespace eosio;

class chain_api_plugin_impl {
public:
   chain_api_plugin_impl(controller& db)
      : db(db) {}

   controller& db;
};

chain_api_plugin::chain_api_plugin(){}
chain_api_plugin::~chain_api_plugin(){}

void chain_api_plugin::set_program_options(options_description&, options_description&) {}
void chain_api_plugin::plugin_initialize(const variables_map&) {}

struct async_result_visitor : public fc::visitor<fc::variant> {
   template<typename T>
   fc::variant operator()(const T& v) const {
      return fc::variant(v);
   }
};

namespace {
   template<typename T>
   T parse_params(const std::string& body) {
      if (body.empty()) {
         EOS_THROW(chain::invalid_http_request, "A Request body is required");
      }

      try {
        try {
           return fc::json::from_string(body).as<T>();
        } catch (const chain::chain_exception& e) { // EOS_RETHROW_EXCEPTIONS does not re-type these so, re-code it
          throw fc::exception(e);
        }
      } EOS_RETHROW_EXCEPTIONS(chain::invalid_http_request, "Unable to parse valid input from POST body");
   }
}

#define CALL_WITH_400(api_name, api_handle, api_namespace, call_name, http_response_code, params_type) \
{std::string("/v1/" #api_name "/" #call_name), \
   [api_handle](string, string body, url_response_callback cb) mutable { \
          api_handle.validate(); \
          try { \
             auto params = parse_params<api_namespace::call_name ## _params, params_type>(body);\
             fc::variant result( api_handle.call_name( std::move(params) ) ); \
             cb(http_response_code, std::move(result)); \
          } catch (...) { \
             http_plugin::handle_exception(#api_name, #call_name, body, cb); \
          } \
       }}

#define CALL_ASYNC_WITH_400(api_name, api_handle, api_namespace, call_name, call_result, http_response_code, params_type) \
{std::string("/v1/" #api_name "/" #call_name), \
   [api_handle](string, string body, url_response_callback cb) mutable { \
      api_handle.validate(); \
      try { \
         auto params = parse_params<api_namespace::call_name ## _params, params_type>(body);\
         api_handle.call_name( std::move(params),\
            [cb, body](const fc::static_variant<fc::exception_ptr, call_result>& result){\
               if (result.contains<fc::exception_ptr>()) {\
                  try {\
                     result.get<fc::exception_ptr>()->dynamic_rethrow_exception();\
                  } catch (...) {\
                     http_plugin::handle_exception(#api_name, #call_name, body, cb);\
                  }\
               } else {\
                  cb(http_response_code, result.visit(async_result_visitor()));\
               }\
            });\
      } catch (...) { \
         http_plugin::handle_exception(#api_name, #call_name, body, cb); \
      } \
   }\
}

#define CHAIN_RO_CALL(call_name, http_response_code, params_type) CALL_WITH_400(chain, ro_api, chain_apis::read_only, call_name, http_response_code, params_type)
#define CHAIN_RW_CALL(call_name, http_response_code, params_type) CALL_WITH_400(chain, rw_api, chain_apis::read_write, call_name, http_response_code, params_type)
#define CHAIN_RO_CALL_ASYNC(call_name, call_result, http_response_code, params_type) CALL_ASYNC_WITH_400(chain, ro_api, chain_apis::read_only, call_name, call_result, http_response_code, params_type)
#define CHAIN_RW_CALL_ASYNC(call_name, call_result, http_response_code, params_type) CALL_ASYNC_WITH_400(chain, rw_api, chain_apis::read_write, call_name, call_result, http_response_code, params_type)

#define CHAIN_RO_CALL_WITH_400(call_name, http_response_code) CALL_WITH_400(chain, ro_api, chain_apis::read_only, call_name, http_response_code, params_type)

void chain_api_plugin::plugin_startup() {
   ilog( "starting chain_api_plugin" );
   my.reset(new chain_api_plugin_impl(app().get_plugin<chain_plugin>().chain()));
   auto& chain = app().get_plugin<chain_plugin>();
   auto ro_api = chain.get_read_only_api();
   auto rw_api = chain.get_read_write_api();

   auto& _http_plugin = app().get_plugin<http_plugin>();
   ro_api.set_shorten_abi_errors( !_http_plugin.verbose_errors() );

   _http_plugin.add_api({
      CHAIN_RO_CALL(get_info, 200, http_params_types::no_params_required)}, appbase::priority::medium_high);
   _http_plugin.add_api({
      CHAIN_RO_CALL(get_activated_protocol_features, 200, http_params_types::possible_no_params),
      CHAIN_RO_CALL(get_block, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_block_info, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_block_header_state, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_account, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_code, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_code_hash, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_abi, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_raw_code_and_abi, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_raw_abi, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_table_rows, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_table_by_scope, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_currency_balance, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_currency_stats, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_producers, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_producer_schedule, 200, http_params_types::no_params_required),
      CHAIN_RO_CALL(get_scheduled_transactions, 200, http_params_types::params_required),
      CHAIN_RO_CALL(abi_json_to_bin, 200, http_params_types::params_required),
      CHAIN_RO_CALL(abi_bin_to_json, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_required_keys, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_transaction_id, 200, http_params_types::params_required),
      CHAIN_RW_CALL_ASYNC(push_block, chain_apis::read_write::push_block_results, 202, http_params_types::params_required),
      CHAIN_RW_CALL_ASYNC(push_transaction, chain_apis::read_write::push_transaction_results, 202, http_params_types::params_required),
      CHAIN_RW_CALL_ASYNC(push_transactions, chain_apis::read_write::push_transactions_results, 202, http_params_types::params_required),
      CHAIN_RW_CALL_ASYNC(send_transaction, chain_apis::read_write::send_transaction_results, 202, http_params_types::params_required)
   });

   if (chain.account_queries_enabled()) {
      _http_plugin.add_async_api({
         CHAIN_RO_CALL_WITH_400(get_accounts_by_authorizers, 200),
      });
   }
}

void chain_api_plugin::plugin_shutdown() {}

}
<commit_msg>Update chain_api_plugin.cpp<commit_after>#include <eosio/chain_api_plugin/chain_api_plugin.hpp>
#include <eosio/chain/exceptions.hpp>

#include <fc/io/json.hpp>

namespace eosio {

static appbase::abstract_plugin& _chain_api_plugin = app().register_plugin<chain_api_plugin>();

using namespace eosio;

class chain_api_plugin_impl {
public:
   chain_api_plugin_impl(controller& db)
      : db(db) {}

   controller& db;
};

chain_api_plugin::chain_api_plugin(){}
chain_api_plugin::~chain_api_plugin(){}

void chain_api_plugin::set_program_options(options_description&, options_description&) {}
void chain_api_plugin::plugin_initialize(const variables_map&) {}

struct async_result_visitor : public fc::visitor<fc::variant> {
   template<typename T>
   fc::variant operator()(const T& v) const {
      return fc::variant(v);
   }
};

namespace {
   template<typename T>
   T parse_params(const std::string& body) {
      if (body.empty()) {
         EOS_THROW(chain::invalid_http_request, "A Request body is required");
      }

      try {
        try {
           return fc::json::from_string(body).as<T>();
        } catch (const chain::chain_exception& e) { // EOS_RETHROW_EXCEPTIONS does not re-type these so, re-code it
          throw fc::exception(e);
        }
      } EOS_RETHROW_EXCEPTIONS(chain::invalid_http_request, "Unable to parse valid input from POST body");
   }
}

#define CALL_WITH_400(api_name, api_handle, api_namespace, call_name, http_response_code, params_type) \
{std::string("/v1/" #api_name "/" #call_name), \
   [api_handle](string, string body, url_response_callback cb) mutable { \
          api_handle.validate(); \
          try { \
             auto params = parse_params<api_namespace::call_name ## _params, params_type>(body);\
             fc::variant result( api_handle.call_name( std::move(params) ) ); \
             cb(http_response_code, std::move(result)); \
          } catch (...) { \
             http_plugin::handle_exception(#api_name, #call_name, body, cb); \
          } \
       }}

#define CALL_ASYNC_WITH_400(api_name, api_handle, api_namespace, call_name, call_result, http_response_code, params_type) \
{std::string("/v1/" #api_name "/" #call_name), \
   [api_handle](string, string body, url_response_callback cb) mutable { \
      api_handle.validate(); \
      try { \
         auto params = parse_params<api_namespace::call_name ## _params, params_type>(body);\
         api_handle.call_name( std::move(params),\
            [cb, body](const fc::static_variant<fc::exception_ptr, call_result>& result){\
               if (result.contains<fc::exception_ptr>()) {\
                  try {\
                     result.get<fc::exception_ptr>()->dynamic_rethrow_exception();\
                  } catch (...) {\
                     http_plugin::handle_exception(#api_name, #call_name, body, cb);\
                  }\
               } else {\
                  cb(http_response_code, result.visit(async_result_visitor()));\
               }\
            });\
      } catch (...) { \
         http_plugin::handle_exception(#api_name, #call_name, body, cb); \
      } \
   }\
}

#define CHAIN_RO_CALL(call_name, http_response_code, params_type) CALL_WITH_400(chain, ro_api, chain_apis::read_only, call_name, http_response_code, params_type)
#define CHAIN_RW_CALL(call_name, http_response_code, params_type) CALL_WITH_400(chain, rw_api, chain_apis::read_write, call_name, http_response_code, params_type)
#define CHAIN_RO_CALL_ASYNC(call_name, call_result, http_response_code, params_type) CALL_ASYNC_WITH_400(chain, ro_api, chain_apis::read_only, call_name, call_result, http_response_code, params_type)
#define CHAIN_RW_CALL_ASYNC(call_name, call_result, http_response_code, params_type) CALL_ASYNC_WITH_400(chain, rw_api, chain_apis::read_write, call_name, call_result, http_response_code, params_type)

#define CHAIN_RO_CALL_WITH_400(call_name, http_response_code, params_type) CALL_WITH_400(chain, ro_api, chain_apis::read_only, call_name, http_response_code, params_type)

void chain_api_plugin::plugin_startup() {
   ilog( "starting chain_api_plugin" );
   my.reset(new chain_api_plugin_impl(app().get_plugin<chain_plugin>().chain()));
   auto& chain = app().get_plugin<chain_plugin>();
   auto ro_api = chain.get_read_only_api();
   auto rw_api = chain.get_read_write_api();

   auto& _http_plugin = app().get_plugin<http_plugin>();
   ro_api.set_shorten_abi_errors( !_http_plugin.verbose_errors() );

   _http_plugin.add_api({
      CHAIN_RO_CALL(get_info, 200, http_params_types::no_params_required)}, appbase::priority::medium_high);
   _http_plugin.add_api({
      CHAIN_RO_CALL(get_activated_protocol_features, 200, http_params_types::possible_no_params),
      CHAIN_RO_CALL(get_block, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_block_info, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_block_header_state, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_account, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_code, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_code_hash, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_abi, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_raw_code_and_abi, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_raw_abi, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_table_rows, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_table_by_scope, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_currency_balance, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_currency_stats, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_producers, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_producer_schedule, 200, http_params_types::no_params_required),
      CHAIN_RO_CALL(get_scheduled_transactions, 200, http_params_types::params_required),
      CHAIN_RO_CALL(abi_json_to_bin, 200, http_params_types::params_required),
      CHAIN_RO_CALL(abi_bin_to_json, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_required_keys, 200, http_params_types::params_required),
      CHAIN_RO_CALL(get_transaction_id, 200, http_params_types::params_required),
      CHAIN_RW_CALL_ASYNC(push_block, chain_apis::read_write::push_block_results, 202, http_params_types::params_required),
      CHAIN_RW_CALL_ASYNC(push_transaction, chain_apis::read_write::push_transaction_results, 202, http_params_types::params_required),
      CHAIN_RW_CALL_ASYNC(push_transactions, chain_apis::read_write::push_transactions_results, 202, http_params_types::params_required),
      CHAIN_RW_CALL_ASYNC(send_transaction, chain_apis::read_write::send_transaction_results, 202, http_params_types::params_required)
   });

   if (chain.account_queries_enabled()) {
      _http_plugin.add_async_api({
         CHAIN_RO_CALL_WITH_400(get_accounts_by_authorizers, 200),
      });
   }
}

void chain_api_plugin::plugin_shutdown() {}

}
<|endoftext|>


<commit_before>/*
    Copyright (C) 2003 by Jorrit Tyberghein
	      (C) 2003 by Frank Richter

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"

#include "csutil/util.h"
#include "iutil/document.h"
#include "iutil/objreg.h"
#include "iengine/engine.h"
#include "iengine/renderloop.h"
#include "imap/services.h"
#include "ivaria/reporter.h"
#include "iengine/rendersteps/irenderstep.h"
#include "iengine/rendersteps/icontainer.h"

#include "rlloader.h"

CS_LEAKGUARD_IMPLEMENT (csRenderLoopLoader);

// Plugin stuff

SCF_IMPLEMENT_IBASE(csRenderLoopLoader);
  SCF_IMPLEMENTS_INTERFACE(iLoaderPlugin);
  SCF_IMPLEMENTS_INTERFACE(iComponent);
SCF_IMPLEMENT_IBASE_END

CS_IMPLEMENT_PLUGIN

SCF_IMPLEMENT_FACTORY(csRenderLoopLoader)

//---------------------------------------------------------------------------

csRenderLoopLoader::csRenderLoopLoader (iBase *p)
{
  SCF_CONSTRUCT_IBASE (p);
  InitTokenTable (tokens);
}

csRenderLoopLoader::~csRenderLoopLoader ()
{
  SCF_DESTRUCT_IBASE();
}

bool csRenderLoopLoader::Initialize(iObjectRegistry *object_reg)
{
  csRenderLoopLoader::object_reg = object_reg;

  synldr = CS_QUERY_REGISTRY (object_reg, iSyntaxService);
  rsp.Initialize (object_reg);

  return true;
}

bool csRenderLoopLoader::ParseRenderSteps (iRenderLoop* loop,
					   iDocumentNode* node)
{
  csRef<iRenderStepContainer> cont =
    scfQueryInterface<iRenderStepContainer> (loop);
  if (!cont)
  {
    if (synldr)
      synldr->ReportError (
	      "crystalspace.renderloop.load",
              node, "Internal error: doesn't implement iRenderStepContainer!");
    return false;
  }

  return rsp.ParseRenderSteps (cont, node);
}

csPtr<iBase> csRenderLoopLoader::Parse (iDocumentNode* node,
  iStreamSource*, iLoaderContext* ldr_context, iBase* /*context*/)
{
  csRef<iEngine> engine = CS_QUERY_REGISTRY (object_reg, iEngine);
  if (!engine)
  {
    if (synldr)
      synldr->ReportError (
	      "crystalspace.renderloop.load",
              node, "Can't find engine!");
    return 0;
  }

  iRenderLoopManager* loopmgr = engine->GetRenderLoopManager ();
  if (!loopmgr)
  {
    if (synldr)
      synldr->ReportError (
	      "crystalspace.renderloop.load",
              node, "Engine doesn't have a render loop manager!");
    return 0;
  }

  csRef<iRenderLoop> loop = loopmgr->Create ();
  csRef<iObject> obj = scfQueryInterface<iObject> (loop);
  if (ldr_context->GetRegion ())
    ldr_context->GetRegion ()->QueryObject ()->ObjAdd (obj);

  char* loopName = 0;

  if (node)
  {
    csRef<iDocumentNodeIterator> it = node->GetNodes ();
    while (it->HasNext ())
    {
      csRef<iDocumentNode> child = it->Next ();
      if (child->GetType () != CS_NODE_ELEMENT) continue;
      csStringID id = tokens.Request (child->GetValue ());
      switch (id)
      {
	case XMLTOKEN_NAME:
	  {
	    loopName = csStrNew (child->GetContentsValue ());
	  }
	  break;
	case XMLTOKEN_STEPS:
	  {
	    if (!ParseRenderSteps (loop, child))
	    {
	      goto error;
	    }
	  }
	  break;
	default:
	  if (synldr) synldr->ReportBadToken (child);
	  goto error;
      }
    }
  }

  if (loopName)
  {
    if (!loopmgr->Register (loopName, loop))
    {
      if (synldr)
      {
	synldr->Report (
	  "crystalspace.renderloop.loop.loader",
	  CS_REPORTER_SEVERITY_WARNING,
	  node,
	  "Couldn't register render loop '%s'. Maybe a loop of the same "
	  "name already exists?",
	  loopName);
      }
    }
  }
  else
  {
    if (synldr)
    {
      synldr->Report (
	"crystalspace.renderloop.loop.loader",
	CS_REPORTER_SEVERITY_WARNING,
	node,
	"Render loop has no name and is therefore inaccessible. "
	"This may not be what you want.");
    }
  }

  if (loop->GetStepCount () == 0)
  {
    if (synldr)
    {
      synldr->Report (
	"crystalspace.renderloop.loop.loader",
	CS_REPORTER_SEVERITY_WARNING,
	node,
	"Render loop has no steps. "
	"This may not be what you want.");
    }
  }

  delete[] loopName;
  return csPtr<iBase> (loop);

error:
  delete[] loopName;
  return 0;
}

<commit_msg>Fixed compile errors.<commit_after>/*
    Copyright (C) 2003 by Jorrit Tyberghein
	      (C) 2003 by Frank Richter

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Library General Public
    License as published by the Free Software Foundation; either
    version 2 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
    Library General Public License for more details.

    You should have received a copy of the GNU Library General Public
    License along with this library; if not, write to the Free
    Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*/

#include "cssysdef.h"

#include "csutil/util.h"
#include "iutil/document.h"
#include "iutil/objreg.h"
#include "iutil/object.h"
#include "iengine/engine.h"
#include "iengine/renderloop.h"
#include "imap/services.h"
#include "imap/ldrctxt.h"
#include "iengine/region.h"
#include "ivaria/reporter.h"
#include "iengine/rendersteps/irenderstep.h"
#include "iengine/rendersteps/icontainer.h"

#include "rlloader.h"

CS_LEAKGUARD_IMPLEMENT (csRenderLoopLoader);

// Plugin stuff

SCF_IMPLEMENT_IBASE(csRenderLoopLoader);
  SCF_IMPLEMENTS_INTERFACE(iLoaderPlugin);
  SCF_IMPLEMENTS_INTERFACE(iComponent);
SCF_IMPLEMENT_IBASE_END

CS_IMPLEMENT_PLUGIN

SCF_IMPLEMENT_FACTORY(csRenderLoopLoader)

//---------------------------------------------------------------------------

csRenderLoopLoader::csRenderLoopLoader (iBase *p)
{
  SCF_CONSTRUCT_IBASE (p);
  InitTokenTable (tokens);
}

csRenderLoopLoader::~csRenderLoopLoader ()
{
  SCF_DESTRUCT_IBASE();
}

bool csRenderLoopLoader::Initialize(iObjectRegistry *object_reg)
{
  csRenderLoopLoader::object_reg = object_reg;

  synldr = CS_QUERY_REGISTRY (object_reg, iSyntaxService);
  rsp.Initialize (object_reg);

  return true;
}

bool csRenderLoopLoader::ParseRenderSteps (iRenderLoop* loop,
					   iDocumentNode* node)
{
  csRef<iRenderStepContainer> cont =
    scfQueryInterface<iRenderStepContainer> (loop);
  if (!cont)
  {
    if (synldr)
      synldr->ReportError (
	      "crystalspace.renderloop.load",
              node, "Internal error: doesn't implement iRenderStepContainer!");
    return false;
  }

  return rsp.ParseRenderSteps (cont, node);
}

csPtr<iBase> csRenderLoopLoader::Parse (iDocumentNode* node,
  iStreamSource*, iLoaderContext* ldr_context, iBase* /*context*/)
{
  csRef<iEngine> engine = CS_QUERY_REGISTRY (object_reg, iEngine);
  if (!engine)
  {
    if (synldr)
      synldr->ReportError (
	      "crystalspace.renderloop.load",
              node, "Can't find engine!");
    return 0;
  }

  iRenderLoopManager* loopmgr = engine->GetRenderLoopManager ();
  if (!loopmgr)
  {
    if (synldr)
      synldr->ReportError (
	      "crystalspace.renderloop.load",
              node, "Engine doesn't have a render loop manager!");
    return 0;
  }

  csRef<iRenderLoop> loop = loopmgr->Create ();
  csRef<iObject> obj = scfQueryInterface<iObject> (loop);
  if (ldr_context->GetRegion ())
    ldr_context->GetRegion ()->QueryObject ()->ObjAdd (obj);

  char* loopName = 0;

  if (node)
  {
    csRef<iDocumentNodeIterator> it = node->GetNodes ();
    while (it->HasNext ())
    {
      csRef<iDocumentNode> child = it->Next ();
      if (child->GetType () != CS_NODE_ELEMENT) continue;
      csStringID id = tokens.Request (child->GetValue ());
      switch (id)
      {
	case XMLTOKEN_NAME:
	  {
	    loopName = csStrNew (child->GetContentsValue ());
	  }
	  break;
	case XMLTOKEN_STEPS:
	  {
	    if (!ParseRenderSteps (loop, child))
	    {
	      goto error;
	    }
	  }
	  break;
	default:
	  if (synldr) synldr->ReportBadToken (child);
	  goto error;
      }
    }
  }

  if (loopName)
  {
    if (!loopmgr->Register (loopName, loop))
    {
      if (synldr)
      {
	synldr->Report (
	  "crystalspace.renderloop.loop.loader",
	  CS_REPORTER_SEVERITY_WARNING,
	  node,
	  "Couldn't register render loop '%s'. Maybe a loop of the same "
	  "name already exists?",
	  loopName);
      }
    }
  }
  else
  {
    if (synldr)
    {
      synldr->Report (
	"crystalspace.renderloop.loop.loader",
	CS_REPORTER_SEVERITY_WARNING,
	node,
	"Render loop has no name and is therefore inaccessible. "
	"This may not be what you want.");
    }
  }

  if (loop->GetStepCount () == 0)
  {
    if (synldr)
    {
      synldr->Report (
	"crystalspace.renderloop.loop.loader",
	CS_REPORTER_SEVERITY_WARNING,
	node,
	"Render loop has no steps. "
	"This may not be what you want.");
    }
  }

  delete[] loopName;
  return csPtr<iBase> (loop);

error:
  delete[] loopName;
  return 0;
}

<|endoftext|>