<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "objmeshfilewriter.h"

// appleseed.foundation headers.
#include "foundation/core/exceptions/exceptionioerror.h"
#include "foundation/core/appleseed.h"
#include "foundation/math/vector.h"
#include "foundation/utility/otherwise.h"
#include "foundation/utility/string.h"

// Standard headers.
#include <cstddef>
#include <cstdio>

using namespace std;

namespace foundation
{

//
// OBJMeshFileWriter class implementation.
//

namespace
{
    //
    // IMeshWalker to IOBJMeshWalker adaptor.
    //

    class OBJMeshBuilderWalker
      : public IOBJMeshWalker
    {
      public:
        explicit OBJMeshBuilderWalker(const IMeshWalker& walker)
          : m_walker(walker)
        {
        }

        virtual string get_name() const
        {
            return m_walker.get_name();
        }

        virtual size_t get_vertex_count() const
        {
            return m_walker.get_vertex_count();
        }

        virtual Vector3d get_vertex(const size_t i) const
        {
            return m_walker.get_vertex(i);
        }

        virtual size_t get_vertex_normal_count() const
        {
            return m_walker.get_vertex_normal_count();
        }

        virtual Vector3d get_vertex_normal(const size_t i) const
        {
            return m_walker.get_vertex_normal(i);
        }

        virtual size_t get_tex_coords_count() const
        {
            return m_walker.get_tex_coords_count();
        }

        virtual Vector2d get_tex_coords(const size_t i) const
        {
            return m_walker.get_tex_coords(i);
        }

        virtual size_t get_face_count() const
        {
            return m_walker.get_face_count();
        }

        virtual Face get_face(const size_t i) const
        {
            return m_walker.get_face(i);
        }

      private:
        const IMeshWalker& m_walker;
    };

    // Floating-point formatting settings.
    #define VectorFormat "%.15f"

    void write_vector(FILE* file, const char* prefix, const Vector2d& v)
    {
        fprintf(
            file,
            "%s " VectorFormat " " VectorFormat "\n",
            prefix, v[0], v[1]);
    }

    void write_vector(FILE* file, const char* prefix, const Vector3d& v)
    {
        fprintf(
            file,
            "%s " VectorFormat " " VectorFormat " " VectorFormat "\n",
            prefix, v[0], v[1], v[2]);
    }

    void write_vertices(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t vertex_count = walker.get_vertex_count();

        fprintf(
            file,
            "# %s %s.\n",
            pretty_int(vertex_count).c_str(),
            plural(vertex_count, "vertex", "vertices").c_str());

        for (size_t i = 0; i < vertex_count; ++i)
        {
            const Vector3d v = walker.get_vertex(i);
            write_vector(file, "v", v);
        }
    }

    void write_vertex_normals(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t vertex_normal_count = walker.get_vertex_normal_count();

        if (vertex_normal_count == 0)
            return;

        fprintf(
            file,
            "# %s %s.\n",
            pretty_int(vertex_normal_count).c_str(),
            plural(vertex_normal_count, "vertex normal").c_str());

        for (size_t i = 0; i < vertex_normal_count; ++i)
        {
            const Vector3d vn = walker.get_vertex_normal(i);
            write_vector(file, "vn", vn);
        }
    }

    void write_texture_coordinates(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t tex_coords_count = walker.get_tex_coords_count();

        if (tex_coords_count == 0)
            return;

        fprintf(
            file,
            "# %s %s.\n",
            pretty_int(tex_coords_count).c_str(),
            plural(tex_coords_count, "texture coordinate").c_str());

        for (size_t i = 0; i < tex_coords_count; ++i)
        {
            const Vector2d vt = walker.get_tex_coords(i);
            write_vector(file, "vt", vt);
        }
    }

    void write_faces_no_vn_no_vt(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t face_count = walker.get_face_count();

        for (size_t i = 0; i < face_count; ++i)
        {
            const IOBJMeshWalker::Face face = walker.get_face(i);
            fprintf(
                file,
                "f " FMT_SIZE_T
                 " " FMT_SIZE_T
                 " " FMT_SIZE_T "\n",
                face.m_v0 + 1,
                face.m_v1 + 1,
                face.m_v2 + 1);
        }
    }

    void write_faces_vn_no_vt(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t face_count = walker.get_face_count();

        for (size_t i = 0; i < face_count; ++i)
        {
            const IOBJMeshWalker::Face face = walker.get_face(i);
            fprintf(
                file,
                "f " FMT_SIZE_T "//" FMT_SIZE_T
                 " " FMT_SIZE_T "//" FMT_SIZE_T
                 " " FMT_SIZE_T "//" FMT_SIZE_T "\n",
                face.m_v0 + 1, face.m_n0 + 1,
                face.m_v1 + 1, face.m_n1 + 1,
                face.m_v2 + 1, face.m_n2 + 1);
        }
    }

    void write_faces_no_vn_vt(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t face_count = walker.get_face_count();

        for (size_t i = 0; i < face_count; ++i)
        {
            const IOBJMeshWalker::Face face = walker.get_face(i);
            fprintf(
                file,
                "f " FMT_SIZE_T "/"
                 " " FMT_SIZE_T "/"
                 " " FMT_SIZE_T "/" "\n",
                face.m_v0 + 1, face.m_t0 + 1,
                face.m_v1 + 1, face.m_t1 + 1,
                face.m_v2 + 1, face.m_t2 + 1);
        }
    }

    void write_faces_vn_vt(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t face_count = walker.get_face_count();

        for (size_t i = 0; i < face_count; ++i)
        {
            const IOBJMeshWalker::Face face = walker.get_face(i);
            fprintf(
                file,
                "f " FMT_SIZE_T "/" FMT_SIZE_T "/" FMT_SIZE_T
                 " " FMT_SIZE_T "/" FMT_SIZE_T "/" FMT_SIZE_T
                 " " FMT_SIZE_T "/" FMT_SIZE_T "/" FMT_SIZE_T "\n",
                face.m_v0 + 1, face.m_t0 + 1, face.m_n0 + 1,
                face.m_v1 + 1, face.m_t1 + 1, face.m_n1 + 1,
                face.m_v2 + 1, face.m_t2 + 1, face.m_n2 + 1);
        }
    }

    void write_faces(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t face_count = walker.get_face_count();

        fprintf(
            file,
            "# %s %s.\n",
            pretty_int(face_count).c_str(),
            plural(face_count, "face").c_str());

        const size_t feature_mask =
            (walker.get_vertex_normal_count() > 0 ? 1 : 0) +
            (walker.get_tex_coords_count() > 0 ? 2 : 0);

        switch (feature_mask)
        {
          case 0: write_faces_no_vn_no_vt(file, walker); break;
          case 1: write_faces_vn_no_vt(file, walker); break;
          case 2: write_faces_no_vn_vt(file, walker); break;
          case 3: write_faces_vn_vt(file, walker); break;
          assert_otherwise;
        }
    }
}

void OBJMeshFileWriter::write(
    const string&           filename,
    const IMeshWalker&      walker)
{
    OBJMeshBuilderWalker adaptor(walker);
    write(filename, adaptor);
}

void OBJMeshFileWriter::write(
    const string&           filename,
    const IOBJMeshWalker&   walker)
{
    FILE* file = fopen(filename.c_str(), "wt");

    if (file == 0)
        throw ExceptionIOError();

    // Write the file header.
    fprintf(
        file,
        "# File generated by %s.\n",
        Appleseed::get_synthetic_version_string());

    // Write the mesh object name.
    fprintf(
        file,
        "o %s\n",
        walker.get_name().c_str());

    write_vertices(file, walker);
    write_vertex_normals(file, walker);
    write_texture_coordinates(file, walker);
    write_faces(file, walker);

    fclose(file);
}

}   // namespace foundation
<commit_msg>fixed writing of .obj files with texture coordinates but no vertex normals.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "objmeshfilewriter.h"

// appleseed.foundation headers.
#include "foundation/core/exceptions/exceptionioerror.h"
#include "foundation/core/appleseed.h"
#include "foundation/math/vector.h"
#include "foundation/utility/otherwise.h"
#include "foundation/utility/string.h"

// Standard headers.
#include <cstddef>
#include <cstdio>

using namespace std;

namespace foundation
{

//
// OBJMeshFileWriter class implementation.
//

namespace
{
    //
    // IMeshWalker to IOBJMeshWalker adaptor.
    //

    class OBJMeshBuilderWalker
      : public IOBJMeshWalker
    {
      public:
        explicit OBJMeshBuilderWalker(const IMeshWalker& walker)
          : m_walker(walker)
        {
        }

        virtual string get_name() const
        {
            return m_walker.get_name();
        }

        virtual size_t get_vertex_count() const
        {
            return m_walker.get_vertex_count();
        }

        virtual Vector3d get_vertex(const size_t i) const
        {
            return m_walker.get_vertex(i);
        }

        virtual size_t get_vertex_normal_count() const
        {
            return m_walker.get_vertex_normal_count();
        }

        virtual Vector3d get_vertex_normal(const size_t i) const
        {
            return m_walker.get_vertex_normal(i);
        }

        virtual size_t get_tex_coords_count() const
        {
            return m_walker.get_tex_coords_count();
        }

        virtual Vector2d get_tex_coords(const size_t i) const
        {
            return m_walker.get_tex_coords(i);
        }

        virtual size_t get_face_count() const
        {
            return m_walker.get_face_count();
        }

        virtual Face get_face(const size_t i) const
        {
            return m_walker.get_face(i);
        }

      private:
        const IMeshWalker& m_walker;
    };

    // Floating-point formatting settings.
    #define VectorFormat "%.15f"

    void write_vector(FILE* file, const char* prefix, const Vector2d& v)
    {
        fprintf(
            file,
            "%s " VectorFormat " " VectorFormat "\n",
            prefix, v[0], v[1]);
    }

    void write_vector(FILE* file, const char* prefix, const Vector3d& v)
    {
        fprintf(
            file,
            "%s " VectorFormat " " VectorFormat " " VectorFormat "\n",
            prefix, v[0], v[1], v[2]);
    }

    void write_vertices(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t vertex_count = walker.get_vertex_count();

        fprintf(
            file,
            "# %s %s.\n",
            pretty_int(vertex_count).c_str(),
            plural(vertex_count, "vertex", "vertices").c_str());

        for (size_t i = 0; i < vertex_count; ++i)
        {
            const Vector3d v = walker.get_vertex(i);
            write_vector(file, "v", v);
        }
    }

    void write_vertex_normals(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t vertex_normal_count = walker.get_vertex_normal_count();

        if (vertex_normal_count == 0)
            return;

        fprintf(
            file,
            "# %s %s.\n",
            pretty_int(vertex_normal_count).c_str(),
            plural(vertex_normal_count, "vertex normal").c_str());

        for (size_t i = 0; i < vertex_normal_count; ++i)
        {
            const Vector3d vn = walker.get_vertex_normal(i);
            write_vector(file, "vn", vn);
        }
    }

    void write_texture_coordinates(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t tex_coords_count = walker.get_tex_coords_count();

        if (tex_coords_count == 0)
            return;

        fprintf(
            file,
            "# %s %s.\n",
            pretty_int(tex_coords_count).c_str(),
            plural(tex_coords_count, "texture coordinate").c_str());

        for (size_t i = 0; i < tex_coords_count; ++i)
        {
            const Vector2d vt = walker.get_tex_coords(i);
            write_vector(file, "vt", vt);
        }
    }

    void write_faces_no_vn_no_vt(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t face_count = walker.get_face_count();

        for (size_t i = 0; i < face_count; ++i)
        {
            const IOBJMeshWalker::Face face = walker.get_face(i);
            fprintf(
                file,
                "f " FMT_SIZE_T
                 " " FMT_SIZE_T
                 " " FMT_SIZE_T "\n",
                face.m_v0 + 1,
                face.m_v1 + 1,
                face.m_v2 + 1);
        }
    }

    void write_faces_vn_no_vt(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t face_count = walker.get_face_count();

        for (size_t i = 0; i < face_count; ++i)
        {
            const IOBJMeshWalker::Face face = walker.get_face(i);
            fprintf(
                file,
                "f " FMT_SIZE_T "//" FMT_SIZE_T
                 " " FMT_SIZE_T "//" FMT_SIZE_T
                 " " FMT_SIZE_T "//" FMT_SIZE_T "\n",
                face.m_v0 + 1, face.m_n0 + 1,
                face.m_v1 + 1, face.m_n1 + 1,
                face.m_v2 + 1, face.m_n2 + 1);
        }
    }

    void write_faces_no_vn_vt(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t face_count = walker.get_face_count();

        for (size_t i = 0; i < face_count; ++i)
        {
            const IOBJMeshWalker::Face face = walker.get_face(i);
            fprintf(
                file,
                "f " FMT_SIZE_T "/" FMT_SIZE_T
                 " " FMT_SIZE_T "/" FMT_SIZE_T
                 " " FMT_SIZE_T "/" FMT_SIZE_T "\n",
                face.m_v0 + 1, face.m_t0 + 1,
                face.m_v1 + 1, face.m_t1 + 1,
                face.m_v2 + 1, face.m_t2 + 1);
        }
    }

    void write_faces_vn_vt(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t face_count = walker.get_face_count();

        for (size_t i = 0; i < face_count; ++i)
        {
            const IOBJMeshWalker::Face face = walker.get_face(i);
            fprintf(
                file,
                "f " FMT_SIZE_T "/" FMT_SIZE_T "/" FMT_SIZE_T
                 " " FMT_SIZE_T "/" FMT_SIZE_T "/" FMT_SIZE_T
                 " " FMT_SIZE_T "/" FMT_SIZE_T "/" FMT_SIZE_T "\n",
                face.m_v0 + 1, face.m_t0 + 1, face.m_n0 + 1,
                face.m_v1 + 1, face.m_t1 + 1, face.m_n1 + 1,
                face.m_v2 + 1, face.m_t2 + 1, face.m_n2 + 1);
        }
    }

    void write_faces(FILE* file, const IOBJMeshWalker& walker)
    {
        const size_t face_count = walker.get_face_count();

        fprintf(
            file,
            "# %s %s.\n",
            pretty_int(face_count).c_str(),
            plural(face_count, "face").c_str());

        const size_t feature_mask =
            (walker.get_vertex_normal_count() > 0 ? 1 : 0) +
            (walker.get_tex_coords_count() > 0 ? 2 : 0);

        switch (feature_mask)
        {
          case 0: write_faces_no_vn_no_vt(file, walker); break;
          case 1: write_faces_vn_no_vt(file, walker); break;
          case 2: write_faces_no_vn_vt(file, walker); break;
          case 3: write_faces_vn_vt(file, walker); break;
          assert_otherwise;
        }
    }
}

void OBJMeshFileWriter::write(
    const string&           filename,
    const IMeshWalker&      walker)
{
    OBJMeshBuilderWalker adaptor(walker);
    write(filename, adaptor);
}

void OBJMeshFileWriter::write(
    const string&           filename,
    const IOBJMeshWalker&   walker)
{
    FILE* file = fopen(filename.c_str(), "wt");

    if (file == 0)
        throw ExceptionIOError();

    // Write the file header.
    fprintf(
        file,
        "# File generated by %s.\n",
        Appleseed::get_synthetic_version_string());

    // Write the mesh object name.
    fprintf(
        file,
        "o %s\n",
        walker.get_name().c_str());

    write_vertices(file, walker);
    write_vertex_normals(file, walker);
    write_texture_coordinates(file, walker);
    write_faces(file, walker);

    fclose(file);
}

}   // namespace foundation
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "spotlight.h"

// appleseed.renderer headers.
#include "renderer/global/globaltypes.h"
#include "renderer/modeling/input/inputarray.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/input/source.h"
#include "renderer/utility/paramarray.h"

// appleseed.foundation headers.
#include "foundation/math/basis.h"
#include "foundation/math/matrix.h"
#include "foundation/math/sampling.h"
#include "foundation/math/scalar.h"
#include "foundation/math/transform.h"
#include "foundation/math/vector.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"

// Standard headers.
#include <cmath>

// Forward declarations.
namespace renderer  { class Assembly; }
namespace renderer  { class Project; }

using namespace foundation;
using namespace std;

namespace renderer
{

namespace
{
    //
    // Spot light.
    //

    const char* Model = "spot_light";

    class SpotLight
      : public Light
    {
      public:
        SpotLight(
            const char*         name,
            const ParamArray&   params)
          : Light(name, params)
        {
            m_inputs.declare("exitance", InputFormatSpectrum);
            m_inputs.declare("exitance_multiplier", InputFormatScalar, "1.0");
        }

        virtual void release() override
        {
            delete this;
        }

        virtual const char* get_model() const override
        {
            return Model;
        }

        virtual bool on_frame_begin(
            const Project&      project,
            const Assembly&     assembly) override
        {
            if (!Light::on_frame_begin(project, assembly))
                return false;

            m_exitance_source = m_inputs.source("exitance");
            m_exitance_multiplier_source = m_inputs.source("exitance_multiplier");

            check_non_zero_exitance(m_exitance_source, m_exitance_multiplier_source);

            const double inner_half_angle = deg_to_rad(m_params.get_required<double>("inner_angle", 20.0) / 2.0);
            const double outer_half_angle = deg_to_rad(m_params.get_required<double>("outer_angle", 30.0) / 2.0);
            const double tilt_angle = deg_to_rad(m_params.get_optional<double>("tilt_angle", 0.0));

            m_cos_inner_half_angle = cos(inner_half_angle);
            m_cos_outer_half_angle = cos(outer_half_angle);
            m_rcp_screen_half_size = 1.0 / tan(outer_half_angle);

            m_transform = Transformd(Matrix4d::rotation(Vector3d(1.0, 0.0, 0.0), -HalfPi)) * get_transform();
            m_axis = normalize(m_transform.vector_to_parent(Vector3d(0.0, 1.0, 0.0)));

            const Vector3d up = m_transform.vector_to_parent(Vector3d(sin(tilt_angle), 0.0, cos(tilt_angle)));
            const Vector3d v = -m_axis;
            const Vector3d u = normalize(cross(up, v));
            const Vector3d n = cross(v, u);

            m_screen_basis.build(n, u, v);

            return true;
        }

        void evaluate_inputs(
            InputEvaluator&     input_evaluator,
            const Vector3d&     outgoing) const override
        {
            const double cos_theta = dot(outgoing, m_axis);
            const Vector3d d = outgoing / cos_theta - m_axis;
            const double x = dot(d, m_screen_basis.get_tangent_u()) * m_rcp_screen_half_size;
            const double y = dot(d, m_screen_basis.get_normal()) * m_rcp_screen_half_size;
            const Vector2d uv(0.5 * (x + 1.0), 0.5 * (y + 1.0));

            input_evaluator.evaluate(m_inputs, uv);
        }

        virtual void sample(
            const void*         data,
            const Vector2d&     s,
            Vector3d&           outgoing,
            Spectrum&           value,
            double&             probability) const override
        {
            const Vector3d wo = sample_cone_uniform(s, m_cos_outer_half_angle);
            outgoing = m_transform.vector_to_parent(wo);

            compute_exitance(data, wo.y, value);

            probability = sample_cone_uniform_pdf(m_cos_outer_half_angle);
        }

        virtual void evaluate(
            const void*         data,
            const Vector3d&     outgoing,
            Spectrum&           value) const override
        {
            const double cos_theta = dot(outgoing, m_axis);

            if (cos_theta > m_cos_outer_half_angle)
                compute_exitance(data, cos_theta, value);
            else value.set(0.0f);
        }

        virtual void evaluate(
            const void*         data,
            const Vector3d&     outgoing,
            Spectrum&           value,
            double&             probability) const override
        {
            const double cos_theta = dot(outgoing, m_axis);

            if (cos_theta > m_cos_outer_half_angle)
            {
                compute_exitance(data, cos_theta, value);
                probability = sample_cone_uniform_pdf(m_cos_outer_half_angle);
            }
            else
            {
                value.set(0.0f);
                probability = 0.0f;
            }
        }

        virtual double evaluate_pdf(
            const void*         data,
            const Vector3d&     outgoing) const override
        {
            const double cos_theta = dot(outgoing, m_axis);

            return
                cos_theta > m_cos_outer_half_angle
                    ? sample_cone_uniform_pdf(m_cos_outer_half_angle)
                    : 0.0;
        }

      private:
        struct InputValues
        {
            Spectrum    m_exitance;             // radiant exitance, in W.m^-2
            Alpha       m_exitance_alpha;       // unused
            double      m_exitance_multiplier;  // radiant exitance multiplier
        };

        const Source*   m_exitance_source;
        const Source*   m_exitance_multiplier_source;

        double          m_cos_inner_half_angle;
        double          m_cos_outer_half_angle;
        double          m_rcp_screen_half_size;

        Transformd      m_transform;
        Vector3d        m_axis;                 // world space
        Basis3d         m_screen_basis;         // world space

        void compute_exitance(
            const void*         data,
            const double        cos_theta,
            Spectrum&           exitance) const
        {
            assert(cos_theta > m_cos_outer_half_angle);

            const InputValues* values = static_cast<const InputValues*>(data);
            exitance = values->m_exitance;
            exitance *= static_cast<float>(values->m_exitance_multiplier);

            if (cos_theta < m_cos_inner_half_angle)
            {
                exitance *=
                    static_cast<float>(
                        smoothstep(m_cos_outer_half_angle, m_cos_inner_half_angle, cos_theta));
            }
        }
    };
}

//
// SpotLightFactory class implementation.
//

const char* SpotLightFactory::get_model() const
{
    return Model;
}

const char* SpotLightFactory::get_human_readable_model() const
{
    return "Spot Light";
}

DictionaryArray SpotLightFactory::get_widget_definitions() const
{
    DictionaryArray definitions;

    definitions.push_back(
        Dictionary()
            .insert("name", "exitance")
            .insert("label", "Exitance")
            .insert("widget", "entity_picker")
            .insert("entity_types",
                Dictionary()
                    .insert("color", "Colors")
                    .insert("texture_instance", "Textures"))
            .insert("use", "required")
            .insert("default", ""));

    definitions.push_back(
        Dictionary()
            .insert("name", "exitance_multiplier")
            .insert("label", "Exitance Multiplier")
            .insert("widget", "entity_picker")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    definitions.push_back(
        Dictionary()
            .insert("name", "inner_angle")
            .insert("label", "Inner Angle")
            .insert("widget", "text_box")
            .insert("use", "required")
            .insert("default", "20.0"));

    definitions.push_back(
        Dictionary()
            .insert("name", "outer_angle")
            .insert("label", "Outer Angle")
            .insert("widget", "text_box")
            .insert("use", "required")
            .insert("default", "30.0"));

    definitions.push_back(
        Dictionary()
            .insert("name", "tilt_angle")
            .insert("label", "Tilt Angle")
            .insert("widget", "text_box")
            .insert("use", "optional")
            .insert("default", "0.0"));

    return definitions;
}

auto_release_ptr<Light> SpotLightFactory::create(
    const char*         name,
    const ParamArray&   params) const
{
    return auto_release_ptr<Light>(new SpotLight(name, params));
}

}   // namespace renderer
<commit_msg>cosmetics.<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2012 Francois Beaune, Jupiter Jazz Limited
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "spotlight.h"

// appleseed.renderer headers.
#include "renderer/global/globaltypes.h"
#include "renderer/modeling/input/inputarray.h"
#include "renderer/modeling/input/inputevaluator.h"
#include "renderer/modeling/input/source.h"
#include "renderer/utility/paramarray.h"

// appleseed.foundation headers.
#include "foundation/math/basis.h"
#include "foundation/math/matrix.h"
#include "foundation/math/sampling.h"
#include "foundation/math/scalar.h"
#include "foundation/math/transform.h"
#include "foundation/math/vector.h"
#include "foundation/utility/containers/dictionary.h"
#include "foundation/utility/containers/specializedarrays.h"

// Standard headers.
#include <cmath>

// Forward declarations.
namespace renderer  { class Assembly; }
namespace renderer  { class Project; }

using namespace foundation;
using namespace std;

namespace renderer
{

namespace
{
    //
    // Spot light.
    //

    const char* Model = "spot_light";

    class SpotLight
      : public Light
    {
      public:
        SpotLight(
            const char*         name,
            const ParamArray&   params)
          : Light(name, params)
        {
            m_inputs.declare("exitance", InputFormatSpectrum);
            m_inputs.declare("exitance_multiplier", InputFormatScalar, "1.0");
        }

        virtual void release() override
        {
            delete this;
        }

        virtual const char* get_model() const override
        {
            return Model;
        }

        virtual bool on_frame_begin(
            const Project&      project,
            const Assembly&     assembly) override
        {
            if (!Light::on_frame_begin(project, assembly))
                return false;

            m_exitance_source = m_inputs.source("exitance");
            m_exitance_multiplier_source = m_inputs.source("exitance_multiplier");
            check_non_zero_exitance(m_exitance_source, m_exitance_multiplier_source);

            const double inner_half_angle = deg_to_rad(m_params.get_required<double>("inner_angle", 20.0) / 2.0);
            const double outer_half_angle = deg_to_rad(m_params.get_required<double>("outer_angle", 30.0) / 2.0);
            const double tilt_angle = deg_to_rad(m_params.get_optional<double>("tilt_angle", 0.0));

            m_cos_inner_half_angle = cos(inner_half_angle);
            m_cos_outer_half_angle = cos(outer_half_angle);
            m_rcp_screen_half_size = 1.0 / tan(outer_half_angle);

            m_transform = Transformd(Matrix4d::rotation(Vector3d(1.0, 0.0, 0.0), -HalfPi)) * get_transform();
            m_axis = normalize(m_transform.vector_to_parent(Vector3d(0.0, 1.0, 0.0)));

            const Vector3d up = m_transform.vector_to_parent(Vector3d(sin(tilt_angle), 0.0, cos(tilt_angle)));
            const Vector3d v = -m_axis;
            const Vector3d u = normalize(cross(up, v));
            const Vector3d n = cross(v, u);

            m_screen_basis.build(n, u, v);

            return true;
        }

        void evaluate_inputs(
            InputEvaluator&     input_evaluator,
            const Vector3d&     outgoing) const override
        {
            const double cos_theta = dot(outgoing, m_axis);
            const Vector3d d = outgoing / cos_theta - m_axis;
            const double x = dot(d, m_screen_basis.get_tangent_u()) * m_rcp_screen_half_size;
            const double y = dot(d, m_screen_basis.get_normal()) * m_rcp_screen_half_size;
            const Vector2d uv(0.5 * (x + 1.0), 0.5 * (y + 1.0));

            input_evaluator.evaluate(m_inputs, uv);
        }

        virtual void sample(
            const void*         data,
            const Vector2d&     s,
            Vector3d&           outgoing,
            Spectrum&           value,
            double&             probability) const override
        {
            const Vector3d wo = sample_cone_uniform(s, m_cos_outer_half_angle);
            outgoing = m_transform.vector_to_parent(wo);

            compute_exitance(data, wo.y, value);

            probability = sample_cone_uniform_pdf(m_cos_outer_half_angle);
        }

        virtual void evaluate(
            const void*         data,
            const Vector3d&     outgoing,
            Spectrum&           value) const override
        {
            const double cos_theta = dot(outgoing, m_axis);

            if (cos_theta > m_cos_outer_half_angle)
                compute_exitance(data, cos_theta, value);
            else value.set(0.0f);
        }

        virtual void evaluate(
            const void*         data,
            const Vector3d&     outgoing,
            Spectrum&           value,
            double&             probability) const override
        {
            const double cos_theta = dot(outgoing, m_axis);

            if (cos_theta > m_cos_outer_half_angle)
            {
                compute_exitance(data, cos_theta, value);
                probability = sample_cone_uniform_pdf(m_cos_outer_half_angle);
            }
            else
            {
                value.set(0.0f);
                probability = 0.0f;
            }
        }

        virtual double evaluate_pdf(
            const void*         data,
            const Vector3d&     outgoing) const override
        {
            const double cos_theta = dot(outgoing, m_axis);

            return
                cos_theta > m_cos_outer_half_angle
                    ? sample_cone_uniform_pdf(m_cos_outer_half_angle)
                    : 0.0;
        }

      private:
        struct InputValues
        {
            Spectrum    m_exitance;             // radiant exitance, in W.m^-2
            Alpha       m_exitance_alpha;       // unused
            double      m_exitance_multiplier;  // radiant exitance multiplier
        };

        const Source*   m_exitance_source;
        const Source*   m_exitance_multiplier_source;

        double          m_cos_inner_half_angle;
        double          m_cos_outer_half_angle;
        double          m_rcp_screen_half_size;

        Transformd      m_transform;
        Vector3d        m_axis;                 // world space
        Basis3d         m_screen_basis;         // world space

        void compute_exitance(
            const void*         data,
            const double        cos_theta,
            Spectrum&           exitance) const
        {
            assert(cos_theta > m_cos_outer_half_angle);

            const InputValues* values = static_cast<const InputValues*>(data);
            exitance = values->m_exitance;
            exitance *= static_cast<float>(values->m_exitance_multiplier);

            if (cos_theta < m_cos_inner_half_angle)
            {
                exitance *=
                    static_cast<float>(
                        smoothstep(m_cos_outer_half_angle, m_cos_inner_half_angle, cos_theta));
            }
        }
    };
}

//
// SpotLightFactory class implementation.
//

const char* SpotLightFactory::get_model() const
{
    return Model;
}

const char* SpotLightFactory::get_human_readable_model() const
{
    return "Spot Light";
}

DictionaryArray SpotLightFactory::get_widget_definitions() const
{
    DictionaryArray definitions;

    definitions.push_back(
        Dictionary()
            .insert("name", "exitance")
            .insert("label", "Exitance")
            .insert("widget", "entity_picker")
            .insert("entity_types",
                Dictionary()
                    .insert("color", "Colors")
                    .insert("texture_instance", "Textures"))
            .insert("use", "required")
            .insert("default", ""));

    definitions.push_back(
        Dictionary()
            .insert("name", "exitance_multiplier")
            .insert("label", "Exitance Multiplier")
            .insert("widget", "entity_picker")
            .insert("entity_types",
                Dictionary().insert("texture_instance", "Textures"))
            .insert("use", "optional")
            .insert("default", "1.0"));

    definitions.push_back(
        Dictionary()
            .insert("name", "inner_angle")
            .insert("label", "Inner Angle")
            .insert("widget", "text_box")
            .insert("use", "required")
            .insert("default", "20.0"));

    definitions.push_back(
        Dictionary()
            .insert("name", "outer_angle")
            .insert("label", "Outer Angle")
            .insert("widget", "text_box")
            .insert("use", "required")
            .insert("default", "30.0"));

    definitions.push_back(
        Dictionary()
            .insert("name", "tilt_angle")
            .insert("label", "Tilt Angle")
            .insert("widget", "text_box")
            .insert("use", "optional")
            .insert("default", "0.0"));

    return definitions;
}

auto_release_ptr<Light> SpotLightFactory::create(
    const char*         name,
    const ParamArray&   params) const
{
    return auto_release_ptr<Light>(new SpotLight(name, params));
}

}   // namespace renderer
<|endoftext|>


<commit_before>#include "glm/gtc/matrix_transform.hpp"

#include "pixelboost/logic/component/transform.h"
#include "pixelboost/logic/message/transform.h"
#include "pixelboost/logic/entity.h"
#include "pixelboost/logic/scene.h"
#include "pixelboost/maths/matrixHelpers.h"

using namespace pb;

PB_DEFINE_COMPONENT(pb::TransformComponent)

TransformComponent::TransformComponent(Entity* parent)
    : Component(parent)
    , _Dirty(kDirtyTypeNone)
    , _Scale(1,1,1)
{

}

TransformComponent::~TransformComponent()
{

}

const glm::mat4x4& TransformComponent::GetMatrix()
{
    if (_Dirty != kDirtyTypeNone)
    {
        if (_Dirty == kDirtyTypeThis)
        {
            _LocalMatrix = CreateTransformMatrix(pb::kRotationOrder_XYZ, _Position, _Rotation, _Scale);
        }

        if (GetEntity()->GetParent())
        {
            _Matrix = _LocalMatrix * GetEntity()->GetParent()->GetComponent<TransformComponent>()->GetMatrix();
        }
    }

    if (GetEntity()->GetParent())
    {
        return _Matrix;
    }

    return _LocalMatrix;
}

void TransformComponent::SetTransform(const glm::vec3& position, const glm::vec3& rotation, const glm::vec3& scale)
{
    _Position = position;
    _Rotation = rotation;
    _Scale = scale;

    Dirty(true);
}

glm::vec3 TransformComponent::GetPosition()
{
    return _Position;
}

void TransformComponent::SetPosition(const glm::vec3& position)
{
    _Position = position;

    Dirty(true);
}

glm::vec3 TransformComponent::GetRotation()
{
    return _Rotation;
}

void TransformComponent::SetRotation(const glm::vec3& rotation)
{
    _Rotation = rotation;

    Dirty(true);
}

glm::vec3 TransformComponent::GetScale()
{
    return _Scale;
}

void TransformComponent::SetScale(const glm::vec3& scale)
{
    _Scale = scale;

    Dirty(true);
}

void TransformComponent::Dirty(bool dirtyThis)
{
    if (_Dirty != kDirtyTypeThis)
        _Dirty = dirtyThis ? kDirtyTypeThis : kDirtyTypeParent;

    for (const auto& child : GetEntity()->GetChildren())
    {
        TransformComponent* transform = child->GetComponent<pb::TransformComponent>();
        if (transform)
        {
            transform->Dirty(false);
        }
    }

    TransformChangedMessage message(GetEntity(), this);
    GetScene()->SendMessage(GetEntityUid(), message);
}
<commit_msg>Fix transform when parented<commit_after>#include "glm/gtc/matrix_transform.hpp"

#include "pixelboost/logic/component/transform.h"
#include "pixelboost/logic/message/transform.h"
#include "pixelboost/logic/entity.h"
#include "pixelboost/logic/scene.h"
#include "pixelboost/maths/matrixHelpers.h"

using namespace pb;

PB_DEFINE_COMPONENT(pb::TransformComponent)

TransformComponent::TransformComponent(Entity* parent)
    : Component(parent)
    , _Dirty(kDirtyTypeThis)
    , _Scale(1,1,1)
{

}

TransformComponent::~TransformComponent()
{

}

const glm::mat4x4& TransformComponent::GetMatrix()
{
    if (_Dirty != kDirtyTypeNone)
    {
        if (_Dirty == kDirtyTypeThis)
        {
            _LocalMatrix = CreateTransformMatrix(pb::kRotationOrder_XYZ, _Position, _Rotation, _Scale);
        }

        if (GetEntity()->GetParent())
        {
            _Matrix = GetEntity()->GetParent()->GetComponent<TransformComponent>()->GetMatrix() * _LocalMatrix;
        }
    }

    if (GetEntity()->GetParent())
    {
        return _Matrix;
    }

    return _LocalMatrix;
}

void TransformComponent::SetTransform(const glm::vec3& position, const glm::vec3& rotation, const glm::vec3& scale)
{
    _Position = position;
    _Rotation = rotation;
    _Scale = scale;

    Dirty(true);
}

glm::vec3 TransformComponent::GetPosition()
{
    return _Position;
}

void TransformComponent::SetPosition(const glm::vec3& position)
{
    _Position = position;

    Dirty(true);
}

glm::vec3 TransformComponent::GetRotation()
{
    return _Rotation;
}

void TransformComponent::SetRotation(const glm::vec3& rotation)
{
    _Rotation = rotation;

    Dirty(true);
}

glm::vec3 TransformComponent::GetScale()
{
    return _Scale;
}

void TransformComponent::SetScale(const glm::vec3& scale)
{
    _Scale = scale;

    Dirty(true);
}

void TransformComponent::Dirty(bool dirtyThis)
{
    if (_Dirty != kDirtyTypeThis)
        _Dirty = dirtyThis ? kDirtyTypeThis : kDirtyTypeParent;

    for (const auto& child : GetEntity()->GetChildren())
    {
        TransformComponent* transform = child->GetComponent<pb::TransformComponent>();
        if (transform)
        {
            transform->Dirty(false);
        }
    }

    TransformChangedMessage message(GetEntity(), this);
    GetScene()->SendMessage(GetEntityUid(), message);
}
<|endoftext|>


<commit_before>#include "application_manager/hmi_state.h"
#include "utils/helpers.h"

namespace application_manager {

HmiState::HmiState(uint32_t app_id, const StateContext& state_context_,
                   StateID state_id):
  app_id_(app_id),
  state_id_(state_id),
  state_context_(state_context_),
  hmi_level_(mobile_apis::HMILevel::INVALID_ENUM),
  audio_streaming_state_(mobile_apis::AudioStreamingState::INVALID_ENUM),
  system_context_(mobile_apis::SystemContext::INVALID_ENUM) {
}

HmiState::HmiState(uint32_t app_id, const StateContext& state_context):
  app_id_(app_id),
  state_id_(STATE_ID_REGULAR),
  state_context_(state_context),
  hmi_level_(mobile_apis::HMILevel::INVALID_ENUM),
  audio_streaming_state_(mobile_apis::AudioStreamingState::INVALID_ENUM),
  system_context_(mobile_apis::SystemContext::INVALID_ENUM) {
}

void HmiState::set_parent(HmiStatePtr parent) {
  DCHECK_OR_RETURN_VOID(parent);
  parent_ = parent;
}

mobile_apis::AudioStreamingState::eType
VRHmiState::audio_streaming_state() const {
  using namespace mobile_apis;
  return AudioStreamingState::NOT_AUDIBLE;
}

VRHmiState::VRHmiState(uint32_t app_id, StateContext& state_context):
  HmiState(app_id, state_context, STATE_ID_VR_SESSION) {
}

TTSHmiState::TTSHmiState(uint32_t app_id, StateContext& state_context):
  HmiState(app_id, state_context, STATE_ID_TTS_SESSION) {
}

mobile_apis::AudioStreamingState::eType
TTSHmiState::audio_streaming_state() const {
  using namespace helpers;
  using namespace mobile_apis;
  AudioStreamingState::eType expected_state = AudioStreamingState::NOT_AUDIBLE;
  if (state_context_.is_attenuated_supported() &&
      Compare<HMILevel::eType, EQ, ONE> (hmi_level(), HMILevel::HMI_FULL,
                                         HMILevel::HMI_LIMITED)) {
      expected_state = AudioStreamingState::ATTENUATED;
  }
  return expected_state;
}

NaviStreamingHmiState::NaviStreamingHmiState(uint32_t app_id, StateContext& state_context):
  HmiState(app_id, state_context, STATE_ID_NAVI_STREAMING) {
}

mobile_apis::AudioStreamingState::eType
NaviStreamingHmiState::audio_streaming_state() const {
  using namespace helpers;
  using namespace mobile_apis;
  AudioStreamingState::eType expected_state = parent()->audio_streaming_state();
  if (Compare<HMILevel::eType, EQ, ONE> (hmi_level(), HMILevel::HMI_FULL) &&
      !state_context_.is_navi_app(app_id_)) {
    if (state_context_.is_attenuated_supported()) {
      expected_state = AudioStreamingState::ATTENUATED;
    } else {
      expected_state = AudioStreamingState::NOT_AUDIBLE;
    }
  }
  return expected_state;
}

PhoneCallHmiState::PhoneCallHmiState(uint32_t app_id, StateContext& state_context):
  HmiState(app_id, state_context, STATE_ID_PHONE_CALL) {
}

mobile_apis::HMILevel::eType PhoneCallHmiState::hmi_level() const {
  using namespace mobile_apis;
   HMILevel::eType expected_level(HMILevel::HMI_BACKGROUND);
   if (parent()->hmi_level() == HMILevel::HMI_FULL
       && state_context_.is_navi_app(app_id_)) {
     expected_level = HMILevel::HMI_LIMITED;
   }
   return expected_level;
}

SafetyModeHmiState::SafetyModeHmiState(uint32_t app_id, StateContext& state_context):
  HmiState(app_id, state_context, STATE_ID_SAFETY_MODE) {
}

}
<commit_msg>Set ATTENUATED audio state only if current state is AUDIBLE.<commit_after>#include "application_manager/hmi_state.h"
#include "utils/helpers.h"

namespace application_manager {

HmiState::HmiState(uint32_t app_id, const StateContext& state_context_,
                   StateID state_id):
  app_id_(app_id),
  state_id_(state_id),
  state_context_(state_context_),
  hmi_level_(mobile_apis::HMILevel::INVALID_ENUM),
  audio_streaming_state_(mobile_apis::AudioStreamingState::INVALID_ENUM),
  system_context_(mobile_apis::SystemContext::INVALID_ENUM) {
}

HmiState::HmiState(uint32_t app_id, const StateContext& state_context):
  app_id_(app_id),
  state_id_(STATE_ID_REGULAR),
  state_context_(state_context),
  hmi_level_(mobile_apis::HMILevel::INVALID_ENUM),
  audio_streaming_state_(mobile_apis::AudioStreamingState::INVALID_ENUM),
  system_context_(mobile_apis::SystemContext::INVALID_ENUM) {
}

void HmiState::set_parent(HmiStatePtr parent) {
  DCHECK_OR_RETURN_VOID(parent);
  parent_ = parent;
}

mobile_apis::AudioStreamingState::eType
VRHmiState::audio_streaming_state() const {
  using namespace mobile_apis;
  return AudioStreamingState::NOT_AUDIBLE;
}

VRHmiState::VRHmiState(uint32_t app_id, StateContext& state_context):
  HmiState(app_id, state_context, STATE_ID_VR_SESSION) {
}

TTSHmiState::TTSHmiState(uint32_t app_id, StateContext& state_context):
  HmiState(app_id, state_context, STATE_ID_TTS_SESSION) {
}

mobile_apis::AudioStreamingState::eType
TTSHmiState::audio_streaming_state() const {
  using namespace helpers;
  using namespace mobile_apis;

  AudioStreamingState::eType expected_state = AudioStreamingState::NOT_AUDIBLE;
  if (state_context_.is_attenuated_supported() &&
    AudioStreamingState::NOT_AUDIBLE != parent()->audio_streaming_state() &&
    Compare<HMILevel::eType, EQ, ONE> (hmi_level(), HMILevel::HMI_FULL,
                                       HMILevel::HMI_LIMITED)) {
    expected_state = AudioStreamingState::ATTENUATED;
  }
  return expected_state;
}

NaviStreamingHmiState::NaviStreamingHmiState(uint32_t app_id, StateContext& state_context):
  HmiState(app_id, state_context, STATE_ID_NAVI_STREAMING) {
}

mobile_apis::AudioStreamingState::eType
NaviStreamingHmiState::audio_streaming_state() const {
  using namespace helpers;
  using namespace mobile_apis;

  AudioStreamingState::eType expected_state = parent()->audio_streaming_state();
  if (Compare<HMILevel::eType, EQ, ONE> (hmi_level(), HMILevel::HMI_FULL) &&
      !state_context_.is_navi_app(app_id_) &&
      AudioStreamingState::AUDIBLE == expected_state) {
    if (state_context_.is_attenuated_supported()) {
      expected_state = AudioStreamingState::ATTENUATED;
    } else {
      expected_state = AudioStreamingState::NOT_AUDIBLE;
    }
  }
  return expected_state;
}

PhoneCallHmiState::PhoneCallHmiState(uint32_t app_id, StateContext& state_context):
  HmiState(app_id, state_context, STATE_ID_PHONE_CALL) {
}

mobile_apis::HMILevel::eType PhoneCallHmiState::hmi_level() const {
  using namespace mobile_apis;
   HMILevel::eType expected_level(HMILevel::HMI_BACKGROUND);
   if (parent()->hmi_level() == HMILevel::HMI_FULL
       && state_context_.is_navi_app(app_id_)) {
     expected_level = HMILevel::HMI_LIMITED;
   }
   return expected_level;
}

SafetyModeHmiState::SafetyModeHmiState(uint32_t app_id, StateContext& state_context):
  HmiState(app_id, state_context, STATE_ID_SAFETY_MODE) {
}

}
<|endoftext|>


<commit_before>/*
 Copyright (c) 2013, Ford Motor Company
 All rights reserved.

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

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

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include <string>
#include "remote_control/message_helper.h"
#include "remote_control/rc_module_constants.h"
#include "utils/make_shared.h"

namespace remote_control {
using functional_modules::RCFunctionID;
namespace {
std::map<RCFunctionID, std::string> GenerateAPINames() {
  std::map<RCFunctionID, std::string> result;
  result.insert(std::make_pair<RCFunctionID, std::string>(
      RCFunctionID::BUTTON_PRESS, "ButtonPress"));
  result.insert(std::make_pair<RCFunctionID, std::string>(
      RCFunctionID::GET_INTERIOR_VEHICLE_DATA, "GetInteriorVehicleData"));
  result.insert(std::make_pair<RCFunctionID, std::string>(
      RCFunctionID::SET_INTERIOR_VEHICLE_DATA, "SetInteriorVehicleData"));
  result.insert(std::make_pair<RCFunctionID, std::string>(
      RCFunctionID::ON_INTERIOR_VEHICLE_DATA, "OnInteriorVehicleData"));
  result.insert(std::make_pair<RCFunctionID, std::string>(
      RCFunctionID::ON_REMOTE_CONTROL_SETTINGS, "OnRemoteControlSetting"));
  return result;
}

std::map<std::string, hmi_apis::Common_RCAccessMode::eType> access_modes{
    {enums_value::kAutoAllow, hmi_apis::Common_RCAccessMode::AUTO_ALLOW},
    {enums_value::kAutoDeny, hmi_apis::Common_RCAccessMode::AUTO_DENY},
    {enums_value::kAskDriver, hmi_apis::Common_RCAccessMode::ASK_DRIVER}};
}

const std::map<RCFunctionID, std::string> MessageHelper::kMobileAPINames =
    GenerateAPINames();

const std::string MessageHelper::GetMobileAPIName(RCFunctionID func_id) {
  std::map<RCFunctionID, std::string>::const_iterator it =
      kMobileAPINames.find(func_id);
  if (kMobileAPINames.end() != it) {
    return it->second;
  } else {
    return "";
  }
}

std::string MessageHelper::ValueToString(const Json::Value& value) {
  Json::FastWriter writer;

  return writer.write(value);
}

Json::Value MessageHelper::StringToValue(const std::string& string) {
  Json::Reader reader;
  Json::Value json;

  return reader.parse(string, json) ? json
                                    : Json::Value(Json::ValueType::nullValue);
}

bool IsMember(const Json::Value& value, const std::string& key) {
  if (!value.isObject()) {
    return false;
  }

  return value.isMember(key);
}

application_manager::MessagePtr MessageHelper::CreateHmiRequest(
    const char* function_id,
    const uint32_t hmi_app_id,
    const Json::Value& message_params,
    RemotePluginInterface& rc_module) {
  using namespace json_keys;
  Json::Value msg;

  msg[json_keys::kId] = rc_module.service()->GetNextCorrelationID();

  msg[kJsonrpc] = "2.0";
  msg[kMethod] = function_id;
  if (!message_params.isNull()) {
    msg[kParams] = message_params;
  }

  msg[kParams][json_keys::kAppId] = hmi_app_id;

  Json::FastWriter writer;
  application_manager::MessagePtr message_to_send =
      utils::MakeShared<application_manager::Message>(
          application_manager::Message(
              protocol_handler::MessagePriority::kDefault));
  message_to_send->set_protocol_version(
      protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_HMI);
  message_to_send->set_correlation_id(msg[json_keys::kId].asInt());
  message_to_send->set_function_name(msg[kMethod].asString());
  std::string json_msg = writer.write(msg);
  message_to_send->set_json_message(json_msg);
  message_to_send->set_message_type(application_manager::MessageType::kRequest);

  return message_to_send;
}

hmi_apis::Common_RCAccessMode::eType MessageHelper::AccessModeFromString(
    const std::string& access_mode) {
  std::map<std::string, hmi_apis::Common_RCAccessMode::eType>::const_iterator
      mode = access_modes.find(access_mode);
  return access_modes.end() != mode
             ? mode->second
             : hmi_apis::Common_RCAccessMode::INVALID_ENUM;
}

std::string MessageHelper::AccessModeToString(
    const hmi_apis::Common_RCAccessMode::eType access_mode) {
  std::map<std::string, hmi_apis::Common_RCAccessMode::eType>::const_iterator
      it = access_modes.begin();
  for (; access_modes.end() != it; ++it) {
    if (access_mode == it->second) {
      return it->first;
    }
  }
  const std::string error = "UNKNOW_ACCESS_MODE";
  DCHECK_OR_RETURN(false, error);
  return error;
}

}  // namespace remote_control
<commit_msg>Fixes typo in conversion string<commit_after>/*
 Copyright (c) 2013, Ford Motor Company
 All rights reserved.

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

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

 Redistributions in binary form must reproduce the above copyright notice,
 this list of conditions and the following
 disclaimer in the documentation and/or other materials provided with the
 distribution.

 Neither the name of the Ford Motor Company nor the names of its contributors
 may be used to endorse or promote products derived from this software
 without specific prior written permission.

 THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
 AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
 LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
 CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
 SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
 INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
 CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
 POSSIBILITY OF SUCH DAMAGE.
 */

#include <string>
#include "remote_control/message_helper.h"
#include "remote_control/rc_module_constants.h"
#include "utils/make_shared.h"

namespace remote_control {
using functional_modules::RCFunctionID;
namespace {
std::map<RCFunctionID, std::string> GenerateAPINames() {
  std::map<RCFunctionID, std::string> result;
  result.insert(std::make_pair<RCFunctionID, std::string>(
      RCFunctionID::BUTTON_PRESS, "ButtonPress"));
  result.insert(std::make_pair<RCFunctionID, std::string>(
      RCFunctionID::GET_INTERIOR_VEHICLE_DATA, "GetInteriorVehicleData"));
  result.insert(std::make_pair<RCFunctionID, std::string>(
      RCFunctionID::SET_INTERIOR_VEHICLE_DATA, "SetInteriorVehicleData"));
  result.insert(std::make_pair<RCFunctionID, std::string>(
      RCFunctionID::ON_INTERIOR_VEHICLE_DATA, "OnInteriorVehicleData"));
  result.insert(std::make_pair<RCFunctionID, std::string>(
      RCFunctionID::ON_REMOTE_CONTROL_SETTINGS, "OnRemoteControlSettings"));
  return result;
}

std::map<std::string, hmi_apis::Common_RCAccessMode::eType> access_modes{
    {enums_value::kAutoAllow, hmi_apis::Common_RCAccessMode::AUTO_ALLOW},
    {enums_value::kAutoDeny, hmi_apis::Common_RCAccessMode::AUTO_DENY},
    {enums_value::kAskDriver, hmi_apis::Common_RCAccessMode::ASK_DRIVER}};
}

const std::map<RCFunctionID, std::string> MessageHelper::kMobileAPINames =
    GenerateAPINames();

const std::string MessageHelper::GetMobileAPIName(RCFunctionID func_id) {
  std::map<RCFunctionID, std::string>::const_iterator it =
      kMobileAPINames.find(func_id);
  if (kMobileAPINames.end() != it) {
    return it->second;
  } else {
    return "";
  }
}

std::string MessageHelper::ValueToString(const Json::Value& value) {
  Json::FastWriter writer;

  return writer.write(value);
}

Json::Value MessageHelper::StringToValue(const std::string& string) {
  Json::Reader reader;
  Json::Value json;

  return reader.parse(string, json) ? json
                                    : Json::Value(Json::ValueType::nullValue);
}

bool IsMember(const Json::Value& value, const std::string& key) {
  if (!value.isObject()) {
    return false;
  }

  return value.isMember(key);
}

application_manager::MessagePtr MessageHelper::CreateHmiRequest(
    const char* function_id,
    const uint32_t hmi_app_id,
    const Json::Value& message_params,
    RemotePluginInterface& rc_module) {
  using namespace json_keys;
  Json::Value msg;

  msg[json_keys::kId] = rc_module.service()->GetNextCorrelationID();

  msg[kJsonrpc] = "2.0";
  msg[kMethod] = function_id;
  if (!message_params.isNull()) {
    msg[kParams] = message_params;
  }

  msg[kParams][json_keys::kAppId] = hmi_app_id;

  Json::FastWriter writer;
  application_manager::MessagePtr message_to_send =
      utils::MakeShared<application_manager::Message>(
          application_manager::Message(
              protocol_handler::MessagePriority::kDefault));
  message_to_send->set_protocol_version(
      protocol_handler::MajorProtocolVersion::PROTOCOL_VERSION_HMI);
  message_to_send->set_correlation_id(msg[json_keys::kId].asInt());
  message_to_send->set_function_name(msg[kMethod].asString());
  std::string json_msg = writer.write(msg);
  message_to_send->set_json_message(json_msg);
  message_to_send->set_message_type(application_manager::MessageType::kRequest);

  return message_to_send;
}

hmi_apis::Common_RCAccessMode::eType MessageHelper::AccessModeFromString(
    const std::string& access_mode) {
  std::map<std::string, hmi_apis::Common_RCAccessMode::eType>::const_iterator
      mode = access_modes.find(access_mode);
  return access_modes.end() != mode
             ? mode->second
             : hmi_apis::Common_RCAccessMode::INVALID_ENUM;
}

std::string MessageHelper::AccessModeToString(
    const hmi_apis::Common_RCAccessMode::eType access_mode) {
  std::map<std::string, hmi_apis::Common_RCAccessMode::eType>::const_iterator
      it = access_modes.begin();
  for (; access_modes.end() != it; ++it) {
    if (access_mode == it->second) {
      return it->first;
    }
  }
  const std::string error = "UNKNOW_ACCESS_MODE";
  DCHECK_OR_RETURN(false, error);
  return error;
}

}  // namespace remote_control
<|endoftext|>


<commit_before>#include "term_buffer.h"
#include "term_window.h"
#include "term_cell.h"

#include "cap_manager.h"

#include <iostream>

DEFINE_CAP(enable_mode);
DEFINE_CAP(disable_mode);
DEFINE_CAP(enter_bold_mode);
DEFINE_CAP(enter_reverse_mode);
DEFINE_CAP(keypad_xmit);
DEFINE_CAP(exit_standout_mode);
DEFINE_CAP(enter_ca_mode);
DEFINE_CAP(exit_ca_mode);

void enable_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    auto mode = params[0];

    const std::vector<int> empty_params {};

    if (mode == 25) {
        handle_cap(term_context, "cursor_normal", params);
    }
    else if (mode == 40){
        term_context.dec_mode = true;
        term_context.force_column = true;
        resize_terminal(term_context);
    }
    else if (mode == 3) {
        if (term_context.dec_mode){
            term_context.force_column = true;
            term_context.force_column_count = 132;
            resize_terminal(term_context);

            handle_cap(term_context, "clr_eos", empty_params);
            handle_cap(term_context, "cursor_home", empty_params);
        }
    }
    else if (mode == 5) {
        term_context.cell_template->AddMode(TermCell::Reverse);
    }
    else if (mode == 6) {
        term_context.origin_mode = true;
        handle_cap(term_context, "cursor_home", empty_params);
    }
    else if (mode == 7) {
        term_context.auto_wrap = true;
    }
    else {
        std::cerr << "enable mode not implemented, with params:[";
        std::copy(params.begin(), params.end(), std::ostream_iterator<int>(std::cerr, ","));
        std::cerr << "]" << std::endl;
    }
}

void disable_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    auto mode = params[0];

    const std::vector<int> empty_params {};

    if (mode == 25) {
        handle_cap(term_context, "cursor_invisible", params);
    }
    else if (mode == 40){
        term_context.dec_mode = false;
        term_context.force_column = false;
        resize_terminal(term_context);
    }
    else if (mode == 3) {
        if (term_context.dec_mode){
            term_context.force_column = true;
            term_context.force_column_count = 80;
            resize_terminal(term_context);

            handle_cap(term_context, "clr_eos", empty_params);
            handle_cap(term_context, "cursor_home", empty_params);
        }
    }
    else if (mode == 5) {
        term_context.cell_template->RemoveMode(TermCell::Reverse);
    }
    else if (mode == 6) {
        term_context.origin_mode = false;
        handle_cap(term_context, "cursor_home", empty_params);
    }
    else if (mode == 7) {
        term_context.auto_wrap = false;
    }
    else {
        std::cerr << "disable mode not implemented, with params:[";
        std::copy(params.begin(), params.end(), std::ostream_iterator<int>(std::cerr, ","));
        std::cerr << "]" << std::endl;
    }
}

void enter_bold_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    (void)params;
    term_context.cell_template->AddMode(TermCell::Bold);
    term_context.term_buffer->AddMode(TermCell::Bold);
}
void keypad_xmit(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    (void)params;
    term_context.keypad_transmit_mode = true;
}
void enter_reverse_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    (void)params;
    term_context.cell_template->AddMode(TermCell::Reverse);
    term_context.term_buffer->AddMode(TermCell::Reverse);
}

void exit_standout_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    (void)params;
    term_context.cell_template->SetMode(term_context.default_cell_template->GetMode());
    term_context.term_buffer->SetMode(term_context.default_cell_template->GetMode());
}

void enter_ca_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    (void)params;
    term_context.saved_cell_template = term_context.cell_template;
    term_context.cell_template = term_context.term_buffer->CreateCellWithDefaults();
    term_context.term_buffer->EnableAlterBuffer(true);
}
void exit_ca_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    (void)params;
    term_context.cell_template = term_context.saved_cell_template;
    term_context.term_buffer->EnableAlterBuffer(false);
}
/*
    def exit_alt_charset_mode(self, context):
        self.charset_modes_translate[0] = None
        self.exit_standout_mode(context)
        if self.is_debug():
            LOGGER.debug('exit alt:{} {}'.format(' at ', self.get_cursor()))

    def enter_alt_charset_mode(self, context):
        self.charset_modes_translate[0] = translate_char
        if self.is_debug():
            LOGGER.debug('enter alt:{} {}'.format(' at ', self.get_cursor()))

    def enter_alt_charset_mode_british(self, context):
        self.charset_modes_translate[0] = translate_char_british

    def enter_alt_charset_mode_g1(self, context):
        self.charset_modes_translate[1] = translate_char

    def enter_alt_charset_mode_g1_british(self, context):
        self.charset_modes_translate[1] = translate_char_british

    def exit_alt_charset_mode_g1_british(self, context):
        self.charset_modes_translate[1] = None
        self.exit_standout_mode(context)

    def shift_in_to_charset_mode_g0(self, context):
        self.charset_mode = 0

    def shift_out_to_charset_mode_g1(self, context):
        self.charset_mode = 1
*/
<commit_msg>fix linux build problem<commit_after>#include "term_buffer.h"
#include "term_window.h"
#include "term_cell.h"

#include "cap_manager.h"

#include <iostream>
#include <iterator> // for ostream_iterator

DEFINE_CAP(enable_mode);
DEFINE_CAP(disable_mode);
DEFINE_CAP(enter_bold_mode);
DEFINE_CAP(enter_reverse_mode);
DEFINE_CAP(keypad_xmit);
DEFINE_CAP(exit_standout_mode);
DEFINE_CAP(enter_ca_mode);
DEFINE_CAP(exit_ca_mode);

void enable_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    auto mode = params[0];

    const std::vector<int> empty_params {};

    if (mode == 25) {
        handle_cap(term_context, "cursor_normal", params);
    }
    else if (mode == 40){
        term_context.dec_mode = true;
        term_context.force_column = true;
        resize_terminal(term_context);
    }
    else if (mode == 3) {
        if (term_context.dec_mode){
            term_context.force_column = true;
            term_context.force_column_count = 132;
            resize_terminal(term_context);

            handle_cap(term_context, "clr_eos", empty_params);
            handle_cap(term_context, "cursor_home", empty_params);
        }
    }
    else if (mode == 5) {
        term_context.cell_template->AddMode(TermCell::Reverse);
    }
    else if (mode == 6) {
        term_context.origin_mode = true;
        handle_cap(term_context, "cursor_home", empty_params);
    }
    else if (mode == 7) {
        term_context.auto_wrap = true;
    }
    else {
        std::cerr << "enable mode not implemented, with params:[";
        std::copy(params.begin(), params.end(), std::ostream_iterator<int>(std::cerr, ","));
        std::cerr << "]" << std::endl;
    }
}

void disable_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    auto mode = params[0];

    const std::vector<int> empty_params {};

    if (mode == 25) {
        handle_cap(term_context, "cursor_invisible", params);
    }
    else if (mode == 40){
        term_context.dec_mode = false;
        term_context.force_column = false;
        resize_terminal(term_context);
    }
    else if (mode == 3) {
        if (term_context.dec_mode){
            term_context.force_column = true;
            term_context.force_column_count = 80;
            resize_terminal(term_context);

            handle_cap(term_context, "clr_eos", empty_params);
            handle_cap(term_context, "cursor_home", empty_params);
        }
    }
    else if (mode == 5) {
        term_context.cell_template->RemoveMode(TermCell::Reverse);
    }
    else if (mode == 6) {
        term_context.origin_mode = false;
        handle_cap(term_context, "cursor_home", empty_params);
    }
    else if (mode == 7) {
        term_context.auto_wrap = false;
    }
    else {
        std::cerr << "disable mode not implemented, with params:[";
        std::copy(params.begin(), params.end(), std::ostream_iterator<int>(std::cerr, ","));
        std::cerr << "]" << std::endl;
    }
}

void enter_bold_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    (void)params;
    term_context.cell_template->AddMode(TermCell::Bold);
    term_context.term_buffer->AddMode(TermCell::Bold);
}
void keypad_xmit(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    (void)params;
    term_context.keypad_transmit_mode = true;
}
void enter_reverse_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    (void)params;
    term_context.cell_template->AddMode(TermCell::Reverse);
    term_context.term_buffer->AddMode(TermCell::Reverse);
}

void exit_standout_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    (void)params;
    term_context.cell_template->SetMode(term_context.default_cell_template->GetMode());
    term_context.term_buffer->SetMode(term_context.default_cell_template->GetMode());
}

void enter_ca_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    (void)params;
    term_context.saved_cell_template = term_context.cell_template;
    term_context.cell_template = term_context.term_buffer->CreateCellWithDefaults();
    term_context.term_buffer->EnableAlterBuffer(true);
}
void exit_ca_mode(term_data_context_s & term_context,
                    const std::vector<int> & params) {
    (void)params;
    term_context.cell_template = term_context.saved_cell_template;
    term_context.term_buffer->EnableAlterBuffer(false);
}
/*
    def exit_alt_charset_mode(self, context):
        self.charset_modes_translate[0] = None
        self.exit_standout_mode(context)
        if self.is_debug():
            LOGGER.debug('exit alt:{} {}'.format(' at ', self.get_cursor()))

    def enter_alt_charset_mode(self, context):
        self.charset_modes_translate[0] = translate_char
        if self.is_debug():
            LOGGER.debug('enter alt:{} {}'.format(' at ', self.get_cursor()))

    def enter_alt_charset_mode_british(self, context):
        self.charset_modes_translate[0] = translate_char_british

    def enter_alt_charset_mode_g1(self, context):
        self.charset_modes_translate[1] = translate_char

    def enter_alt_charset_mode_g1_british(self, context):
        self.charset_modes_translate[1] = translate_char_british

    def exit_alt_charset_mode_g1_british(self, context):
        self.charset_modes_translate[1] = None
        self.exit_standout_mode(context)

    def shift_in_to_charset_mode_g0(self, context):
        self.charset_mode = 0

    def shift_out_to_charset_mode_g1(self, context):
        self.charset_mode = 1
*/
<|endoftext|>


<commit_before>/*
 * feature suite - Feature detection suite
 *
 * Copyright (c) 2013-2015 FOXEL SA - http://foxel.ch
 * Please read <http://foxel.ch/license> for more information.
 *
 *
 * Author(s):
 *
 *      Nils Hamel <n.hamel@foxel.ch>
 *
 *
 * This file is part of the FOXEL project <http://foxel.ch>.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 *      You are required to preserve legal notices and author attributions in
 *      that material or in the Appropriate Legal Notices displayed by works
 *      containing it.
 *
 *      You are required to attribute the work as explained in the "Usage and
 *      Attribution" section of <http://foxel.ch/license>.
 */

/*
    Source - Includes
 */

    # include "feature-file-concat.hpp"

/*
    Source - Entry point
 */

    int main ( int argc, char ** argv ) {

        /* Path variables */
        char fsFileA[256] = { 0 };
        char fsFileB[256] = { 0 };
        char fsFileO[256] = { 0 };

        /* Reading variables */
        int fsCountA ( 0 );
        int fsCountB ( 0 );

        /* Stream variables */
        std::fstream fsStreamA;
        std::fstream fsStreamB;
        std::fstream fsStreamO;

        /* Line buffer */
        std::string fsLine;

        /* Arguments and parameters handle */
        lc_stdp( lc_stda( argc, argv, "--input-a", "-a" ), argv, fsFileA, LC_STRING );
        lc_stdp( lc_stda( argc, argv, "--input-b", "-b" ), argv, fsFileB, LC_STRING );
        lc_stdp( lc_stda( argc, argv, "--output" , "-o" ), argv, fsFileO, LC_STRING );

        /* Software swicth */
        if ( ( lc_stda( argc, argv, "--help", "-h" ) ) || ( argc <= 1 ) ) {

            /* Display message */
            std::cout << FS_HELP;

        } else {

            /* Open input stream */
            fsStreamA.open( fsFileA, std::ios::in );

            /* Check stream openning */
            if ( fsStreamA.is_open() == true ) {

                /* Open input stream */
                fsStreamB.open( fsFileB, std::ios::in );

                /* Check stream openning */
                if ( fsStreamB.is_open() == true ) {

                    /* Open output stream */
                    fsStreamO.open( fsFileO, std::ios::out );

                    /* Check stream openning */
                    if ( fsStreamO.is_open() == true ) {

                        /* Read elements count */
                        std::getline( fsStreamA, fsLine ); fsCountA = std::stoi( fsLine );
                        std::getline( fsStreamB, fsLine ); fsCountB = std::stoi( fsLine );

                        /* Export concatenation count */
                        fsStreamO << fsCountA + fsCountB << std::endl;

                        /* Read matches coordinates */
                        for ( int fsIndex( 0 ); fsIndex < fsCountA; fsIndex ++ ) {

                            /* Import input file line */
                            std::getline( fsStreamA, fsLine );

                            /* Export line in output file */
                            fsStreamO << fsLine << std::endl;

                        }

                        /* Close input stream */
                        fsStreamA.close();

                        /* Read matches coordinates */
                        for ( int fsIndex( 0 ); fsIndex < fsCountB; fsIndex ++ ) {

                            /* Import input file line */
                            std::getline( fsStreamB, fsLine );

                            /* Export line in output file */
                            fsStreamO << fsLine << std::endl;

                        }

                        /* Close input stream */
                        fsStreamB.close();

                        /* Close output stream */
                        fsStreamO.close();

                        /* Display message */
                        std::cout << "Exported " << fsCountA + fsCountB << " in " << fsFileO << " output file" << std::endl;

                    /* Display message */
                    } else { std::cout << "Error : Unable to open output file" << std::endl; }

                /* Display message */
                } else { std::cout << "Error : Unable to open second input file" << std::endl; }

            /* Display message */
            } else { std::cout << "Error : Unable to open first input file" << std::endl; }

        }

        /* Return to system */
        return( EXIT_SUCCESS );

    }

<commit_msg>Adaptation of feature-file-concat to new arguments and parameters management<commit_after>/*
 * feature suite - Feature detection suite
 *
 * Copyright (c) 2013-2015 FOXEL SA - http://foxel.ch
 * Please read <http://foxel.ch/license> for more information.
 *
 *
 * Author(s):
 *
 *      Nils Hamel <n.hamel@foxel.ch>
 *
 *
 * This file is part of the FOXEL project <http://foxel.ch>.
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *
 * Additional Terms:
 *
 *      You are required to preserve legal notices and author attributions in
 *      that material or in the Appropriate Legal Notices displayed by works
 *      containing it.
 *
 *      You are required to attribute the work as explained in the "Usage and
 *      Attribution" section of <http://foxel.ch/license>.
 */

/*
    Source - Includes
 */

    # include "feature-file-concat.hpp"

/*
    Source - Entry point
 */

    int main ( int argc, char ** argv ) {

        /* Path variables */
        char * fsFileA( NULL );
        char * fsFileB( NULL );
        char * fsFileO( NULL );

        /* Reading variables */
        int fsCountA ( 0 );
        int fsCountB ( 0 );

        /* Stream variables */
        std::fstream fsStreamA;
        std::fstream fsStreamB;
        std::fstream fsStreamO;

        /* Line buffer */
        std::string fsLine;

        /* Arguments and parameters handle */
        lc_stdp( lc_stda( argc, argv, "--input-a", "-a" ), argv, & fsFileA, LC_STRING );
        lc_stdp( lc_stda( argc, argv, "--input-b", "-b" ), argv, & fsFileB, LC_STRING );
        lc_stdp( lc_stda( argc, argv, "--output" , "-o" ), argv, & fsFileO, LC_STRING );

        /* Software swicth */
        if ( ( lc_stda( argc, argv, "--help", "-h" ) ) || ( argc <= 1 ) ) {

            /* Display message */
            std::cout << FS_HELP;

        } else {

            /* Verify path strings */
            if ( ( fsFileA != NULL ) && ( fsFileB != NULL ) && ( fsFileO != NULL ) ) {

                /* Open input stream */
                fsStreamA.open( fsFileA, std::ios::in );

                /* Check stream openning */
                if ( fsStreamA.is_open() == true ) {

                    /* Open input stream */
                    fsStreamB.open( fsFileB, std::ios::in );

                    /* Check stream openning */
                    if ( fsStreamB.is_open() == true ) {

                        /* Open output stream */
                        fsStreamO.open( fsFileO, std::ios::out );

                        /* Check stream openning */
                        if ( fsStreamO.is_open() == true ) {

                            /* Read elements count */
                            std::getline( fsStreamA, fsLine ); fsCountA = std::stoi( fsLine );
                            std::getline( fsStreamB, fsLine ); fsCountB = std::stoi( fsLine );

                            /* Export concatenation count */
                            fsStreamO << fsCountA + fsCountB << std::endl;

                            /* Read matches coordinates */
                            for ( int fsIndex( 0 ); fsIndex < fsCountA; fsIndex ++ ) {

                                /* Import input file line */
                                std::getline( fsStreamA, fsLine );

                                /* Export line in output file */
                                fsStreamO << fsLine << std::endl;

                            }

                            /* Close input stream */
                            fsStreamA.close();

                            /* Read matches coordinates */
                            for ( int fsIndex( 0 ); fsIndex < fsCountB; fsIndex ++ ) {

                                /* Import input file line */
                                std::getline( fsStreamB, fsLine );

                                /* Export line in output file */
                                fsStreamO << fsLine << std::endl;

                            }

                            /* Close input stream */
                            fsStreamB.close();

                            /* Close output stream */
                            fsStreamO.close();

                            /* Display message */
                            std::cout << "Exported " << fsCountA + fsCountB << " in " << fsFileO << " output file" << std::endl;

                        /* Display message */
                        } else { std::cout << "Error : Unable to open output file" << std::endl; }

                    /* Display message */
                    } else { std::cout << "Error : Unable to open second input file" << std::endl; }

                /* Display message */
                } else { std::cout << "Error : Unable to open first input file" << std::endl; }

            /* Display message */
            } else { std::cout << "Error : Invalid path specification" << std::endl; }

        }

        /* Return to system */
        return( EXIT_SUCCESS );

    }

<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_reset.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_pm_reset.H
/// @brief Wrapper that calls underlying HWPs to perform a Power Management
///        Reset function when needing to restart the OCC complex.
///
// *HWP HWP Owner        : Greg Still <stillgs@us.ibm.com>
// *HWP HWP Backup Owner :
// *HWP FW Owner         : Sangeetha T S <sangeet2@in.ibm.com>
// *HWP Team             : PM
// *HWP Level            : 2
// *HWP Consumed by      : HS

#ifndef _P9_PM_RESET_H
#define _P9_PM_RESET_H

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

// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include <fapi2.H>
#include <p9_pm.H>
#include <p9_pm_utils.H>
#include <p9_misc_scom_addresses.H>
#include <p9_pm_firinit.H>
#include <p9_pm_occ_control.H>
#include <p9_cpu_special_wakeup.H>
#include <p9_pm_stop_gpe_init.H>
#include <p9_pm_occ_gpe_init.H>
#include <p9_pm_corequad_init.H>
#include <p9_pm_pba_init.H>
#include <p9_pm_occ_sram_init.H>
#include <p9_pm_ocb_init.H>
#include <p9_pm_pss_init.H>

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

// -----------------------------------------------------------------------------
// Function Prototype
// -----------------------------------------------------------------------------
extern "C"
{
//------------------------------------------------------------------------------
///
/// @brief Call underlying unit procedures to reset PM complex
///
/// @param[in] i_target Proc Chip target
///
/// @return FAPI2_RC_SUCCESS on success, else error code.
///
    fapi2::ReturnCode p9_pm_reset(
        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);
}

#endif // _P9_PM_RESET_H
<commit_msg>Modifications to reset/init procedures<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_pm_reset.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_pm_reset.H
/// @brief Wrapper that calls underlying HWPs to perform a Power Management
///        Reset function when needing to restart the OCC complex.
///
// *HWP HWP Owner        : Greg Still <stillgs@us.ibm.com>
// *HWP HWP Backup Owner :
// *HWP FW Owner         : Sangeetha T S <sangeet2@in.ibm.com>
// *HWP Team             : PM
// *HWP Level            : 2
// *HWP Consumed by      : HS

#ifndef _P9_PM_RESET_H
#define _P9_PM_RESET_H

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

// -----------------------------------------------------------------------------
// Includes
// -----------------------------------------------------------------------------
#include <fapi2.H>
#include <p9_pm.H>
#include <p9_pm_utils.H>
#include <p9_misc_scom_addresses.H>
#include <p9_pm_occ_firinit.H>
#include <p9_pm_firinit.H>
#include <p9_pm_occ_control.H>
#include <p9_pm_stop_gpe_init.H>
#include <p9_pm_occ_gpe_init.H>
#include <p9_pm_corequad_init.H>
#include <p9_pm_occ_sram_init.H>
#include <p9_pm_ocb_init.H>
#include <p9_pm_pss_init.H>

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

// -----------------------------------------------------------------------------
// Function Prototype
// -----------------------------------------------------------------------------
extern "C"
{
//------------------------------------------------------------------------------
///
/// @brief Call underlying unit procedures to reset PM complex
///
/// @param[in] i_target Proc Chip target
///
/// @return FAPI2_RC_SUCCESS on success, else error code.
///
    fapi2::ReturnCode p9_pm_reset(
        const fapi2::Target<fapi2::TARGET_TYPE_PROC_CHIP>& i_target);
}

#endif // _P9_PM_RESET_H
<|endoftext|>