<commit_before>/*
    This file is part of Magnum.

    Original authors — credit is appreciated but not required:

        2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 —
            Vladimír Vondruš <mosra@centrum.cz>
        2020 — Nghia Truong <nghiatruong.vn@gmail.com>

    This is free and unencumbered software released into the public domain.

    Anyone is free to copy, modify, publish, use, compile, sell, or distribute
    this software, either in source code form or as a compiled binary, for any
    purpose, commercial or non-commercial, and by any means.

    In jurisdictions that recognize copyright laws, the author or authors of
    this software dedicate any and all copyright interest in the software to
    the public domain. We make this dedication for the benefit of the public
    at large and to the detriment of our heirs and successors. We intend this
    dedication to be an overt act of relinquishment in perpetuity of all
    present and future rights to this software under copyright law.

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

#include <Corrade/Containers/Optional.h>
#include <Magnum/Mesh.h>
#include <Magnum/GL/Buffer.h>
#include <Magnum/GL/DefaultFramebuffer.h>
#include <Magnum/GL/Mesh.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/Math/Color.h>
#include <Magnum/Math/Matrix4.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/SceneGraph/Camera.h>
#include <Magnum/SceneGraph/Drawable.h>
#include <Magnum/SceneGraph/MatrixTransformation3D.h>
#include <Magnum/SceneGraph/Object.h>
#include <Magnum/SceneGraph/Scene.h>
#include <Magnum/Shaders/VertexColor.h>
#include <Magnum/Shaders/MeshVisualizer.h>

#include "ArcBall.h"
#include "ArcBallCamera.h"

namespace Magnum { namespace Examples {

using Object3D = SceneGraph::Object<SceneGraph::MatrixTransformation3D>;
using Scene3D = SceneGraph::Scene<SceneGraph::MatrixTransformation3D>;

using namespace Math::Literals;

class ArcBallExample: public Platform::Application {
    public:
        explicit ArcBallExample(const Arguments& arguments);

    private:
        void drawEvent() override;
        void viewportEvent(ViewportEvent& event) override;
        void keyPressEvent(KeyEvent& event) override;
        void mousePressEvent(MouseEvent& event) override;
        void mouseReleaseEvent(MouseEvent& event) override;
        void mouseMoveEvent(MouseMoveEvent& event) override;
        void mouseScrollEvent(MouseScrollEvent& event) override;

        Scene3D _scene;
        SceneGraph::DrawableGroup3D _drawables;
        GL::Mesh _mesh{NoCreate};
        Shaders::VertexColor3D _shader{NoCreate};
        Shaders::MeshVisualizer _wireframeShader{NoCreate};
        Containers::Optional<ArcBallCamera> _arcballCamera;
};

class VertexColorDrawable: public SceneGraph::Drawable3D {
    public:
        explicit VertexColorDrawable(Object3D& object,
            Shaders::VertexColor3D& shader,
            Shaders::MeshVisualizer& wireframeShader, GL::Mesh& mesh,
            SceneGraph::DrawableGroup3D& drawables):
                SceneGraph::Drawable3D{object, &drawables}, _shader(shader),
                _wireframeShader(wireframeShader), _mesh(mesh) {}

        void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) {
            _shader
                .setTransformationProjectionMatrix(
                    camera.projectionMatrix()*transformation)
                .draw(_mesh);
            _wireframeShader
                .setTransformationProjectionMatrix(
                    camera.projectionMatrix()*transformation)
                .draw(_mesh);
        }

    private:
        Shaders::VertexColor3D& _shader;
        Shaders::MeshVisualizer& _wireframeShader;
        GL::Mesh& _mesh;
};

ArcBallExample::ArcBallExample(const Arguments& arguments) :
    Platform::Application{arguments, NoCreate}
{
    /* Setup window */
    {
        const Vector2 dpiScaling = this->dpiScaling({});
        Configuration conf;
        conf.setTitle("Magnum ArcBall Camera Example")
            .setSize(conf.size(), dpiScaling)
            .setWindowFlags(Configuration::WindowFlag::Resizable);
        GLConfiguration glConf;
        glConf.setSampleCount(dpiScaling.max() < 2.0f ? 8 : 2);
        if(!tryCreate(conf, glConf)) {
            create(conf, glConf.setSampleCount(0));
        }
    }

    GL::Renderer::enable(GL::Renderer::Feature::DepthTest);
    GL::Renderer::enable(GL::Renderer::Feature::FaceCulling);

    /* For cube wireframe vizualization */
    GL::Renderer::setDepthFunction(GL::Renderer::DepthFunction::LessOrEqual);
    GL::Renderer::setBlendEquation(GL::Renderer::BlendEquation::Add,
        GL::Renderer::BlendEquation::Add);
    GL::Renderer::setBlendFunction(GL::Renderer::BlendFunction::One,
        GL::Renderer::BlendFunction::OneMinusSourceAlpha);
    GL::Renderer::enable(GL::Renderer::Feature::Blending);

    /* Setup the cube with vertex color */
    {
        const Deg hue = 360.0_degf/8;
        const struct {
            Vector3 position;
            Color3 color;
        } cubeVertices[] {
            /* front */
            {{-1.0f, -1.0f,  1.0f}, Color3::fromHsv({hue*1.0f, 0.666f, 1.0f})},
            {{ 1.0f, -1.0f,  1.0f}, Color3::fromHsv({hue*2.0f, 0.666f, 1.0f})},
            {{ 1.0f,  1.0f,  1.0f}, Color3::fromHsv({hue*3.0f, 0.666f, 1.0f})},
            {{-1.0f,  1.0f,  1.0f}, Color3::fromHsv({hue*4.0f, 0.666f, 1.0f})},

            /* back */
            {{-1.0f, -1.0f, -1.0f}, Color3::fromHsv({hue*5.0f, 0.666f, 1.0f})},
            {{ 1.0f, -1.0f, -1.0f}, Color3::fromHsv({hue*6.0f, 0.666f, 1.0f})},
            {{ 1.0f,  1.0f, -1.0f}, Color3::fromHsv({hue*7.0f, 0.666f, 1.0f})},
            {{-1.0f,  1.0f, -1.0f}, Color3::fromHsv({hue*8.0f, 0.666f, 1.0f})}
        };

        UnsignedByte cubeIndices[]{
            /* front */
            0, 1, 2, 2, 3, 0,
            /* right */
            1, 5, 6, 6, 2, 1,
            /* back */
            7, 6, 5, 5, 4, 7,
            /* left */
            4, 0, 3, 3, 7, 4,
            /* bottom */
            4, 5, 1, 1, 0, 4,
            /* top */
            3, 2, 6, 6, 7, 3
        };

        _mesh = GL::Mesh{};
        _mesh.setCount(Containers::arraySize(cubeIndices))
            .addVertexBuffer(GL::Buffer{cubeVertices}, 0,
                Shaders::VertexColor3D::Position{},
                Shaders::VertexColor3D::Color3{})
            .setIndexBuffer(GL::Buffer{cubeIndices}, 0,
                MeshIndexType::UnsignedByte);

        _shader = Shaders::VertexColor3D{};
        _wireframeShader = Shaders::MeshVisualizer{Shaders::MeshVisualizer::Flag::Wireframe};
        _wireframeShader.setViewportSize(Vector2{framebufferSize()})
            .setColor(0x00000000_rgbaf)
            .setWireframeColor(0x000000ff_rgbaf);
        new VertexColorDrawable{*(new Object3D{&_scene}),
            _shader, _wireframeShader, _mesh, _drawables};
    }

    /* Set up the camera */
    {
        /* Setup the arcball after the camera objects */
        const Vector3 eye = Vector3::zAxis(-10.0f);
        const Vector3 center{};
        const Vector3 up = Vector3::yAxis();
        _arcballCamera.emplace(_scene, eye, center, up, 45.0_degf,
            windowSize(), framebufferSize());
    }

    /* Start the timer, loop at 60 Hz max */
    setSwapInterval(1);
    setMinimalLoopPeriod(16);
}

void ArcBallExample::drawEvent() {
    GL::defaultFramebuffer.clear(
        GL::FramebufferClear::Color|GL::FramebufferClear::Depth);

    /* Call arcball update in every frame. This will do nothing if the camera
       has not been changed. Otherwise, camera transformation will be
       propagated into the camera objects. */
    bool camChanged = _arcballCamera->update();
    _arcballCamera->draw(_drawables);
    swapBuffers();

    if(camChanged) redraw();
}

void ArcBallExample::viewportEvent(ViewportEvent& event) {
    GL::defaultFramebuffer.setViewport({{}, event.framebufferSize()});

    _arcballCamera->reshape(event.windowSize(), event.framebufferSize());
    _wireframeShader.setViewportSize(Vector2{framebufferSize()});
}

void ArcBallExample::keyPressEvent(KeyEvent& event) {
    switch(event.key()) {
        case KeyEvent::Key::L:
            if(_arcballCamera->lagging() > 0.0f) {
                Debug{} << "Lagging disabled";
                _arcballCamera->setLagging(0.0f);
            } else {
                Debug{} << "Lagging enabled";
                _arcballCamera->setLagging(0.85f);
            }
            break;
        case KeyEvent::Key::R:
            _arcballCamera->reset();
            break;

        default: return;
    }

    event.setAccepted();
    redraw(); /* camera has changed, redraw! */
}

void ArcBallExample::mousePressEvent(MouseEvent& event) {
    /* Enable mouse capture so the mouse can drag outside of the window */
    /** @todo replace once https://github.com/mosra/magnum/pull/419 is in */
    SDL_CaptureMouse(SDL_TRUE);

    _arcballCamera->initTransformation(event.position());

    event.setAccepted();
    redraw(); /* camera has changed, redraw! */
}

void ArcBallExample::mouseReleaseEvent(MouseEvent&) {
    /* Disable mouse capture again */
    /** @todo replace once https://github.com/mosra/magnum/pull/419 is in */
    SDL_CaptureMouse(SDL_FALSE);
}

void ArcBallExample::mouseMoveEvent(MouseMoveEvent& event) {
    if(!event.buttons()) return;

    if(event.modifiers() & MouseMoveEvent::Modifier::Shift)
        _arcballCamera->translate(event.position());
    else _arcballCamera->rotate(event.position());

    event.setAccepted();
    redraw(); /* camera has changed, redraw! */
}

void ArcBallExample::mouseScrollEvent(MouseScrollEvent& event) {
    const Float delta = event.offset().y();
    if(Math::abs(delta) < 1.0e-2f) return;

    _arcballCamera->zoom(delta);

    event.setAccepted();
    redraw(); /* camera has changed, redraw! */
}

}}

MAGNUM_APPLICATION_MAIN(Magnum::Examples::ArcBallExample)
<commit_msg>arcball: adapt to Magnum changes.<commit_after>/*
    This file is part of Magnum.

    Original authors — credit is appreciated but not required:

        2010, 2011, 2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019 —
            Vladimír Vondruš <mosra@centrum.cz>
        2020 — Nghia Truong <nghiatruong.vn@gmail.com>

    This is free and unencumbered software released into the public domain.

    Anyone is free to copy, modify, publish, use, compile, sell, or distribute
    this software, either in source code form or as a compiled binary, for any
    purpose, commercial or non-commercial, and by any means.

    In jurisdictions that recognize copyright laws, the author or authors of
    this software dedicate any and all copyright interest in the software to
    the public domain. We make this dedication for the benefit of the public
    at large and to the detriment of our heirs and successors. We intend this
    dedication to be an overt act of relinquishment in perpetuity of all
    present and future rights to this software under copyright law.

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

#include <Corrade/Containers/Optional.h>
#include <Magnum/Mesh.h>
#include <Magnum/GL/Buffer.h>
#include <Magnum/GL/DefaultFramebuffer.h>
#include <Magnum/GL/Mesh.h>
#include <Magnum/GL/Renderer.h>
#include <Magnum/Math/Color.h>
#include <Magnum/Math/Matrix4.h>
#include <Magnum/Platform/Sdl2Application.h>
#include <Magnum/SceneGraph/Camera.h>
#include <Magnum/SceneGraph/Drawable.h>
#include <Magnum/SceneGraph/MatrixTransformation3D.h>
#include <Magnum/SceneGraph/Object.h>
#include <Magnum/SceneGraph/Scene.h>
#include <Magnum/Shaders/VertexColor.h>
#include <Magnum/Shaders/MeshVisualizer.h>

#include "ArcBall.h"
#include "ArcBallCamera.h"

namespace Magnum { namespace Examples {

using Object3D = SceneGraph::Object<SceneGraph::MatrixTransformation3D>;
using Scene3D = SceneGraph::Scene<SceneGraph::MatrixTransformation3D>;

using namespace Math::Literals;

class ArcBallExample: public Platform::Application {
    public:
        explicit ArcBallExample(const Arguments& arguments);

    private:
        void drawEvent() override;
        void viewportEvent(ViewportEvent& event) override;
        void keyPressEvent(KeyEvent& event) override;
        void mousePressEvent(MouseEvent& event) override;
        void mouseReleaseEvent(MouseEvent& event) override;
        void mouseMoveEvent(MouseMoveEvent& event) override;
        void mouseScrollEvent(MouseScrollEvent& event) override;

        Scene3D _scene;
        SceneGraph::DrawableGroup3D _drawables;
        GL::Mesh _mesh{NoCreate};
        Shaders::VertexColor3D _shader{NoCreate};
        Shaders::MeshVisualizer3D _wireframeShader{NoCreate};
        Containers::Optional<ArcBallCamera> _arcballCamera;
};

class VertexColorDrawable: public SceneGraph::Drawable3D {
    public:
        explicit VertexColorDrawable(Object3D& object,
            Shaders::VertexColor3D& shader,
            Shaders::MeshVisualizer3D& wireframeShader, GL::Mesh& mesh,
            SceneGraph::DrawableGroup3D& drawables):
                SceneGraph::Drawable3D{object, &drawables}, _shader(shader),
                _wireframeShader(wireframeShader), _mesh(mesh) {}

        void draw(const Matrix4& transformation, SceneGraph::Camera3D& camera) {
            _shader
                .setTransformationProjectionMatrix(
                    camera.projectionMatrix()*transformation)
                .draw(_mesh);
            _wireframeShader
                .setTransformationMatrix(transformation)
                .setProjectionMatrix(camera.projectionMatrix())
                .draw(_mesh);
        }

    private:
        Shaders::VertexColor3D& _shader;
        Shaders::MeshVisualizer3D& _wireframeShader;
        GL::Mesh& _mesh;
};

ArcBallExample::ArcBallExample(const Arguments& arguments) :
    Platform::Application{arguments, NoCreate}
{
    /* Setup window */
    {
        const Vector2 dpiScaling = this->dpiScaling({});
        Configuration conf;
        conf.setTitle("Magnum ArcBall Camera Example")
            .setSize(conf.size(), dpiScaling)
            .setWindowFlags(Configuration::WindowFlag::Resizable);
        GLConfiguration glConf;
        glConf.setSampleCount(dpiScaling.max() < 2.0f ? 8 : 2);
        if(!tryCreate(conf, glConf)) {
            create(conf, glConf.setSampleCount(0));
        }
    }

    GL::Renderer::enable(GL::Renderer::Feature::DepthTest);
    GL::Renderer::enable(GL::Renderer::Feature::FaceCulling);

    /* For cube wireframe vizualization */
    GL::Renderer::setDepthFunction(GL::Renderer::DepthFunction::LessOrEqual);
    GL::Renderer::setBlendEquation(GL::Renderer::BlendEquation::Add,
        GL::Renderer::BlendEquation::Add);
    GL::Renderer::setBlendFunction(GL::Renderer::BlendFunction::One,
        GL::Renderer::BlendFunction::OneMinusSourceAlpha);
    GL::Renderer::enable(GL::Renderer::Feature::Blending);

    /* Setup the cube with vertex color */
    {
        const Deg hue = 360.0_degf/8;
        const struct {
            Vector3 position;
            Color3 color;
        } cubeVertices[] {
            /* front */
            {{-1.0f, -1.0f,  1.0f}, Color3::fromHsv({hue*1.0f, 0.666f, 1.0f})},
            {{ 1.0f, -1.0f,  1.0f}, Color3::fromHsv({hue*2.0f, 0.666f, 1.0f})},
            {{ 1.0f,  1.0f,  1.0f}, Color3::fromHsv({hue*3.0f, 0.666f, 1.0f})},
            {{-1.0f,  1.0f,  1.0f}, Color3::fromHsv({hue*4.0f, 0.666f, 1.0f})},

            /* back */
            {{-1.0f, -1.0f, -1.0f}, Color3::fromHsv({hue*5.0f, 0.666f, 1.0f})},
            {{ 1.0f, -1.0f, -1.0f}, Color3::fromHsv({hue*6.0f, 0.666f, 1.0f})},
            {{ 1.0f,  1.0f, -1.0f}, Color3::fromHsv({hue*7.0f, 0.666f, 1.0f})},
            {{-1.0f,  1.0f, -1.0f}, Color3::fromHsv({hue*8.0f, 0.666f, 1.0f})}
        };

        UnsignedByte cubeIndices[]{
            /* front */
            0, 1, 2, 2, 3, 0,
            /* right */
            1, 5, 6, 6, 2, 1,
            /* back */
            7, 6, 5, 5, 4, 7,
            /* left */
            4, 0, 3, 3, 7, 4,
            /* bottom */
            4, 5, 1, 1, 0, 4,
            /* top */
            3, 2, 6, 6, 7, 3
        };

        _mesh = GL::Mesh{};
        _mesh.setCount(Containers::arraySize(cubeIndices))
            .addVertexBuffer(GL::Buffer{cubeVertices}, 0,
                Shaders::VertexColor3D::Position{},
                Shaders::VertexColor3D::Color3{})
            .setIndexBuffer(GL::Buffer{cubeIndices}, 0,
                MeshIndexType::UnsignedByte);

        _shader = Shaders::VertexColor3D{};
        _wireframeShader = Shaders::MeshVisualizer3D{Shaders::MeshVisualizer3D::Flag::Wireframe};
        _wireframeShader.setViewportSize(Vector2{framebufferSize()})
            .setColor(0x00000000_rgbaf)
            .setWireframeColor(0x000000ff_rgbaf);
        new VertexColorDrawable{*(new Object3D{&_scene}),
            _shader, _wireframeShader, _mesh, _drawables};
    }

    /* Set up the camera */
    {
        /* Setup the arcball after the camera objects */
        const Vector3 eye = Vector3::zAxis(-10.0f);
        const Vector3 center{};
        const Vector3 up = Vector3::yAxis();
        _arcballCamera.emplace(_scene, eye, center, up, 45.0_degf,
            windowSize(), framebufferSize());
    }

    /* Start the timer, loop at 60 Hz max */
    setSwapInterval(1);
    setMinimalLoopPeriod(16);
}

void ArcBallExample::drawEvent() {
    GL::defaultFramebuffer.clear(
        GL::FramebufferClear::Color|GL::FramebufferClear::Depth);

    /* Call arcball update in every frame. This will do nothing if the camera
       has not been changed. Otherwise, camera transformation will be
       propagated into the camera objects. */
    bool camChanged = _arcballCamera->update();
    _arcballCamera->draw(_drawables);
    swapBuffers();

    if(camChanged) redraw();
}

void ArcBallExample::viewportEvent(ViewportEvent& event) {
    GL::defaultFramebuffer.setViewport({{}, event.framebufferSize()});

    _arcballCamera->reshape(event.windowSize(), event.framebufferSize());
    _wireframeShader.setViewportSize(Vector2{framebufferSize()});
}

void ArcBallExample::keyPressEvent(KeyEvent& event) {
    switch(event.key()) {
        case KeyEvent::Key::L:
            if(_arcballCamera->lagging() > 0.0f) {
                Debug{} << "Lagging disabled";
                _arcballCamera->setLagging(0.0f);
            } else {
                Debug{} << "Lagging enabled";
                _arcballCamera->setLagging(0.85f);
            }
            break;
        case KeyEvent::Key::R:
            _arcballCamera->reset();
            break;

        default: return;
    }

    event.setAccepted();
    redraw(); /* camera has changed, redraw! */
}

void ArcBallExample::mousePressEvent(MouseEvent& event) {
    /* Enable mouse capture so the mouse can drag outside of the window */
    /** @todo replace once https://github.com/mosra/magnum/pull/419 is in */
    SDL_CaptureMouse(SDL_TRUE);

    _arcballCamera->initTransformation(event.position());

    event.setAccepted();
    redraw(); /* camera has changed, redraw! */
}

void ArcBallExample::mouseReleaseEvent(MouseEvent&) {
    /* Disable mouse capture again */
    /** @todo replace once https://github.com/mosra/magnum/pull/419 is in */
    SDL_CaptureMouse(SDL_FALSE);
}

void ArcBallExample::mouseMoveEvent(MouseMoveEvent& event) {
    if(!event.buttons()) return;

    if(event.modifiers() & MouseMoveEvent::Modifier::Shift)
        _arcballCamera->translate(event.position());
    else _arcballCamera->rotate(event.position());

    event.setAccepted();
    redraw(); /* camera has changed, redraw! */
}

void ArcBallExample::mouseScrollEvent(MouseScrollEvent& event) {
    const Float delta = event.offset().y();
    if(Math::abs(delta) < 1.0e-2f) return;

    _arcballCamera->zoom(delta);

    event.setAccepted();
    redraw(); /* camera has changed, redraw! */
}

}}

MAGNUM_APPLICATION_MAIN(Magnum::Examples::ArcBallExample)
<|endoftext|>


<commit_before>//===- ExecutionEngineTest.cpp - Unit tests for ExecutionEngine -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/ExecutionEngine/Interpreter.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "gtest/gtest.h"

using namespace llvm;

namespace {

class ExecutionEngineTest : public testing::Test {
protected:
  ExecutionEngineTest() {
    auto Owner = make_unique<Module>("<main>", getGlobalContext());
    M = Owner.get();
    Engine.reset(EngineBuilder(std::move(Owner)).setErrorStr(&Error).create());
  }

  virtual void SetUp() {
    ASSERT_TRUE(Engine.get() != nullptr) << "EngineBuilder returned error: '"
      << Error << "'";
  }

  GlobalVariable *NewExtGlobal(Type *T, const Twine &Name) {
    return new GlobalVariable(*M, T, false,  // Not constant.
                              GlobalValue::ExternalLinkage, nullptr, Name);
  }

  std::string Error;
  Module *M;  // Owned by ExecutionEngine.
  std::unique_ptr<ExecutionEngine> Engine;
};

TEST_F(ExecutionEngineTest, ForwardGlobalMapping) {
  GlobalVariable *G1 =
      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
  int32_t Mem1 = 3;
  Engine->addGlobalMapping(G1, &Mem1);
  EXPECT_EQ(&Mem1, Engine->getPointerToGlobalIfAvailable(G1));
  int32_t Mem2 = 4;
  Engine->updateGlobalMapping(G1, &Mem2);
  EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1));
  Engine->updateGlobalMapping(G1, nullptr);
  EXPECT_EQ(nullptr, Engine->getPointerToGlobalIfAvailable(G1));
  Engine->updateGlobalMapping(G1, &Mem2);
  EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1));

  GlobalVariable *G2 =
      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
  EXPECT_EQ(nullptr, Engine->getPointerToGlobalIfAvailable(G2))
    << "The NULL return shouldn't depend on having called"
    << " updateGlobalMapping(..., NULL)";
  // Check that update...() can be called before add...().
  Engine->updateGlobalMapping(G2, &Mem1);
  EXPECT_EQ(&Mem1, Engine->getPointerToGlobalIfAvailable(G2));
  EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1))
    << "A second mapping shouldn't affect the first.";
}

TEST_F(ExecutionEngineTest, ReverseGlobalMapping) {
  GlobalVariable *G1 =
      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");

  int32_t Mem1 = 3;
  Engine->addGlobalMapping(G1, &Mem1);
  EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem1));
  int32_t Mem2 = 4;
  Engine->updateGlobalMapping(G1, &Mem2);
  EXPECT_EQ(nullptr, Engine->getGlobalValueAtAddress(&Mem1));
  EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem2));

  GlobalVariable *G2 =
      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global2");
  Engine->updateGlobalMapping(G2, &Mem1);
  EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1));
  EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem2));
  Engine->updateGlobalMapping(G1, nullptr);
  EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1))
    << "Removing one mapping doesn't affect a different one.";
  EXPECT_EQ(nullptr, Engine->getGlobalValueAtAddress(&Mem2));
  Engine->updateGlobalMapping(G2, &Mem2);
  EXPECT_EQ(nullptr, Engine->getGlobalValueAtAddress(&Mem1));
  EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem2))
    << "Once a mapping is removed, we can point another GV at the"
    << " now-free address.";
}

TEST_F(ExecutionEngineTest, ClearModuleMappings) {
  GlobalVariable *G1 =
      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");

  int32_t Mem1 = 3;
  Engine->addGlobalMapping(G1, &Mem1);
  EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem1));

  Engine->clearGlobalMappingsFromModule(M);

  EXPECT_EQ(nullptr, Engine->getGlobalValueAtAddress(&Mem1));

  GlobalVariable *G2 =
      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global2");
  // After clearing the module mappings, we can assign a new GV to the
  // same address.
  Engine->addGlobalMapping(G2, &Mem1);
  EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1));
}

TEST_F(ExecutionEngineTest, DestructionRemovesGlobalMapping) {
  GlobalVariable *G1 =
    NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
  int32_t Mem1 = 3;
  Engine->addGlobalMapping(G1, &Mem1);
  // Make sure the reverse mapping is enabled.
  EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem1));
  // When the GV goes away, the ExecutionEngine should remove any
  // mappings that refer to it.
  G1->eraseFromParent();
  EXPECT_EQ(nullptr, Engine->getGlobalValueAtAddress(&Mem1));
}

}
<commit_msg>ExecutionEngineTests: Call llvm_shutdown() on exit for ManagedStatic introduced in r218151.<commit_after>//===- ExecutionEngineTest.cpp - Unit tests for ExecutionEngine -----------===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

#include "llvm/ExecutionEngine/Interpreter.h"
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/GlobalVariable.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/ManagedStatic.h"
#include "gtest/gtest.h"

using namespace llvm;

static llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.

namespace {

class ExecutionEngineTest : public testing::Test {
protected:
  ExecutionEngineTest() {
    auto Owner = make_unique<Module>("<main>", getGlobalContext());
    M = Owner.get();
    Engine.reset(EngineBuilder(std::move(Owner)).setErrorStr(&Error).create());
  }

  virtual void SetUp() {
    ASSERT_TRUE(Engine.get() != nullptr) << "EngineBuilder returned error: '"
      << Error << "'";
  }

  GlobalVariable *NewExtGlobal(Type *T, const Twine &Name) {
    return new GlobalVariable(*M, T, false,  // Not constant.
                              GlobalValue::ExternalLinkage, nullptr, Name);
  }

  std::string Error;
  Module *M;  // Owned by ExecutionEngine.
  std::unique_ptr<ExecutionEngine> Engine;
};

TEST_F(ExecutionEngineTest, ForwardGlobalMapping) {
  GlobalVariable *G1 =
      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
  int32_t Mem1 = 3;
  Engine->addGlobalMapping(G1, &Mem1);
  EXPECT_EQ(&Mem1, Engine->getPointerToGlobalIfAvailable(G1));
  int32_t Mem2 = 4;
  Engine->updateGlobalMapping(G1, &Mem2);
  EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1));
  Engine->updateGlobalMapping(G1, nullptr);
  EXPECT_EQ(nullptr, Engine->getPointerToGlobalIfAvailable(G1));
  Engine->updateGlobalMapping(G1, &Mem2);
  EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1));

  GlobalVariable *G2 =
      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
  EXPECT_EQ(nullptr, Engine->getPointerToGlobalIfAvailable(G2))
    << "The NULL return shouldn't depend on having called"
    << " updateGlobalMapping(..., NULL)";
  // Check that update...() can be called before add...().
  Engine->updateGlobalMapping(G2, &Mem1);
  EXPECT_EQ(&Mem1, Engine->getPointerToGlobalIfAvailable(G2));
  EXPECT_EQ(&Mem2, Engine->getPointerToGlobalIfAvailable(G1))
    << "A second mapping shouldn't affect the first.";
}

TEST_F(ExecutionEngineTest, ReverseGlobalMapping) {
  GlobalVariable *G1 =
      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");

  int32_t Mem1 = 3;
  Engine->addGlobalMapping(G1, &Mem1);
  EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem1));
  int32_t Mem2 = 4;
  Engine->updateGlobalMapping(G1, &Mem2);
  EXPECT_EQ(nullptr, Engine->getGlobalValueAtAddress(&Mem1));
  EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem2));

  GlobalVariable *G2 =
      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global2");
  Engine->updateGlobalMapping(G2, &Mem1);
  EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1));
  EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem2));
  Engine->updateGlobalMapping(G1, nullptr);
  EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1))
    << "Removing one mapping doesn't affect a different one.";
  EXPECT_EQ(nullptr, Engine->getGlobalValueAtAddress(&Mem2));
  Engine->updateGlobalMapping(G2, &Mem2);
  EXPECT_EQ(nullptr, Engine->getGlobalValueAtAddress(&Mem1));
  EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem2))
    << "Once a mapping is removed, we can point another GV at the"
    << " now-free address.";
}

TEST_F(ExecutionEngineTest, ClearModuleMappings) {
  GlobalVariable *G1 =
      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");

  int32_t Mem1 = 3;
  Engine->addGlobalMapping(G1, &Mem1);
  EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem1));

  Engine->clearGlobalMappingsFromModule(M);

  EXPECT_EQ(nullptr, Engine->getGlobalValueAtAddress(&Mem1));

  GlobalVariable *G2 =
      NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global2");
  // After clearing the module mappings, we can assign a new GV to the
  // same address.
  Engine->addGlobalMapping(G2, &Mem1);
  EXPECT_EQ(G2, Engine->getGlobalValueAtAddress(&Mem1));
}

TEST_F(ExecutionEngineTest, DestructionRemovesGlobalMapping) {
  GlobalVariable *G1 =
    NewExtGlobal(Type::getInt32Ty(getGlobalContext()), "Global1");
  int32_t Mem1 = 3;
  Engine->addGlobalMapping(G1, &Mem1);
  // Make sure the reverse mapping is enabled.
  EXPECT_EQ(G1, Engine->getGlobalValueAtAddress(&Mem1));
  // When the GV goes away, the ExecutionEngine should remove any
  // mappings that refer to it.
  G1->eraseFromParent();
  EXPECT_EQ(nullptr, Engine->getGlobalValueAtAddress(&Mem1));
}

}
<|endoftext|>


<commit_before>

#include <iostream>
#include <cstdlib>
#include "drake/systems/plants/RigidBodyTree.h"

using namespace std;

int main(int argc, char* argv[]) {
  if (argc < 2) {
    cerr << "Usage: urdfCollisionTest urdf_filename" << endl;
    exit(-1);
  }
  RigidBodyTree* model = new RigidBodyTree(argv[1]);
  if (!model) {
    cerr << "ERROR: Failed to load model from " << argv[1] << endl;
    return -1;
  }

  // run kinematics with second derivatives 100 times
  Eigen::VectorXd q = model->getZeroConfiguration();
  int i;

  if (argc >= 2 + model->num_positions) {
    for (i = 0; i < model->num_positions; i++)
      sscanf(argv[2 + i], "%lf", &q(i));
  }

  // for (i=0; i<model->num_dof; i++)
  // 	 q(i)=(double)rand() / RAND_MAX;
  KinematicsCache<double> cache = model->doKinematics(q);
  //  }

  Eigen::VectorXd phi;
  Eigen::Matrix3Xd normal, xA, xB;
  vector<int> bodyA_idx, bodyB_idx;

  model->collisionDetect(cache, phi, normal, xA, xB, bodyA_idx, bodyB_idx);

  cout << "=======" << endl;
  for (int j = 0; j < phi.rows(); ++j) {
    cout << phi(j) << " ";
    for (int i = 0; i < 3; ++i) {
      cout << normal(i, j) << " ";
    }
    for (int i = 0; i < 3; ++i) {
      cout << xA(i, j) << " ";
    }
    for (int i = 0; i < 3; ++i) {
      cout << xB(i, j) << " ";
    }
    cout << model->bodies[bodyA_idx.at(j)]->linkname << " ";
    cout << model->bodies[bodyB_idx.at(j)]->linkname << endl;
  }

  delete model;
  return 0;
}
<commit_msg>Remove literal tabs from urdfCollisionTest.cpp.<commit_after>

#include <iostream>
#include <cstdlib>
#include "drake/systems/plants/RigidBodyTree.h"

using namespace std;

int main(int argc, char* argv[]) {
  if (argc < 2) {
    cerr << "Usage: urdfCollisionTest urdf_filename" << endl;
    exit(-1);
  }
  RigidBodyTree* model = new RigidBodyTree(argv[1]);
  if (!model) {
    cerr << "ERROR: Failed to load model from " << argv[1] << endl;
    return -1;
  }

  // run kinematics with second derivatives 100 times
  Eigen::VectorXd q = model->getZeroConfiguration();
  int i;

  if (argc >= 2 + model->num_positions) {
    for (i = 0; i < model->num_positions; i++)
      sscanf(argv[2 + i], "%lf", &q(i));
  }

  // for (i=0; i<model->num_dof; i++)
  //   q(i)=(double)rand() / RAND_MAX;
  KinematicsCache<double> cache = model->doKinematics(q);
  //  }

  Eigen::VectorXd phi;
  Eigen::Matrix3Xd normal, xA, xB;
  vector<int> bodyA_idx, bodyB_idx;

  model->collisionDetect(cache, phi, normal, xA, xB, bodyA_idx, bodyB_idx);

  cout << "=======" << endl;
  for (int j = 0; j < phi.rows(); ++j) {
    cout << phi(j) << " ";
    for (int i = 0; i < 3; ++i) {
      cout << normal(i, j) << " ";
    }
    for (int i = 0; i < 3; ++i) {
      cout << xA(i, j) << " ";
    }
    for (int i = 0; i < 3; ++i) {
      cout << xB(i, j) << " ";
    }
    cout << model->bodies[bodyA_idx.at(j)]->linkname << " ";
    cout << model->bodies[bodyB_idx.at(j)]->linkname << endl;
  }

  delete model;
  return 0;
}
<|endoftext|>


<commit_before>/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2013-2019 Couchbase, Inc.
 *
 *   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.
 */

#include "internal.h"
#include "clconfig.h"
#include <lcbio/lcbio.h>
#include <lcbio/timer-ng.h>
#include <lcbio/timer-cxx.h>
#include <fstream>
#include <iostream>
#include <istream>
#include <cstring>

#define CONFIG_CACHE_MAGIC "{{{fb85b563d0a8f65fa8d3d58f1b3a0708}}}"

#define LOGARGS(pb, lvl) static_cast< Provider * >(pb)->parent->settings, "bc_file", LCB_LOG_##lvl, __FILE__, __LINE__
#define LOGFMT "(cache=%s) "
#define LOGID(fb) fb->filename.c_str()

using namespace lcb::clconfig;

struct FileProvider : Provider, Listener {
    FileProvider(Confmon *confmon);
    ~FileProvider();

    enum Status { CACHE_ERROR, NO_CHANGES, UPDATED };
    Status load_cache();
    void reload_cache();
    void maybe_remove_file()
    {
        if (!is_readonly && !filename.empty()) {
            remove(filename.c_str());
        }
    }
    void write_cache(lcbvb_CONFIG *vbc);

    /* Overrides */
    ConfigInfo *get_cached();
    lcb_STATUS refresh();
    void dump(FILE *) const;
    void clconfig_lsn(EventType, ConfigInfo *);

    std::string filename;
    ConfigInfo *config;
    time_t last_mtime;
    int last_errno;
    bool is_readonly; /* Whether the config cache should _not_ overwrite the file */
    lcb::io::Timer< FileProvider, &FileProvider::reload_cache > timer;
};

FileProvider::Status FileProvider::load_cache()
{
    if (filename.empty()) {
        return CACHE_ERROR;
    }

    std::ifstream ifs(filename.c_str(), std::ios::in | std::ios::binary | std::ios::ate);

    if (!ifs.is_open() || !ifs.good()) {
        int save_errno = last_errno = errno;
        lcb_log(LOGARGS(this, ERROR), LOGFMT "Couldn't open for reading: %s", LOGID(this), strerror(save_errno));
        return CACHE_ERROR;
    }

    struct stat st;
    if (stat(filename.c_str(), &st)) {
        last_errno = errno;
        return CACHE_ERROR;
    }

    if (last_mtime == st.st_mtime) {
        lcb_log(LOGARGS(this, DEBUG), LOGFMT "Modification time too old", LOGID(this));
        return NO_CHANGES;
    }

    size_t fsize = ifs.tellg();
    if (!fsize) {
        lcb_log(LOGARGS(this, WARN), LOGFMT "File '%s' is empty", LOGID(this), filename.c_str());
        return CACHE_ERROR;
    }
    ifs.seekg(0, std::ios::beg);
    std::vector< char > buf(fsize);
    ifs.read(&buf[0], fsize);
    buf.push_back(0); // NUL termination

    char *end = std::strstr(&buf[0], CONFIG_CACHE_MAGIC);
    if (end == NULL) {
        lcb_log(LOGARGS(this, ERROR), LOGFMT "Couldn't find magic", LOGID(this));
        maybe_remove_file();
        return CACHE_ERROR;
    }
    *end = '\0'; // Stop parsing at MAGIC

    lcbvb_CONFIG *vbc = lcbvb_create();
    if (vbc == NULL) {
        return CACHE_ERROR;
    }

    Status status = CACHE_ERROR;

    if (lcbvb_load_json(vbc, &buf[0]) != 0) {
        lcb_log(LOGARGS(this, ERROR), LOGFMT "Couldn't parse configuration", LOGID(this));
        lcb_log_badconfig(LOGARGS(this, ERROR), vbc, &buf[0]);
        maybe_remove_file();
        goto GT_DONE;
    }

    if (lcbvb_get_distmode(vbc) != LCBVB_DIST_VBUCKET) {
        lcb_log(LOGARGS(this, ERROR), LOGFMT "Not applying cached memcached config", LOGID(this));
        goto GT_DONE;
    }

    if (strcmp(vbc->bname, settings().bucket) != 0) {
        lcb_log(LOGARGS(this, ERROR), LOGFMT "Bucket name in file is different from the one requested", LOGID(this));
        goto GT_DONE;
    }

    if (config) {
        config->decref();
    }

    config = ConfigInfo::create(vbc, CLCONFIG_FILE);
    last_mtime = st.st_mtime;

    status = UPDATED;
    vbc = NULL;

GT_DONE:
    if (vbc != NULL) {
        lcbvb_destroy(vbc);
    }
    return status;
}

void FileProvider::write_cache(lcbvb_CONFIG *cfg)
{
    if (filename.empty() || is_readonly) {
        return;
    }

    std::ofstream ofs(filename.c_str(), std::ios::trunc);
    if (ofs.good()) {
        lcb_log(LOGARGS(this, INFO), LOGFMT "Writing configuration to file", LOGID(this));
        char *json = lcbvb_save_json(cfg);
        ofs << json;
        ofs << CONFIG_CACHE_MAGIC;
        free(json);
    } else {
        int save_errno = errno;
        lcb_log(LOGARGS(this, ERROR), LOGFMT "Couldn't open file for writing: %s", LOGID(this), strerror(save_errno));
    }
}

ConfigInfo *FileProvider::get_cached()
{
    return filename.empty() ? NULL : config;
}

void FileProvider::reload_cache()
{
    if (load_cache() == UPDATED) {
        parent->provider_got_config(this, config);
    } else {
        parent->provider_failed(this, LCB_ERROR);
    }
}

lcb_STATUS FileProvider::refresh()
{
    if (!timer.is_armed()) {
        timer.signal();
    }
    return LCB_SUCCESS;
}

FileProvider::~FileProvider()
{
    timer.release();
    if (config) {
        config->decref();
    }
}

void FileProvider::clconfig_lsn(EventType event, ConfigInfo *info)
{
    if (event != CLCONFIG_EVENT_GOT_NEW_CONFIG) {
        return;
    }
    if (!enabled) {
        return;
    }

    if (info->get_origin() == CLCONFIG_PHONY || info->get_origin() == CLCONFIG_FILE) {
        lcb_log(LOGARGS(this, TRACE), "Not writing configuration originating from PHONY or FILE to cache");
        return;
    }

    write_cache(info->vbc);
}

void FileProvider::dump(FILE *fp) const
{
    fprintf(fp, "## BEGIN FILE PROVIEDER DUMP ##\n");
    if (!filename.empty()) {
        fprintf(fp, "FILENAME: %s\n", filename.c_str());
    }
    fprintf(fp, "LAST SYSTEM ERRNO: %d\n", last_errno);
    fprintf(fp, "LAST MTIME: %lu\n", (unsigned long)last_mtime);
    fprintf(fp, "## END FILE PROVIDER DUMP ##\n");
}

FileProvider::FileProvider(Confmon *parent_)
    : Provider(parent_, CLCONFIG_FILE), config(NULL), last_mtime(0), last_errno(0), is_readonly(false),
      timer(parent_->iot, this)
{
    parent->add_listener(this);
}

static std::string mkcachefile(const char *name, const char *bucket)
{
    std::string buffer;
    bool is_dir = false;
    if (name != NULL) {
        buffer = std::string(name);
        if (buffer.back() == '/') {
            is_dir = true;
        }
    } else {
        buffer = lcb_get_tmpdir();
        if (buffer.empty()) {
            buffer += ".";
        }
        buffer += "/";
        is_dir = true;
    }
    if (is_dir) {
        // append bucket name only if we know that
        // cachefile is directory
        buffer += bucket;
    }

    return buffer;
}

bool lcb::clconfig::file_set_filename(Provider *p, const char *f, bool ro)
{
    FileProvider *provider = static_cast< FileProvider * >(p);
    provider->enabled = 1;
    provider->filename = mkcachefile(f, p->parent->settings->bucket);
    provider->is_readonly = bool(ro);

    if (ro) {
        FILE *fp_tmp = fopen(provider->filename.c_str(), "r");
        if (!fp_tmp) {
            lcb_log(LOGARGS(provider, ERROR), LOGFMT "Couldn't open for reading: %s", LOGID(provider), strerror(errno));
            return false;
        } else {
            fclose(fp_tmp);
        }
    }
    return true;
}

const char *lcb::clconfig::file_get_filename(Provider *p)
{
    FileProvider *fp = static_cast< FileProvider * >(p);
    if (fp->filename.empty()) {
        return NULL;
    } else {
        return fp->filename.c_str();
    }
}

void lcb::clconfig::file_set_readonly(Provider *p, bool val)
{
    static_cast< FileProvider * >(p)->is_readonly = val;
}

Provider *lcb::clconfig::new_file_provider(Confmon *mon)
{
    return new FileProvider(mon);
}
<commit_msg>Fix build on CentOS 6<commit_after>/* -*- Mode: C; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2013-2019 Couchbase, Inc.
 *
 *   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.
 */

#include "internal.h"
#include "clconfig.h"
#include <lcbio/lcbio.h>
#include <lcbio/timer-ng.h>
#include <lcbio/timer-cxx.h>
#include <fstream>
#include <iostream>
#include <istream>
#include <cstring>

#define CONFIG_CACHE_MAGIC "{{{fb85b563d0a8f65fa8d3d58f1b3a0708}}}"

#define LOGARGS(pb, lvl) static_cast< Provider * >(pb)->parent->settings, "bc_file", LCB_LOG_##lvl, __FILE__, __LINE__
#define LOGFMT "(cache=%s) "
#define LOGID(fb) fb->filename.c_str()

using namespace lcb::clconfig;

struct FileProvider : Provider, Listener {
    FileProvider(Confmon *confmon);
    ~FileProvider();

    enum Status { CACHE_ERROR, NO_CHANGES, UPDATED };
    Status load_cache();
    void reload_cache();
    void maybe_remove_file()
    {
        if (!is_readonly && !filename.empty()) {
            remove(filename.c_str());
        }
    }
    void write_cache(lcbvb_CONFIG *vbc);

    /* Overrides */
    ConfigInfo *get_cached();
    lcb_STATUS refresh();
    void dump(FILE *) const;
    void clconfig_lsn(EventType, ConfigInfo *);

    std::string filename;
    ConfigInfo *config;
    time_t last_mtime;
    int last_errno;
    bool is_readonly; /* Whether the config cache should _not_ overwrite the file */
    lcb::io::Timer< FileProvider, &FileProvider::reload_cache > timer;
};

FileProvider::Status FileProvider::load_cache()
{
    if (filename.empty()) {
        return CACHE_ERROR;
    }

    std::ifstream ifs(filename.c_str(), std::ios::in | std::ios::binary | std::ios::ate);

    if (!ifs.is_open() || !ifs.good()) {
        int save_errno = last_errno = errno;
        lcb_log(LOGARGS(this, ERROR), LOGFMT "Couldn't open for reading: %s", LOGID(this), strerror(save_errno));
        return CACHE_ERROR;
    }

    struct stat st;
    if (stat(filename.c_str(), &st)) {
        last_errno = errno;
        return CACHE_ERROR;
    }

    if (last_mtime == st.st_mtime) {
        lcb_log(LOGARGS(this, DEBUG), LOGFMT "Modification time too old", LOGID(this));
        return NO_CHANGES;
    }

    size_t fsize = ifs.tellg();
    if (!fsize) {
        lcb_log(LOGARGS(this, WARN), LOGFMT "File '%s' is empty", LOGID(this), filename.c_str());
        return CACHE_ERROR;
    }
    ifs.seekg(0, std::ios::beg);
    std::vector< char > buf(fsize);
    ifs.read(&buf[0], fsize);
    buf.push_back(0); // NUL termination

    char *end = std::strstr(&buf[0], CONFIG_CACHE_MAGIC);
    if (end == NULL) {
        lcb_log(LOGARGS(this, ERROR), LOGFMT "Couldn't find magic", LOGID(this));
        maybe_remove_file();
        return CACHE_ERROR;
    }
    *end = '\0'; // Stop parsing at MAGIC

    lcbvb_CONFIG *vbc = lcbvb_create();
    if (vbc == NULL) {
        return CACHE_ERROR;
    }

    Status status = CACHE_ERROR;

    if (lcbvb_load_json(vbc, &buf[0]) != 0) {
        lcb_log(LOGARGS(this, ERROR), LOGFMT "Couldn't parse configuration", LOGID(this));
        lcb_log_badconfig(LOGARGS(this, ERROR), vbc, &buf[0]);
        maybe_remove_file();
        goto GT_DONE;
    }

    if (lcbvb_get_distmode(vbc) != LCBVB_DIST_VBUCKET) {
        lcb_log(LOGARGS(this, ERROR), LOGFMT "Not applying cached memcached config", LOGID(this));
        goto GT_DONE;
    }

    if (strcmp(vbc->bname, settings().bucket) != 0) {
        lcb_log(LOGARGS(this, ERROR), LOGFMT "Bucket name in file is different from the one requested", LOGID(this));
        goto GT_DONE;
    }

    if (config) {
        config->decref();
    }

    config = ConfigInfo::create(vbc, CLCONFIG_FILE);
    last_mtime = st.st_mtime;

    status = UPDATED;
    vbc = NULL;

GT_DONE:
    if (vbc != NULL) {
        lcbvb_destroy(vbc);
    }
    return status;
}

void FileProvider::write_cache(lcbvb_CONFIG *cfg)
{
    if (filename.empty() || is_readonly) {
        return;
    }

    std::ofstream ofs(filename.c_str(), std::ios::trunc);
    if (ofs.good()) {
        lcb_log(LOGARGS(this, INFO), LOGFMT "Writing configuration to file", LOGID(this));
        char *json = lcbvb_save_json(cfg);
        ofs << json;
        ofs << CONFIG_CACHE_MAGIC;
        free(json);
    } else {
        int save_errno = errno;
        lcb_log(LOGARGS(this, ERROR), LOGFMT "Couldn't open file for writing: %s", LOGID(this), strerror(save_errno));
    }
}

ConfigInfo *FileProvider::get_cached()
{
    return filename.empty() ? NULL : config;
}

void FileProvider::reload_cache()
{
    if (load_cache() == UPDATED) {
        parent->provider_got_config(this, config);
    } else {
        parent->provider_failed(this, LCB_ERROR);
    }
}

lcb_STATUS FileProvider::refresh()
{
    if (!timer.is_armed()) {
        timer.signal();
    }
    return LCB_SUCCESS;
}

FileProvider::~FileProvider()
{
    timer.release();
    if (config) {
        config->decref();
    }
}

void FileProvider::clconfig_lsn(EventType event, ConfigInfo *info)
{
    if (event != CLCONFIG_EVENT_GOT_NEW_CONFIG) {
        return;
    }
    if (!enabled) {
        return;
    }

    if (info->get_origin() == CLCONFIG_PHONY || info->get_origin() == CLCONFIG_FILE) {
        lcb_log(LOGARGS(this, TRACE), "Not writing configuration originating from PHONY or FILE to cache");
        return;
    }

    write_cache(info->vbc);
}

void FileProvider::dump(FILE *fp) const
{
    fprintf(fp, "## BEGIN FILE PROVIEDER DUMP ##\n");
    if (!filename.empty()) {
        fprintf(fp, "FILENAME: %s\n", filename.c_str());
    }
    fprintf(fp, "LAST SYSTEM ERRNO: %d\n", last_errno);
    fprintf(fp, "LAST MTIME: %lu\n", (unsigned long)last_mtime);
    fprintf(fp, "## END FILE PROVIDER DUMP ##\n");
}

FileProvider::FileProvider(Confmon *parent_)
    : Provider(parent_, CLCONFIG_FILE), config(NULL), last_mtime(0), last_errno(0), is_readonly(false),
      timer(parent_->iot, this)
{
    parent->add_listener(this);
}

static std::string mkcachefile(const char *name, const char *bucket)
{
    std::string buffer;
    bool is_dir = false;
    if (name != NULL) {
        buffer = std::string(name);
        if (buffer.size() > 0 && buffer[buffer.size() - 1] == '/') {
            is_dir = true;
        }
    } else {
        buffer = lcb_get_tmpdir();
        if (buffer.empty()) {
            buffer += ".";
        }
        buffer += "/";
        is_dir = true;
    }
    if (is_dir) {
        // append bucket name only if we know that
        // cachefile is directory
        buffer += bucket;
    }

    return buffer;
}

bool lcb::clconfig::file_set_filename(Provider *p, const char *f, bool ro)
{
    FileProvider *provider = static_cast< FileProvider * >(p);
    provider->enabled = 1;
    provider->filename = mkcachefile(f, p->parent->settings->bucket);
    provider->is_readonly = bool(ro);

    if (ro) {
        FILE *fp_tmp = fopen(provider->filename.c_str(), "r");
        if (!fp_tmp) {
            lcb_log(LOGARGS(provider, ERROR), LOGFMT "Couldn't open for reading: %s", LOGID(provider), strerror(errno));
            return false;
        } else {
            fclose(fp_tmp);
        }
    }
    return true;
}

const char *lcb::clconfig::file_get_filename(Provider *p)
{
    FileProvider *fp = static_cast< FileProvider * >(p);
    if (fp->filename.empty()) {
        return NULL;
    } else {
        return fp->filename.c_str();
    }
}

void lcb::clconfig::file_set_readonly(Provider *p, bool val)
{
    static_cast< FileProvider * >(p)->is_readonly = val;
}

Provider *lcb::clconfig::new_file_provider(Confmon *mon)
{
    return new FileProvider(mon);
}
<|endoftext|>


<commit_before>#pragma once

#include "Math.hpp"

namespace atlas::math
{
    Point cartesianToSpherical(Point const& p)
    {
        float r     = glm::length(p);
        float theta = glm::atan(p.y / p.x);
        float phi   = glm::acos(p.z / r);
        return {r, theta, phi};
    }

    Point sphericalToCartesian(Point const& p)
    {
        float x = p.r * glm::cos(p.y) * glm::sin(p.z);
        float y = p.r * glm::sin(p.y) * glm::sin(p.z);
        float z = p.r * glm::cos(p.z);
        return {x, y, z};
    }

    Point cartesianToCylindrical(Point const& p)
    {
        float r     = glm::length(Point2{p});
        float theta = glm::atan(p.y / p.x);
        return {r, theta, p.z};
    }

    Point cylindricalToCartesian(Point const& p)
    {
        float x = p.x * glm::cos(p.y);
        float y = p.x * glm::sin(p.y);
        return {x, y, p.z};
    }

    Point2 cartesianToPolar(Point2 const& p)
    {
        float r     = glm::length(p);
        float theta = glm::atan(p.y / p.x);
        return {r, theta};
    }

    Point2 polarToCartesian(Point2 const& p)
    {
        float x = p.r * glm::cos(p.y);
        float y = p.r * glm::sin(p.y);
        return {x, y};
    }
} // namespace atlas::math<commit_msg>[brief] Updates coding style for Coordinates.<commit_after>#pragma once

#include "Math.hpp"

namespace atlas::math
{
    Point cartesian_to_spherical(Point const& p)
    {
        float r     = glm::length(p);
        float theta = glm::atan(p.y / p.x);
        float phi   = glm::acos(p.z / r);
        return {r, theta, phi};
    }

    Point spherical_to_cartesian(Point const& p)
    {
        float x = p.r * glm::cos(p.y) * glm::sin(p.z);
        float y = p.r * glm::sin(p.y) * glm::sin(p.z);
        float z = p.r * glm::cos(p.z);
        return {x, y, z};
    }

    Point cartesian_to_cylindrical(Point const& p)
    {
        float r     = glm::length(Point2{p});
        float theta = glm::atan(p.y / p.x);
        return {r, theta, p.z};
    }

    Point cylindrical_to_cartesian(Point const& p)
    {
        float x = p.x * glm::cos(p.y);
        float y = p.x * glm::sin(p.y);
        return {x, y, p.z};
    }

    Point2 cartesian_to_polar(Point2 const& p)
    {
        float r     = glm::length(p);
        float theta = glm::atan(p.y / p.x);
        return {r, theta};
    }

    Point2 polar_to_cartesian(Point2 const& p)
    {
        float x = p.r * glm::cos(p.y);
        float y = p.r * glm::sin(p.y);
        return {x, y};
    }
} // namespace atlas::math
<|endoftext|>


<commit_before>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_PLAYGROUND_PRODUCTS_BASE_HH
#define DUNE_GDT_PLAYGROUND_PRODUCTS_BASE_HH

#include <type_traits>

#include <dune/grid/common/gridview.hh>

#include <dune/stuff/common/memory.hh>
#include <dune/stuff/common/tmp-storage.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/walker.hh>
#include <dune/stuff/la/container/pattern.hh>

#include <dune/gdt/assembler/system.hh>
#include <dune/gdt/localoperator/codim1.hh>
#include <dune/gdt/playground/localevaluation/swipdg.hh>
#include <dune/gdt/products/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {
namespace Products {

// forward, needed for the traits
template <class GridViewImp, class DiffusionFactorImp, class RangeImp, class SourceImp, class FieldImp,
          class DiffusionTensorImp>
class EllipticSWIPDGPenaltyLocalizable;

namespace internal {

template <class GridViewImp, class DiffusionFactorImp, class RangeImp, class SourceImp, class FieldImp,
          class DiffusionTensorImp>
class EllipticSWIPDGPenaltyLocalizableTraits
{
public:
  typedef EllipticSWIPDGPenaltyLocalizable<GridViewImp, DiffusionFactorImp, RangeImp, SourceImp, FieldImp,
                                           DiffusionTensorImp> derived_type;
  typedef GridViewImp GridViewType;
  typedef RangeImp RangeType;
  typedef SourceImp SourceType;
  typedef FieldImp FieldType;
}; // class EllipticSWIPDGPenaltyLocalizableTraits

} // namespace internal

template <class GridViewImp, class DiffusionFactorImp, class RangeImp, class SourceImp = RangeImp,
          class FieldImp = double, class DiffusionTensorImp = void>
class EllipticSWIPDGPenaltyLocalizable
    : public LocalizableProductInterface<internal::EllipticSWIPDGPenaltyLocalizableTraits<GridViewImp,
                                                                                DiffusionFactorImp, RangeImp,
                                                                                SourceImp, FieldImp,
                                                                                DiffusionTensorImp>>,
      public Stuff::Grid::Functor::Codim1<GridViewImp>
{
  typedef LocalizableProductInterface<internal::EllipticSWIPDGPenaltyLocalizableTraits<GridViewImp, DiffusionFactorImp,
                                                                                RangeImp, SourceImp, FieldImp,
                                                                                DiffusionTensorImp>>
      ProductBaseType;
  typedef Stuff::Grid::Functor::Codim1<GridViewImp> FunctorBaseType;

public:
  typedef internal::EllipticSWIPDGPenaltyLocalizableTraits<GridViewImp, DiffusionFactorImp, RangeImp, SourceImp,
                                                           FieldImp, DiffusionTensorImp> Traits;

  typedef typename FunctorBaseType::GridViewType GridViewType;
  typedef typename ProductBaseType::RangeType RangeType;
  typedef typename ProductBaseType::SourceType SourceType;
  typedef typename ProductBaseType::FieldType FieldType;
  typedef typename FunctorBaseType::EntityType EntityType;
  typedef typename FunctorBaseType::IntersectionType IntersectionType;
  typedef DiffusionFactorImp DiffusionFactorType;
  typedef DiffusionTensorImp DiffusionTensorType;

  typedef LocalOperator::Codim1CouplingIntegral<LocalEvaluation::SWIPDG::InnerPenalty<DiffusionFactorType,
                                                                                DiffusionTensorType>>
      CouplingOperatorType;
  typedef LocalOperator::Codim1BoundaryIntegral<LocalEvaluation::SWIPDG::BoundaryLHSPenalty<DiffusionFactorType,
                                                                                DiffusionTensorType>>
      BoundaryOperatorType;

private:
  typedef DSC::TmpMatricesStorage<FieldType> TmpMatricesProviderType;

public:
  EllipticSWIPDGPenaltyLocalizable(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src,
                                   const DiffusionFactorType& diffusion_factor,
                                   const DiffusionTensorType& diffusion_tensor, const size_t over_integrate = 0)
    : grid_view_(grd_vw)
    , range_(rng)
    , source_(src)
    , diffusion_factor_(diffusion_factor)
    , diffusion_tensor_(diffusion_tensor)
    , coupling_operator_(over_integrate, diffusion_factor_, diffusion_tensor_)
    , boundary_operator_(over_integrate, diffusion_factor_, diffusion_tensor_)
    , inner_intersections_()
    , boundary_intersections_()
    , tmp_storage_(nullptr)
    , prepared_(false)
    , finalized_(false)
    , result_(0)
    , finalized_result_(0)
  {
  }

  virtual ~EllipticSWIPDGPenaltyLocalizable()
  {
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  const RangeType& range() const
  {
    return range_;
  }

  const SourceType& source() const
  {
    return source_;
  }

  virtual void prepare() DS_OVERRIDE
  {
    if (!prepared_) {
      tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(new TmpMatricesProviderType(
          {4, std::max(coupling_operator_.numTmpObjectsRequired(), boundary_operator_.numTmpObjectsRequired())}, 1, 1));
      result_   = FieldType(0.0);
      prepared_ = true;
    }
  } // ... prepare()

  FieldType compute_locally(const IntersectionType& intersection, const EntityType& inside_entity,
                            const EntityType& outside_entity) const
  {
    assert(prepared_);
    assert(tmp_storage_);
    auto& tmp_storage = tmp_storage_->matrices();
    assert(tmp_storage.size() >= 2);
    assert(tmp_storage[0].size() >= 4);
    auto& local_operator_result_en_en = tmp_storage[0][0];
    auto& local_operator_result_ne_ne = tmp_storage[0][1];
    auto& local_operator_result_en_ne = tmp_storage[0][2];
    auto& local_operator_result_ne_en = tmp_storage[0][3];
    auto& tmp_matrices                = tmp_storage[1];
    // get the local functions
    const auto local_source_ptr_en = this->source().local_function(inside_entity);
    const auto local_source_ptr_ne = this->source().local_function(outside_entity);
    const auto local_range_ptr_en  = this->range().local_function(inside_entity);
    const auto local_range_ptr_ne  = this->range().local_function(outside_entity);
    // apply local operator
    FieldType ret = 0;
    if (inner_intersections_.apply_on(grid_view_, intersection)) {
      coupling_operator_.apply(*local_range_ptr_en,
                               *local_source_ptr_en,
                               *local_source_ptr_ne,
                               *local_range_ptr_ne,
                               intersection,
                               local_operator_result_en_en,
                               local_operator_result_ne_ne,
                               local_operator_result_en_ne,
                               local_operator_result_ne_en,
                               tmp_matrices);
      assert(local_operator_result_en_en.rows() == 1);
      assert(local_operator_result_en_en.cols() == 1);
      assert(local_operator_result_ne_ne.rows() == 1);
      assert(local_operator_result_ne_ne.cols() == 1);
      assert(local_operator_result_en_ne.rows() == 1);
      assert(local_operator_result_en_ne.cols() == 1);
      assert(local_operator_result_ne_en.rows() == 1);
      assert(local_operator_result_ne_en.cols() == 1);
      ret += local_operator_result_en_en[0][0] + local_operator_result_ne_ne[0][0] + local_operator_result_en_ne[0][0]
             + local_operator_result_ne_en[0][0];
    }
    if (boundary_intersections_.apply_on(grid_view_, intersection)) {
      boundary_operator_.apply(
          *local_range_ptr_en, *local_source_ptr_en, intersection, local_operator_result_en_en, tmp_matrices);
      assert(local_operator_result_en_en.rows() == 1);
      assert(local_operator_result_en_en.cols() == 1);
      ret += local_operator_result_en_en[0][0];
    }
    return ret;
  } // ... compute_locally(...)

  virtual void apply_local(const IntersectionType& intersection, const EntityType& inside_entity,
                           const EntityType& outside_entity) DS_OVERRIDE
  {
    *result_ += compute_locally(intersection, inside_entity, outside_entity);
  }

  virtual void finalize() DS_OVERRIDE
  {
    if (!finalized_) {
      finalized_result_ = result_.sum();
      finalized_result_ = grid_view_.comm().sum(finalized_result_);
      finalized_        = true;
    }
  } // ... finalize(...)

  FieldType apply2()
  {
    if (!finalized_) {
      Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_);
      grid_walker.add(*this);
      grid_walker.walk();
    }
    return finalized_result_;
  } // ... apply2(...)

private:
  const GridViewType& grid_view_;
  const RangeType& range_;
  const SourceType& source_;
  const DiffusionFactorType& diffusion_factor_;
  const DiffusionTensorType& diffusion_tensor_;
  const CouplingOperatorType coupling_operator_;
  const BoundaryOperatorType boundary_operator_;
  const DSG::ApplyOn::InnerIntersectionsPrimally<GridViewType> inner_intersections_;
  const DSG::ApplyOn::BoundaryIntersections<GridViewType> boundary_intersections_;
  std::unique_ptr<TmpMatricesProviderType> tmp_storage_;
  bool prepared_;
  bool finalized_;
  DS::PerThreadValue<FieldType> result_;
  FieldType finalized_result_;
}; // class EllipticSWIPDGPenaltyLocalizable

} // namespace Products
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PLAYGROUND_PRODUCTS_BASE_HH
<commit_msg>[products.elliptic-swipdg] added first draft of assemblable product<commit_after>// This file is part of the dune-gdt project:
//   http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Schindler
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)

#ifndef DUNE_GDT_PLAYGROUND_PRODUCTS_BASE_HH
#define DUNE_GDT_PLAYGROUND_PRODUCTS_BASE_HH

#include <type_traits>

#include <dune/grid/common/gridview.hh>

#include <dune/stuff/common/memory.hh>
#include <dune/stuff/common/tmp-storage.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/stuff/grid/walker.hh>
#include <dune/stuff/la/container/pattern.hh>

#include <dune/gdt/assembler/system.hh>
#include <dune/gdt/assembler/local/codim1.hh>
#include <dune/gdt/localoperator/codim1.hh>
#include <dune/gdt/playground/localevaluation/swipdg.hh>
#include <dune/gdt/products/interfaces.hh>
#include <dune/gdt/spaces/interface.hh>

namespace Dune {
namespace GDT {
namespace Products {

// forward, needed for the traits
template <class GridViewImp, class DiffusionFactorImp, class RangeImp, class SourceImp, class FieldImp,
          class DiffusionTensorImp>
class EllipticSWIPDGPenaltyLocalizable;

template <class DiffusionFactorImp, class MatrixImp, class RangeSpaceImp, class GridViewImp, class SourceSpaceImp,
          class DiffusionTensorImp>
class EllipticSWIPDGPenaltyAssemblable;

namespace internal {

template <class GridViewImp, class DiffusionFactorImp, class RangeImp, class SourceImp, class FieldImp,
          class DiffusionTensorImp>
class EllipticSWIPDGPenaltyLocalizableTraits
{
public:
  typedef EllipticSWIPDGPenaltyLocalizable<GridViewImp, DiffusionFactorImp, RangeImp, SourceImp, FieldImp,
                                           DiffusionTensorImp> derived_type;
  typedef GridViewImp GridViewType;
  typedef RangeImp RangeType;
  typedef SourceImp SourceType;
  typedef FieldImp FieldType;
}; // class EllipticSWIPDGPenaltyLocalizableTraits

template <class DiffusionFactorImp, class MatrixImp, class RangeSpaceImp, class GridViewImp, class SourceSpaceImp,
          class DiffusionTensorImp>
class EllipticSWIPDGPenaltyAssemblableTraits
{
public:
  typedef EllipticSWIPDGPenaltyAssemblable<DiffusionFactorImp, MatrixImp, RangeSpaceImp, GridViewImp, SourceSpaceImp,
                                           DiffusionTensorImp> derived_type;
  typedef GridViewImp GridViewType;
  typedef RangeSpaceImp RangeSpaceType;
  typedef SourceSpaceImp SourceSpaceType;
  typedef MatrixImp MatrixType;
}; // class EllipticSWIPDGPenaltyAssemblableTraits

} // namespace internal

template <class GridViewImp, class DiffusionFactorImp, class RangeImp, class SourceImp = RangeImp,
          class FieldImp = double, class DiffusionTensorImp = void>
class EllipticSWIPDGPenaltyLocalizable
    : public LocalizableProductInterface<internal::EllipticSWIPDGPenaltyLocalizableTraits<GridViewImp,
                                                                                DiffusionFactorImp, RangeImp,
                                                                                SourceImp, FieldImp,
                                                                                DiffusionTensorImp>>,
      public Stuff::Grid::Functor::Codim1<GridViewImp>
{
  typedef LocalizableProductInterface<internal::EllipticSWIPDGPenaltyLocalizableTraits<GridViewImp, DiffusionFactorImp,
                                                                                RangeImp, SourceImp, FieldImp,
                                                                                DiffusionTensorImp>>
      ProductBaseType;
  typedef Stuff::Grid::Functor::Codim1<GridViewImp> FunctorBaseType;

public:
  typedef internal::EllipticSWIPDGPenaltyLocalizableTraits<GridViewImp, DiffusionFactorImp, RangeImp, SourceImp,
                                                           FieldImp, DiffusionTensorImp> Traits;

  typedef typename FunctorBaseType::GridViewType GridViewType;
  typedef typename ProductBaseType::RangeType RangeType;
  typedef typename ProductBaseType::SourceType SourceType;
  typedef typename ProductBaseType::FieldType FieldType;
  typedef typename FunctorBaseType::EntityType EntityType;
  typedef typename FunctorBaseType::IntersectionType IntersectionType;
  typedef DiffusionFactorImp DiffusionFactorType;
  typedef DiffusionTensorImp DiffusionTensorType;

  typedef LocalOperator::Codim1CouplingIntegral<LocalEvaluation::SWIPDG::InnerPenalty<DiffusionFactorType,
                                                                                DiffusionTensorType>>
      CouplingOperatorType;
  typedef LocalOperator::Codim1BoundaryIntegral<LocalEvaluation::SWIPDG::BoundaryLHSPenalty<DiffusionFactorType,
                                                                                DiffusionTensorType>>
      BoundaryOperatorType;

private:
  typedef DSC::TmpMatricesStorage<FieldType> TmpMatricesProviderType;

public:
  EllipticSWIPDGPenaltyLocalizable(const GridViewType& grd_vw, const RangeType& rng, const SourceType& src,
                                   const DiffusionFactorType& diffusion_factor,
                                   const DiffusionTensorType& diffusion_tensor, const size_t over_integrate = 0)
    : grid_view_(grd_vw)
    , range_(rng)
    , source_(src)
    , diffusion_factor_(diffusion_factor)
    , diffusion_tensor_(diffusion_tensor)
    , coupling_operator_(over_integrate, diffusion_factor_, diffusion_tensor_)
    , boundary_operator_(over_integrate, diffusion_factor_, diffusion_tensor_)
    , inner_intersections_()
    , boundary_intersections_()
    , tmp_storage_(nullptr)
    , prepared_(false)
    , finalized_(false)
    , result_(0)
    , finalized_result_(0)
  {
  }

  virtual ~EllipticSWIPDGPenaltyLocalizable()
  {
  }

  const GridViewType& grid_view() const
  {
    return grid_view_;
  }

  const RangeType& range() const
  {
    return range_;
  }

  const SourceType& source() const
  {
    return source_;
  }

  virtual void prepare() DS_OVERRIDE
  {
    if (!prepared_) {
      tmp_storage_ = std::unique_ptr<TmpMatricesProviderType>(new TmpMatricesProviderType(
          {4, std::max(coupling_operator_.numTmpObjectsRequired(), boundary_operator_.numTmpObjectsRequired())}, 1, 1));
      result_   = FieldType(0.0);
      prepared_ = true;
    }
  } // ... prepare()

  FieldType compute_locally(const IntersectionType& intersection, const EntityType& inside_entity,
                            const EntityType& outside_entity) const
  {
    assert(prepared_);
    assert(tmp_storage_);
    auto& tmp_storage = tmp_storage_->matrices();
    assert(tmp_storage.size() >= 2);
    assert(tmp_storage[0].size() >= 4);
    auto& local_operator_result_en_en = tmp_storage[0][0];
    auto& local_operator_result_ne_ne = tmp_storage[0][1];
    auto& local_operator_result_en_ne = tmp_storage[0][2];
    auto& local_operator_result_ne_en = tmp_storage[0][3];
    auto& tmp_matrices                = tmp_storage[1];
    // get the local functions
    const auto local_source_ptr_en = this->source().local_function(inside_entity);
    const auto local_source_ptr_ne = this->source().local_function(outside_entity);
    const auto local_range_ptr_en  = this->range().local_function(inside_entity);
    const auto local_range_ptr_ne  = this->range().local_function(outside_entity);
    // apply local operator
    FieldType ret = 0;
    if (inner_intersections_.apply_on(grid_view_, intersection)) {
      coupling_operator_.apply(*local_range_ptr_en,
                               *local_source_ptr_en,
                               *local_source_ptr_ne,
                               *local_range_ptr_ne,
                               intersection,
                               local_operator_result_en_en,
                               local_operator_result_ne_ne,
                               local_operator_result_en_ne,
                               local_operator_result_ne_en,
                               tmp_matrices);
      assert(local_operator_result_en_en.rows() == 1);
      assert(local_operator_result_en_en.cols() == 1);
      assert(local_operator_result_ne_ne.rows() == 1);
      assert(local_operator_result_ne_ne.cols() == 1);
      assert(local_operator_result_en_ne.rows() == 1);
      assert(local_operator_result_en_ne.cols() == 1);
      assert(local_operator_result_ne_en.rows() == 1);
      assert(local_operator_result_ne_en.cols() == 1);
      ret += local_operator_result_en_en[0][0] + local_operator_result_ne_ne[0][0] + local_operator_result_en_ne[0][0]
             + local_operator_result_ne_en[0][0];
    }
    if (boundary_intersections_.apply_on(grid_view_, intersection)) {
      boundary_operator_.apply(
          *local_range_ptr_en, *local_source_ptr_en, intersection, local_operator_result_en_en, tmp_matrices);
      assert(local_operator_result_en_en.rows() == 1);
      assert(local_operator_result_en_en.cols() == 1);
      ret += local_operator_result_en_en[0][0];
    }
    return ret;
  } // ... compute_locally(...)

  virtual void apply_local(const IntersectionType& intersection, const EntityType& inside_entity,
                           const EntityType& outside_entity) DS_OVERRIDE
  {
    *result_ += compute_locally(intersection, inside_entity, outside_entity);
  }

  virtual void finalize() DS_OVERRIDE
  {
    if (!finalized_) {
      finalized_result_ = result_.sum();
      finalized_result_ = grid_view_.comm().sum(finalized_result_);
      finalized_        = true;
    }
  } // ... finalize(...)

  FieldType apply2()
  {
    if (!finalized_) {
      Stuff::Grid::Walker<GridViewType> grid_walker(grid_view_);
      grid_walker.add(*this);
      grid_walker.walk();
    }
    return finalized_result_;
  } // ... apply2(...)

private:
  const GridViewType& grid_view_;
  const RangeType& range_;
  const SourceType& source_;
  const DiffusionFactorType& diffusion_factor_;
  const DiffusionTensorType& diffusion_tensor_;
  const CouplingOperatorType coupling_operator_;
  const BoundaryOperatorType boundary_operator_;
  const DSG::ApplyOn::InnerIntersectionsPrimally<GridViewType> inner_intersections_;
  const DSG::ApplyOn::BoundaryIntersections<GridViewType> boundary_intersections_;
  std::unique_ptr<TmpMatricesProviderType> tmp_storage_;
  bool prepared_;
  bool finalized_;
  DS::PerThreadValue<FieldType> result_;
  FieldType finalized_result_;
}; // class EllipticSWIPDGPenaltyLocalizable

template <class DiffusionFactorImp, class MatrixImp, class RangeSpaceImp,
          class GridViewImp = typename RangeSpaceImp::GridViewType, class SourceSpaceImp = RangeSpaceImp,
          class DiffusionTensorImp = void>
class EllipticSWIPDGPenaltyAssemblable
    : DSC::StorageProvider<MatrixImp>,
      public AssemblableProductInterface<internal::EllipticSWIPDGPenaltyAssemblableTraits<DiffusionFactorImp, MatrixImp,
                                                                                RangeSpaceImp, GridViewImp,
                                                                                SourceSpaceImp,
                                                                                DiffusionTensorImp>>,
      public SystemAssembler<RangeSpaceImp, GridViewImp, SourceSpaceImp>
{
  typedef DSC::StorageProvider<MatrixImp> StorageBaseType;
  typedef AssemblableProductInterface<internal::EllipticSWIPDGPenaltyAssemblableTraits<DiffusionFactorImp, MatrixImp,
                                                                                RangeSpaceImp, GridViewImp,
                                                                                SourceSpaceImp,
                                                                                DiffusionTensorImp>>
      ProductBaseType;
  typedef SystemAssembler<RangeSpaceImp, GridViewImp, SourceSpaceImp> AssemblerBaseType;

public:
  typedef internal::EllipticSWIPDGPenaltyAssemblableTraits<DiffusionFactorImp, MatrixImp, RangeSpaceImp, GridViewImp,
                                                           SourceSpaceImp, DiffusionTensorImp> Traits;
  typedef typename AssemblerBaseType::GridViewType GridViewType;
  typedef typename ProductBaseType::RangeSpaceType RangeSpaceType;
  typedef typename ProductBaseType::SourceSpaceType SourceSpaceType;
  typedef typename ProductBaseType::FieldType FieldType;
  typedef typename ProductBaseType::MatrixType MatrixType;
  typedef typename AssemblerBaseType::EntityType EntityType;
  typedef typename AssemblerBaseType::IntersectionType IntersectionType;
  typedef DiffusionFactorImp DiffusionFactorType;
  typedef DiffusionTensorImp DiffusionTensorType;

  typedef LocalOperator::Codim1CouplingIntegral<LocalEvaluation::SWIPDG::InnerPenalty<DiffusionFactorType,
                                                                                DiffusionTensorType>>
      CouplingOperatorType;
  typedef LocalOperator::Codim1BoundaryIntegral<LocalEvaluation::SWIPDG::BoundaryLHSPenalty<DiffusionFactorType,
                                                                                DiffusionTensorType>>
      BoundaryOperatorType;
  typedef LocalAssembler::Codim1CouplingMatrix<CouplingOperatorType> CouplingAssemblerType;
  typedef LocalAssembler::Codim1BoundaryMatrix<BoundaryOperatorType> BoundaryAssemblerType;

  using ProductBaseType::pattern;

  static Stuff::LA::SparsityPatternDefault pattern(const RangeSpaceType& range_space,
                                                   const SourceSpaceType& source_space, const GridViewType& grid_view)
  {
    return range_space.compute_face_and_volume_pattern(grid_view, source_space);
  }

  EllipticSWIPDGPenaltyAssemblable(const RangeSpaceType& rng_spc, const GridViewType& grd_vw,
                                   const SourceSpaceType& src_spc, const DiffusionFactorImp& diffusion_factor,
                                   const DiffusionTensorImp& diffusion_tensor, const size_t over_integrate = 0)
    : StorageBaseType(
          new MatrixType(rng_spc.mapper().size(), src_spc.mapper().size(), pattern(rng_spc, src_spc, grd_vw)))
    , AssemblerBaseType(rng_spc, src_spc, grd_vw)
    , diffusion_factor_(diffusion_factor)
    , diffusion_tensor_(diffusion_tensor)
    , coupling_operator_(over_integrate, diffusion_factor_, diffusion_tensor_)
    , boundary_operator_(over_integrate, diffusion_factor_, diffusion_tensor_)
    , coupling_assembler_(coupling_operator_)
    , boundary_assembler_(boundary_operator_)
    , assembled_(false)
  {
    setup();
  }

  const GridViewType& grid_view() const
  {
    return AssemblerBaseType::grid_view();
  }

  const RangeSpaceType& range_space() const
  {
    return AssemblerBaseType::test_space();
  }

  const SourceSpaceType& source_space() const
  {
    return AssemblerBaseType::ansatz_space();
  }

  MatrixType& matrix()
  {
    return StorageBaseType::storage_access();
  }

  const MatrixType& matrix() const
  {
    return StorageBaseType::storage_access();
  }

  void assemble()
  {
    if (!assembled_) {
      AssemblerBaseType::assemble();
      assembled_ = true;
    }
  } // ... assemble()

private:
  void setup()
  {
    this->add(coupling_assembler_, matrix(), new DSG::ApplyOn::InnerIntersectionsPrimally<GridViewType>());
    this->add(boundary_assembler_, matrix(), new DSG::ApplyOn::BoundaryIntersections<GridViewType>());
  }

  const DiffusionFactorType& diffusion_factor_;
  const DiffusionTensorType& diffusion_tensor_;
  const CouplingOperatorType coupling_operator_;
  const BoundaryOperatorType boundary_operator_;
  const CouplingAssemblerType coupling_assembler_;
  const BoundaryAssemblerType boundary_assembler_;
  bool assembled_;
}; // class EllipticSWIPDGPenaltyAssemblable

} // namespace Products
} // namespace GDT
} // namespace Dune

#endif // DUNE_GDT_PLAYGROUND_PRODUCTS_BASE_HH
<|endoftext|>


<commit_before>//..............................................................................
//
//  This file is part of the AXL library.
//
//  AXL is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/axl/license.txt
//
//..............................................................................

#include "pch.h"
#include "axl_dox_Module.h"
#include "axl_dox_Host.h"

namespace axl {
namespace dox {

//..............................................................................

void
Module::clear()
{
	m_blockList.clear();
	m_groupList.clear();
	m_footnoteList.clear();
	m_refIdMap.clear();
	m_groupMap.clear();
	m_targetList.clear();
}

Group*
Module::getGroup(const sl::StringRef& name)
{
	sl::StringHashTableIterator<Group*> it = m_groupMap.visit(name);
	if (it->m_value)
		return it->m_value;

	sl::String refId;
	refId.format("group_%s", name.sz());
	refId.replace('-', '_');

	Group* group = AXL_MEM_NEW_ARGS(Group, (m_host));
	group->m_name = name;
	group->m_refId = adjustRefId(refId);

	m_groupList.insertTail(group);
	it->m_value = group;
	return  group;
}

Block*
Module::createBlock(handle_t item)
{
	Block* block = AXL_MEM_NEW_ARGS(Block, (m_host));
	block->m_item = item;
	m_blockList.insertTail(block);
	return  block;
}

Footnote*
Module::createFootnote()
{
	Footnote* footnote = AXL_MEM_NEW_ARGS(Footnote, (m_host));
	m_blockList.insertTail(footnote);
	return footnote;
}

sl::String
Module::adjustRefId(const sl::StringRef& refId)
{
	sl::StringHashTableIterator<size_t> it = m_refIdMap.visit(refId);
	if (!it->m_value) // no collisions
	{
		it->m_value = 2; // start with index 2
		return refId;
	}

	sl::String adjustedRefId;
	adjustedRefId.format("%s_%d", refId.sz(), it->m_value);

	it->m_value++;
	return adjustedRefId;
}

void
Module::setBlockTarget(
	Block* block,
	int tokenKind,
	const sl::StringRef& itemName,
	size_t overloadIdx
	)
{
	Target* target = AXL_MEM_NEW(Target);
	target->m_block = block;
	target->m_tokenKind = tokenKind;
	target->m_itemName = itemName;
	target->m_overloadIdx = overloadIdx;
	m_targetList.insertTail(target);
}

bool
Module::resolveBlockTargets()
{
	bool result = true;

	sl::Iterator<Target> it = m_targetList.getHead();
	for (; it; it++)
	{
		Target* target = *it;

		handle_t item = m_host->findItem(target->m_itemName, target->m_overloadIdx);
		if (!item)
		{
			result = false;
			continue;
		}

		// keep the group of the original item (usually, we use @{ ... @} for grouping)

		Block* block = m_host->findItemBlock(item);
		if (block && block->m_group && !target->m_block->m_group)
			target->m_block->m_group = block->m_group;

		m_host->setItemBlock(item, target->m_block);
	}

	if (!result)
		err::setError("documentation target(s) not found");

	return result;
}

void
Module::deleteEmptyGroups()
{
	bool isGroupDeleted;

	do
	{
		isGroupDeleted = false;

		sl::Iterator<Group> groupIt = m_groupList.getHead();
		while (groupIt)
		{
			sl::Iterator<Group> nextIt = groupIt.getNext();

			if (groupIt->isEmpty())
			{
				if (groupIt->m_group)
					groupIt->m_group->m_groupList.remove(groupIt->m_parentGroupListIt);

				m_groupMap.eraseKey(groupIt->m_name);
				m_groupList.erase(groupIt);
				isGroupDeleted = true;
			}

			groupIt = nextIt;
		}
	} while (isGroupDeleted);
}

bool
Module::generateDocumentation(
	const sl::StringRef& outputDir,
	const sl::StringRef& indexFileName,
	const sl::StringRef& globalNamespaceFileName
	)
{
	static char indexFileHdr[] =
		"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
		"<doxygenindex>\n";

	static char indexFileTerm[] = "</doxygenindex>\n";

	static char compoundFileHdr[] =
		"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
		"<doxygen>\n";

	static char compoundFileTerm[] = "</doxygen>\n";

	bool result;

	result = io::ensureDirExists(outputDir);
	if (!result)
		return false;

	result = resolveBlockTargets();
	if (!result)
	{
		// generate a warning about orphan doxy blocks?
	}

	sl::String nspaceXml;
	sl::String indexXml;

	result = m_host->generateGlobalNamespaceDocumentation(outputDir, &nspaceXml, &indexXml);
	if (!result)
		return false;

	if (nspaceXml.isEmpty())
	{
		err::setError("module does not contain any documentable items");
		return false;
	}

	deleteEmptyGroups();

	result = generateGroupDocumentation(outputDir, &indexXml);
	if (!result)
		return false;

	sl::String nspaceFilePath = io::concatFilePath(outputDir, globalNamespaceFileName);
	sl::String indexFilePath = io::concatFilePath(outputDir, indexFileName);

	io::File file;
	return
		file.open(nspaceFilePath, io::FileFlag_Clear) &&
		file.write(compoundFileHdr, lengthof(compoundFileHdr)) != -1 &&
		file.write(nspaceXml, nspaceXml.getLength()) != -1 &&
		file.write(compoundFileTerm, lengthof(compoundFileTerm)) != -1 &&

		file.open(indexFilePath, io::FileFlag_Clear) &&
		file.write(indexFileHdr, lengthof(indexFileHdr)) != -1 &&
		file.write(indexXml, indexXml.getLength()) != -1 &&
		file.write(indexFileTerm, lengthof(indexFileTerm)) != -1;
}

bool
Module::generateGroupDocumentation(
	const sl::StringRef& outputDir,
	sl::String* indexXml
	)
{
	bool result;

	static char compoundFileHdr[] =
		"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
		"<doxygen>\n";

	static char compoundFileTerm[] = "</doxygen>\n";

	sl::String itemXml;

	sl::Iterator<Group> groupIt = m_groupList.getHead();
	for (; groupIt; groupIt++)
	{
		result = groupIt->generateDocumentation(outputDir, &itemXml, indexXml);
		if (!result)
			return false;

		sl::String refId = groupIt->getRefId();
		sl::String fileName = sl::String(outputDir) + "/" + refId + ".xml";

		io::File compoundFile;
		result =
			compoundFile.open(fileName, io::FileFlag_Clear) &&
			compoundFile.write(compoundFileHdr, lengthof(compoundFileHdr)) != -1 &&
			compoundFile.write(itemXml, itemXml.getLength()) != -1 &&
			compoundFile.write(compoundFileTerm, lengthof(compoundFileTerm)) != -1;

		if (!result)
			return false;
	}

	return true;
}

//..............................................................................

} // namespace dox
} // namespace axl
<commit_msg>[axl_dox] don't delete empty groups (we now use an empty group to specify title/description for the global page)<commit_after>//..............................................................................
//
//  This file is part of the AXL library.
//
//  AXL is distributed under the MIT license.
//  For details see accompanying license.txt file,
//  the public copy of which is also available at:
//  http://tibbo.com/downloads/archive/axl/license.txt
//
//..............................................................................

#include "pch.h"
#include "axl_dox_Module.h"
#include "axl_dox_Host.h"

namespace axl {
namespace dox {

//..............................................................................

void
Module::clear()
{
	m_blockList.clear();
	m_groupList.clear();
	m_footnoteList.clear();
	m_refIdMap.clear();
	m_groupMap.clear();
	m_targetList.clear();
}

Group*
Module::getGroup(const sl::StringRef& name)
{
	sl::StringHashTableIterator<Group*> it = m_groupMap.visit(name);
	if (it->m_value)
		return it->m_value;

	sl::String refId;
	refId.format("group_%s", name.sz());
	refId.replace('-', '_');

	Group* group = AXL_MEM_NEW_ARGS(Group, (m_host));
	group->m_name = name;
	group->m_refId = adjustRefId(refId);

	m_groupList.insertTail(group);
	it->m_value = group;
	return  group;
}

Block*
Module::createBlock(handle_t item)
{
	Block* block = AXL_MEM_NEW_ARGS(Block, (m_host));
	block->m_item = item;
	m_blockList.insertTail(block);
	return  block;
}

Footnote*
Module::createFootnote()
{
	Footnote* footnote = AXL_MEM_NEW_ARGS(Footnote, (m_host));
	m_blockList.insertTail(footnote);
	return footnote;
}

sl::String
Module::adjustRefId(const sl::StringRef& refId)
{
	sl::StringHashTableIterator<size_t> it = m_refIdMap.visit(refId);
	if (!it->m_value) // no collisions
	{
		it->m_value = 2; // start with index 2
		return refId;
	}

	sl::String adjustedRefId;
	adjustedRefId.format("%s_%d", refId.sz(), it->m_value);

	it->m_value++;
	return adjustedRefId;
}

void
Module::setBlockTarget(
	Block* block,
	int tokenKind,
	const sl::StringRef& itemName,
	size_t overloadIdx
	)
{
	Target* target = AXL_MEM_NEW(Target);
	target->m_block = block;
	target->m_tokenKind = tokenKind;
	target->m_itemName = itemName;
	target->m_overloadIdx = overloadIdx;
	m_targetList.insertTail(target);
}

bool
Module::resolveBlockTargets()
{
	bool result = true;

	sl::Iterator<Target> it = m_targetList.getHead();
	for (; it; it++)
	{
		Target* target = *it;

		handle_t item = m_host->findItem(target->m_itemName, target->m_overloadIdx);
		if (!item)
		{
			result = false;
			continue;
		}

		// keep the group of the original item (usually, we use @{ ... @} for grouping)

		Block* block = m_host->findItemBlock(item);
		if (block && block->m_group && !target->m_block->m_group)
			target->m_block->m_group = block->m_group;

		m_host->setItemBlock(item, target->m_block);
	}

	if (!result)
		err::setError("documentation target(s) not found");

	return result;
}

void
Module::deleteEmptyGroups()
{
	bool isGroupDeleted;

	do
	{
		isGroupDeleted = false;

		sl::Iterator<Group> groupIt = m_groupList.getHead();
		while (groupIt)
		{
			sl::Iterator<Group> nextIt = groupIt.getNext();

			if (groupIt->isEmpty())
			{
				if (groupIt->m_group)
					groupIt->m_group->m_groupList.remove(groupIt->m_parentGroupListIt);

				m_groupMap.eraseKey(groupIt->m_name);
				m_groupList.erase(groupIt);
				isGroupDeleted = true;
			}

			groupIt = nextIt;
		}
	} while (isGroupDeleted);
}

bool
Module::generateDocumentation(
	const sl::StringRef& outputDir,
	const sl::StringRef& indexFileName,
	const sl::StringRef& globalNamespaceFileName
	)
{
	static char indexFileHdr[] =
		"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
		"<doxygenindex>\n";

	static char indexFileTerm[] = "</doxygenindex>\n";

	static char compoundFileHdr[] =
		"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
		"<doxygen>\n";

	static char compoundFileTerm[] = "</doxygen>\n";

	bool result;

	result = io::ensureDirExists(outputDir);
	if (!result)
		return false;

	result = resolveBlockTargets();
	if (!result)
	{
		// generate a warning about orphan doxy blocks?
	}

	sl::String nspaceXml;
	sl::String indexXml;

	result = m_host->generateGlobalNamespaceDocumentation(outputDir, &nspaceXml, &indexXml);
	if (!result)
		return false;

	if (nspaceXml.isEmpty())
	{
		err::setError("module does not contain any documentable items");
		return false;
	}

	result = generateGroupDocumentation(outputDir, &indexXml);
	if (!result)
		return false;

	sl::String nspaceFilePath = io::concatFilePath(outputDir, globalNamespaceFileName);
	sl::String indexFilePath = io::concatFilePath(outputDir, indexFileName);

	io::File file;
	return
		file.open(nspaceFilePath, io::FileFlag_Clear) &&
		file.write(compoundFileHdr, lengthof(compoundFileHdr)) != -1 &&
		file.write(nspaceXml, nspaceXml.getLength()) != -1 &&
		file.write(compoundFileTerm, lengthof(compoundFileTerm)) != -1 &&

		file.open(indexFilePath, io::FileFlag_Clear) &&
		file.write(indexFileHdr, lengthof(indexFileHdr)) != -1 &&
		file.write(indexXml, indexXml.getLength()) != -1 &&
		file.write(indexFileTerm, lengthof(indexFileTerm)) != -1;
}

bool
Module::generateGroupDocumentation(
	const sl::StringRef& outputDir,
	sl::String* indexXml
	)
{
	bool result;

	static char compoundFileHdr[] =
		"<?xml version='1.0' encoding='UTF-8' standalone='no'?>\n"
		"<doxygen>\n";

	static char compoundFileTerm[] = "</doxygen>\n";

	sl::String itemXml;

	sl::Iterator<Group> groupIt = m_groupList.getHead();
	for (; groupIt; groupIt++)
	{
		result = groupIt->generateDocumentation(outputDir, &itemXml, indexXml);
		if (!result)
			return false;

		sl::String refId = groupIt->getRefId();
		sl::String fileName = sl::String(outputDir) + "/" + refId + ".xml";

		io::File compoundFile;
		result =
			compoundFile.open(fileName, io::FileFlag_Clear) &&
			compoundFile.write(compoundFileHdr, lengthof(compoundFileHdr)) != -1 &&
			compoundFile.write(itemXml, itemXml.getLength()) != -1 &&
			compoundFile.write(compoundFileTerm, lengthof(compoundFileTerm)) != -1;

		if (!result)
			return false;
	}

	return true;
}

//..............................................................................

} // namespace dox
} // namespace axl
<|endoftext|>