<commit_before>//===- llvm/Support/DiagnosticInfo.cpp - Diagnostic Definitions -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the different classes involved in low level diagnostics.
//
// Diagnostics reporting is still done as part of the LLVMContext.
//===----------------------------------------------------------------------===//

#include "LLVMContextImpl.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Atomic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Regex.h"
#include <string>

using namespace llvm;

namespace {

/// \brief Regular expression corresponding to the value given in one of the
/// -pass-remarks* command line flags. Passes whose name matches this regexp
/// will emit a diagnostic when calling the associated diagnostic function
/// (emitOptimizationRemark, emitOptimizationRemarkMissed or
/// emitOptimizationRemarkAnalysis).
struct PassRemarksOpt {
  std::shared_ptr<Regex> Pattern;

  void operator=(const std::string &Val) {
    // Create a regexp object to match pass names for emitOptimizationRemark.
    if (!Val.empty()) {
      Pattern = std::make_shared<Regex>(Val);
      std::string RegexError;
      if (!Pattern->isValid(RegexError))
        report_fatal_error("Invalid regular expression '" + Val +
                               "' in -pass-remarks: " + RegexError,
                           false);
    }
  };
};

static PassRemarksOpt PassRemarksOptLoc;
static PassRemarksOpt PassRemarksMissedOptLoc;
static PassRemarksOpt PassRemarksAnalysisOptLoc;

// -pass-remarks
//    Command line flag to enable emitOptimizationRemark()
static cl::opt<PassRemarksOpt, true, cl::parser<std::string>>
PassRemarks("pass-remarks", cl::value_desc("pattern"),
            cl::desc("Enable optimization remarks from passes whose name match "
                     "the given regular expression"),
            cl::Hidden, cl::location(PassRemarksOptLoc), cl::ValueRequired,
            cl::ZeroOrMore);

// -pass-remarks-missed
//    Command line flag to enable emitOptimizationRemarkMissed()
static cl::opt<PassRemarksOpt, true, cl::parser<std::string>> PassRemarksMissed(
    "pass-remarks-missed", cl::value_desc("pattern"),
    cl::desc("Enable missed optimization remarks from passes whose name match "
             "the given regular expression"),
    cl::Hidden, cl::location(PassRemarksMissedOptLoc), cl::ValueRequired,
    cl::ZeroOrMore);

// -pass-remarks-analysis
//    Command line flag to enable emitOptimizationRemarkAnalysis()
static cl::opt<PassRemarksOpt, true, cl::parser<std::string>>
PassRemarksAnalysis(
    "pass-remarks-analysis", cl::value_desc("pattern"),
    cl::desc(
        "Enable optimization analysis remarks from passes whose name match "
        "the given regular expression"),
    cl::Hidden, cl::location(PassRemarksAnalysisOptLoc), cl::ValueRequired,
    cl::ZeroOrMore);
}

int llvm::getNextAvailablePluginDiagnosticKind() {
  static sys::cas_flag PluginKindID = DK_FirstPluginKind;
  return (int)sys::AtomicIncrement(&PluginKindID);
}

DiagnosticInfoInlineAsm::DiagnosticInfoInlineAsm(const Instruction &I,
                                                 const Twine &MsgStr,
                                                 DiagnosticSeverity Severity)
    : DiagnosticInfo(DK_InlineAsm, Severity), LocCookie(0), MsgStr(MsgStr),
      Instr(&I) {
  if (const MDNode *SrcLoc = I.getMetadata("srcloc")) {
    if (SrcLoc->getNumOperands() != 0)
      if (const ConstantInt *CI = dyn_cast<ConstantInt>(SrcLoc->getOperand(0)))
        LocCookie = CI->getZExtValue();
  }
}

void DiagnosticInfoInlineAsm::print(DiagnosticPrinter &DP) const {
  DP << getMsgStr();
  if (getLocCookie())
    DP << " at line " << getLocCookie();
}

void DiagnosticInfoStackSize::print(DiagnosticPrinter &DP) const {
  DP << "stack size limit exceeded (" << getStackSize() << ") in "
     << getFunction();
}

void DiagnosticInfoDebugMetadataVersion::print(DiagnosticPrinter &DP) const {
  DP << "ignoring debug info with an invalid version (" << getMetadataVersion()
     << ") in " << getModule();
}

void DiagnosticInfoSampleProfile::print(DiagnosticPrinter &DP) const {
  if (getFileName() && getLineNum() > 0)
    DP << getFileName() << ":" << getLineNum() << ": ";
  else if (getFileName())
    DP << getFileName() << ": ";
  DP << getMsg();
}

bool DiagnosticInfoOptimizationRemarkBase::isLocationAvailable() const {
  return getFunction().getParent()->getNamedMetadata("llvm.dbg.cu") != nullptr;
}

void DiagnosticInfoOptimizationRemarkBase::getLocation(StringRef *Filename,
                                                       unsigned *Line,
                                                       unsigned *Column) const {
  DILocation DIL(getDebugLoc().getAsMDNode(getFunction().getContext()));
  *Filename = DIL.getFilename();
  *Line = DIL.getLineNumber();
  *Column = DIL.getColumnNumber();
}

const std::string DiagnosticInfoOptimizationRemarkBase::getLocationStr() const {
  StringRef Filename("<unknown>");
  unsigned Line = 0;
  unsigned Column = 0;
  if (isLocationAvailable())
    getLocation(&Filename, &Line, &Column);
  return Twine(Filename + ":" + Twine(Line) + ":" + Twine(Column)).str();
}

void DiagnosticInfoOptimizationRemarkBase::print(DiagnosticPrinter &DP) const {
  DP << getLocationStr() << ": " << getMsg();
}

bool DiagnosticInfoOptimizationRemark::isEnabled() const {
  return PassRemarksOptLoc.Pattern &&
         PassRemarksOptLoc.Pattern->match(getPassName());
}

bool DiagnosticInfoOptimizationRemarkMissed::isEnabled() const {
  return PassRemarksMissedOptLoc.Pattern &&
         PassRemarksMissedOptLoc.Pattern->match(getPassName());
}

bool DiagnosticInfoOptimizationRemarkAnalysis::isEnabled() const {
  return PassRemarksAnalysisOptLoc.Pattern &&
         PassRemarksAnalysisOptLoc.Pattern->match(getPassName());
}

void llvm::emitOptimizationRemark(LLVMContext &Ctx, const char *PassName,
                                  const Function &Fn, const DebugLoc &DLoc,
                                  const Twine &Msg) {
  Ctx.diagnose(DiagnosticInfoOptimizationRemark(PassName, Fn, DLoc, Msg));
}

void llvm::emitOptimizationRemarkMissed(LLVMContext &Ctx, const char *PassName,
                                        const Function &Fn,
                                        const DebugLoc &DLoc,
                                        const Twine &Msg) {
  Ctx.diagnose(DiagnosticInfoOptimizationRemarkMissed(PassName, Fn, DLoc, Msg));
}

void llvm::emitOptimizationRemarkAnalysis(LLVMContext &Ctx,
                                          const char *PassName,
                                          const Function &Fn,
                                          const DebugLoc &DLoc,
                                          const Twine &Msg) {
  Ctx.diagnose(
      DiagnosticInfoOptimizationRemarkAnalysis(PassName, Fn, DLoc, Msg));
}
<commit_msg>Simply test for available locations in optimization remarks.<commit_after>//===- llvm/Support/DiagnosticInfo.cpp - Diagnostic Definitions -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the different classes involved in low level diagnostics.
//
// Diagnostics reporting is still done as part of the LLVMContext.
//===----------------------------------------------------------------------===//

#include "LLVMContextImpl.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Atomic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Regex.h"
#include <string>

using namespace llvm;

namespace {

/// \brief Regular expression corresponding to the value given in one of the
/// -pass-remarks* command line flags. Passes whose name matches this regexp
/// will emit a diagnostic when calling the associated diagnostic function
/// (emitOptimizationRemark, emitOptimizationRemarkMissed or
/// emitOptimizationRemarkAnalysis).
struct PassRemarksOpt {
  std::shared_ptr<Regex> Pattern;

  void operator=(const std::string &Val) {
    // Create a regexp object to match pass names for emitOptimizationRemark.
    if (!Val.empty()) {
      Pattern = std::make_shared<Regex>(Val);
      std::string RegexError;
      if (!Pattern->isValid(RegexError))
        report_fatal_error("Invalid regular expression '" + Val +
                               "' in -pass-remarks: " + RegexError,
                           false);
    }
  };
};

static PassRemarksOpt PassRemarksOptLoc;
static PassRemarksOpt PassRemarksMissedOptLoc;
static PassRemarksOpt PassRemarksAnalysisOptLoc;

// -pass-remarks
//    Command line flag to enable emitOptimizationRemark()
static cl::opt<PassRemarksOpt, true, cl::parser<std::string>>
PassRemarks("pass-remarks", cl::value_desc("pattern"),
            cl::desc("Enable optimization remarks from passes whose name match "
                     "the given regular expression"),
            cl::Hidden, cl::location(PassRemarksOptLoc), cl::ValueRequired,
            cl::ZeroOrMore);

// -pass-remarks-missed
//    Command line flag to enable emitOptimizationRemarkMissed()
static cl::opt<PassRemarksOpt, true, cl::parser<std::string>> PassRemarksMissed(
    "pass-remarks-missed", cl::value_desc("pattern"),
    cl::desc("Enable missed optimization remarks from passes whose name match "
             "the given regular expression"),
    cl::Hidden, cl::location(PassRemarksMissedOptLoc), cl::ValueRequired,
    cl::ZeroOrMore);

// -pass-remarks-analysis
//    Command line flag to enable emitOptimizationRemarkAnalysis()
static cl::opt<PassRemarksOpt, true, cl::parser<std::string>>
PassRemarksAnalysis(
    "pass-remarks-analysis", cl::value_desc("pattern"),
    cl::desc(
        "Enable optimization analysis remarks from passes whose name match "
        "the given regular expression"),
    cl::Hidden, cl::location(PassRemarksAnalysisOptLoc), cl::ValueRequired,
    cl::ZeroOrMore);
}

int llvm::getNextAvailablePluginDiagnosticKind() {
  static sys::cas_flag PluginKindID = DK_FirstPluginKind;
  return (int)sys::AtomicIncrement(&PluginKindID);
}

DiagnosticInfoInlineAsm::DiagnosticInfoInlineAsm(const Instruction &I,
                                                 const Twine &MsgStr,
                                                 DiagnosticSeverity Severity)
    : DiagnosticInfo(DK_InlineAsm, Severity), LocCookie(0), MsgStr(MsgStr),
      Instr(&I) {
  if (const MDNode *SrcLoc = I.getMetadata("srcloc")) {
    if (SrcLoc->getNumOperands() != 0)
      if (const ConstantInt *CI = dyn_cast<ConstantInt>(SrcLoc->getOperand(0)))
        LocCookie = CI->getZExtValue();
  }
}

void DiagnosticInfoInlineAsm::print(DiagnosticPrinter &DP) const {
  DP << getMsgStr();
  if (getLocCookie())
    DP << " at line " << getLocCookie();
}

void DiagnosticInfoStackSize::print(DiagnosticPrinter &DP) const {
  DP << "stack size limit exceeded (" << getStackSize() << ") in "
     << getFunction();
}

void DiagnosticInfoDebugMetadataVersion::print(DiagnosticPrinter &DP) const {
  DP << "ignoring debug info with an invalid version (" << getMetadataVersion()
     << ") in " << getModule();
}

void DiagnosticInfoSampleProfile::print(DiagnosticPrinter &DP) const {
  if (getFileName() && getLineNum() > 0)
    DP << getFileName() << ":" << getLineNum() << ": ";
  else if (getFileName())
    DP << getFileName() << ": ";
  DP << getMsg();
}

bool DiagnosticInfoOptimizationRemarkBase::isLocationAvailable() const {
  return getDebugLoc().isUnknown() == false;
}

void DiagnosticInfoOptimizationRemarkBase::getLocation(StringRef *Filename,
                                                       unsigned *Line,
                                                       unsigned *Column) const {
  DILocation DIL(getDebugLoc().getAsMDNode(getFunction().getContext()));
  *Filename = DIL.getFilename();
  *Line = DIL.getLineNumber();
  *Column = DIL.getColumnNumber();
}

const std::string DiagnosticInfoOptimizationRemarkBase::getLocationStr() const {
  StringRef Filename("<unknown>");
  unsigned Line = 0;
  unsigned Column = 0;
  if (isLocationAvailable())
    getLocation(&Filename, &Line, &Column);
  return Twine(Filename + ":" + Twine(Line) + ":" + Twine(Column)).str();
}

void DiagnosticInfoOptimizationRemarkBase::print(DiagnosticPrinter &DP) const {
  DP << getLocationStr() << ": " << getMsg();
}

bool DiagnosticInfoOptimizationRemark::isEnabled() const {
  return PassRemarksOptLoc.Pattern &&
         PassRemarksOptLoc.Pattern->match(getPassName());
}

bool DiagnosticInfoOptimizationRemarkMissed::isEnabled() const {
  return PassRemarksMissedOptLoc.Pattern &&
         PassRemarksMissedOptLoc.Pattern->match(getPassName());
}

bool DiagnosticInfoOptimizationRemarkAnalysis::isEnabled() const {
  return PassRemarksAnalysisOptLoc.Pattern &&
         PassRemarksAnalysisOptLoc.Pattern->match(getPassName());
}

void llvm::emitOptimizationRemark(LLVMContext &Ctx, const char *PassName,
                                  const Function &Fn, const DebugLoc &DLoc,
                                  const Twine &Msg) {
  Ctx.diagnose(DiagnosticInfoOptimizationRemark(PassName, Fn, DLoc, Msg));
}

void llvm::emitOptimizationRemarkMissed(LLVMContext &Ctx, const char *PassName,
                                        const Function &Fn,
                                        const DebugLoc &DLoc,
                                        const Twine &Msg) {
  Ctx.diagnose(DiagnosticInfoOptimizationRemarkMissed(PassName, Fn, DLoc, Msg));
}

void llvm::emitOptimizationRemarkAnalysis(LLVMContext &Ctx,
                                          const char *PassName,
                                          const Function &Fn,
                                          const DebugLoc &DLoc,
                                          const Twine &Msg) {
  Ctx.diagnose(
      DiagnosticInfoOptimizationRemarkAnalysis(PassName, Fn, DLoc, Msg));
}
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization
//
// 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 "scenepicker.h"

// appleseed.renderer headers.
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/intersection/intersector.h"
#include "renderer/kernel/intersection/tracecontext.h"
#include "renderer/kernel/shading/shadingray.h"
#include "renderer/kernel/texturing/texturecache.h"
#include "renderer/kernel/texturing/texturestore.h"
#include "renderer/modeling/bsdf/bsdftraits.h"
#include "renderer/modeling/bssrdf/bssrdftraits.h"
#include "renderer/modeling/camera/camera.h"
#include "renderer/modeling/edf/edftraits.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/input/inputbinder.h"
#include "renderer/modeling/material/material.h"
#include "renderer/modeling/material/materialtraits.h"
#include "renderer/modeling/project/project.h"
#include "renderer/modeling/scene/scene.h"
#include "renderer/modeling/surfaceshader/surfaceshadertraits.h"

// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/image.h"

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

using namespace foundation;

namespace renderer
{

struct ScenePicker::Impl
{
    const Project&      m_project;
    const TraceContext& m_trace_context;
    TextureStore        m_texture_store;
    TextureCache        m_texture_cache;
    Intersector         m_intersector;

    explicit Impl(const Project& project)
      : m_project(project)
      , m_trace_context(m_project.get_trace_context())
      , m_texture_store(m_trace_context.get_scene())
      , m_texture_cache(m_texture_store)
      , m_intersector(m_trace_context, m_texture_cache)
    {
    }
};

ScenePicker::ScenePicker(const Project& project)
  : impl(new Impl(project))
{
}

ScenePicker::~ScenePicker()
{
    delete impl;
}

ScenePicker::PickingResult ScenePicker::pick(const Vector2d& ndc) const
{
    PickingResult result;

    result.m_ndc = ndc;

    result.m_hit = false;
    result.m_primitive_type = ShadingPoint::PrimitiveNone;
    result.m_distance = std::numeric_limits<double>::max();

    result.m_bary = Vector2f(0.0);
    result.m_uv = Vector2f(0.0);
    result.m_duvdx = Vector2f(0.0);
    result.m_duvdy = Vector2f(0.0);
    result.m_point = Vector3d(0.0);
    result.m_dpdu = Vector3d(0.0);
    result.m_dpdv = Vector3d(0.0);
    result.m_dndu = Vector3d(0.0);
    result.m_dndv = Vector3d(0.0);
    result.m_dpdx = Vector3d(0.0);
    result.m_dpdy = Vector3d(0.0);
    result.m_geometric_normal = Vector3d(0.0);
    result.m_original_shading_normal = Vector3d(0.0);
    result.m_side = ObjectInstance::FrontSide;

    result.m_camera = impl->m_project.get_uncached_active_camera();
    result.m_assembly_instance = nullptr;
    result.m_assembly = nullptr;
    result.m_object_instance = nullptr;
    result.m_object = nullptr;
    result.m_material = nullptr;
    result.m_surface_shader = nullptr;
    result.m_bsdf = nullptr;
    result.m_bssrdf = nullptr;
    result.m_edf = nullptr;

    if (result.m_camera == nullptr)
        return result;

    SamplingContext::RNGType rng;
    SamplingContext sampling_context(rng, SamplingContext::QMCMode);

    const CanvasProperties& frame_props = impl->m_project.get_frame()->image().properties();
    const Vector2d ndc_dx(1.0 / (4.0 * frame_props.m_canvas_width), 0.0);
    const Vector2d ndc_dy(0.0, -1.0 / (4.0 * frame_props.m_canvas_height));

    ShadingRay ray;
    result.m_camera->spawn_ray(
        sampling_context,
        Dual2d(ndc, ndc_dx, ndc_dy),
        ray);

    ShadingPoint shading_point;
    impl->m_intersector.trace(ray, shading_point);

    result.m_hit = shading_point.hit_surface();

    if (!result.m_hit)
        return result;

    result.m_primitive_type = shading_point.get_primitive_type();
    result.m_distance = shading_point.get_distance() * norm(ray.m_dir);

    result.m_bary = shading_point.get_bary();
    result.m_uv = shading_point.get_uv(0);
    result.m_duvdx = shading_point.get_duvdx(0);
    result.m_duvdy = shading_point.get_duvdy(0);
    result.m_point = shading_point.get_point();
    result.m_dpdu = shading_point.get_dpdu(0);
    result.m_dpdv = shading_point.get_dpdv(0);
    result.m_dndu = shading_point.get_dndu(0);
    result.m_dndv = shading_point.get_dndv(0);
    result.m_dpdx = shading_point.get_dpdx();
    result.m_dpdy = shading_point.get_dpdy();
    result.m_geometric_normal = shading_point.get_geometric_normal();
    result.m_original_shading_normal = shading_point.get_original_shading_normal();
    result.m_side = shading_point.get_side();

    result.m_assembly_instance = &shading_point.get_assembly_instance();
    result.m_assembly_instance_transform = shading_point.get_assembly_instance_transform();
    result.m_assembly = &shading_point.get_assembly();
    result.m_object_instance = &shading_point.get_object_instance();
    result.m_object = &shading_point.get_object();

    const size_t pa_index = shading_point.get_primitive_attribute_index();

    if (pa_index != Triangle::None)
    {
        const char* material_name =
            result.m_object_instance->get_material_name(pa_index, shading_point.get_side());

        if (material_name)
        {
            result.m_material =
                InputBinder::static_find_entity<Material>(
                    material_name,
                    result.m_object_instance->get_parent());
        }
    }

    if (result.m_material)
    {
        const Entity* parent = result.m_material->get_parent();

        const char* ss_name = result.m_material->get_surface_shader_name();
        result.m_surface_shader = ss_name ? InputBinder::static_find_entity<SurfaceShader>(ss_name, parent) : nullptr;

        const char* bsdf_name = result.m_material->get_bsdf_name();
        result.m_bsdf = bsdf_name ? InputBinder::static_find_entity<BSDF>(bsdf_name, parent) : nullptr;

        const char* bssrdf_name = result.m_material->get_bssrdf_name();
        result.m_bssrdf = bssrdf_name ? InputBinder::static_find_entity<BSSRDF>(bssrdf_name, parent) : nullptr;

        const char* edf = result.m_material->get_edf_name();
        result.m_edf = edf ? InputBinder::static_find_entity<EDF>(edf, parent) : nullptr;
    }

    return result;
}

}   // namespace renderer
<commit_msg>Initialize asm. inst. transform to identity when picking on empty space<commit_after>
//
// This source file is part of appleseed.
// Visit https://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2018 Francois Beaune, The appleseedhq Organization
//
// 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 "scenepicker.h"

// appleseed.renderer headers.
#include "renderer/global/globaltypes.h"
#include "renderer/kernel/intersection/intersector.h"
#include "renderer/kernel/intersection/tracecontext.h"
#include "renderer/kernel/shading/shadingray.h"
#include "renderer/kernel/texturing/texturecache.h"
#include "renderer/kernel/texturing/texturestore.h"
#include "renderer/modeling/bsdf/bsdftraits.h"
#include "renderer/modeling/bssrdf/bssrdftraits.h"
#include "renderer/modeling/camera/camera.h"
#include "renderer/modeling/edf/edftraits.h"
#include "renderer/modeling/frame/frame.h"
#include "renderer/modeling/input/inputbinder.h"
#include "renderer/modeling/material/material.h"
#include "renderer/modeling/material/materialtraits.h"
#include "renderer/modeling/project/project.h"
#include "renderer/modeling/scene/scene.h"
#include "renderer/modeling/surfaceshader/surfaceshadertraits.h"

// appleseed.foundation headers.
#include "foundation/image/canvasproperties.h"
#include "foundation/image/image.h"

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

using namespace foundation;

namespace renderer
{

struct ScenePicker::Impl
{
    const Project&      m_project;
    const TraceContext& m_trace_context;
    TextureStore        m_texture_store;
    TextureCache        m_texture_cache;
    Intersector         m_intersector;

    explicit Impl(const Project& project)
      : m_project(project)
      , m_trace_context(m_project.get_trace_context())
      , m_texture_store(m_trace_context.get_scene())
      , m_texture_cache(m_texture_store)
      , m_intersector(m_trace_context, m_texture_cache)
    {
    }
};

ScenePicker::ScenePicker(const Project& project)
  : impl(new Impl(project))
{
}

ScenePicker::~ScenePicker()
{
    delete impl;
}

ScenePicker::PickingResult ScenePicker::pick(const Vector2d& ndc) const
{
    PickingResult result;

    result.m_ndc = ndc;

    result.m_hit = false;
    result.m_primitive_type = ShadingPoint::PrimitiveNone;
    result.m_distance = std::numeric_limits<double>::max();

    result.m_bary = Vector2f(0.0);
    result.m_uv = Vector2f(0.0);
    result.m_duvdx = Vector2f(0.0);
    result.m_duvdy = Vector2f(0.0);
    result.m_point = Vector3d(0.0);
    result.m_dpdu = Vector3d(0.0);
    result.m_dpdv = Vector3d(0.0);
    result.m_dndu = Vector3d(0.0);
    result.m_dndv = Vector3d(0.0);
    result.m_dpdx = Vector3d(0.0);
    result.m_dpdy = Vector3d(0.0);
    result.m_geometric_normal = Vector3d(0.0);
    result.m_original_shading_normal = Vector3d(0.0);
    result.m_side = ObjectInstance::FrontSide;

    result.m_camera = impl->m_project.get_uncached_active_camera();
    result.m_assembly_instance = nullptr;
    result.m_assembly_instance_transform = Transformd::make_identity();
    result.m_assembly = nullptr;
    result.m_object_instance = nullptr;
    result.m_object = nullptr;
    result.m_material = nullptr;
    result.m_surface_shader = nullptr;
    result.m_bsdf = nullptr;
    result.m_bssrdf = nullptr;
    result.m_edf = nullptr;

    if (result.m_camera == nullptr)
        return result;

    SamplingContext::RNGType rng;
    SamplingContext sampling_context(rng, SamplingContext::QMCMode);

    const CanvasProperties& frame_props = impl->m_project.get_frame()->image().properties();
    const Vector2d ndc_dx(1.0 / (4.0 * frame_props.m_canvas_width), 0.0);
    const Vector2d ndc_dy(0.0, -1.0 / (4.0 * frame_props.m_canvas_height));

    ShadingRay ray;
    result.m_camera->spawn_ray(
        sampling_context,
        Dual2d(ndc, ndc_dx, ndc_dy),
        ray);

    ShadingPoint shading_point;
    impl->m_intersector.trace(ray, shading_point);

    result.m_hit = shading_point.hit_surface();

    if (!result.m_hit)
        return result;

    result.m_primitive_type = shading_point.get_primitive_type();
    result.m_distance = shading_point.get_distance() * norm(ray.m_dir);

    result.m_bary = shading_point.get_bary();
    result.m_uv = shading_point.get_uv(0);
    result.m_duvdx = shading_point.get_duvdx(0);
    result.m_duvdy = shading_point.get_duvdy(0);
    result.m_point = shading_point.get_point();
    result.m_dpdu = shading_point.get_dpdu(0);
    result.m_dpdv = shading_point.get_dpdv(0);
    result.m_dndu = shading_point.get_dndu(0);
    result.m_dndv = shading_point.get_dndv(0);
    result.m_dpdx = shading_point.get_dpdx();
    result.m_dpdy = shading_point.get_dpdy();
    result.m_geometric_normal = shading_point.get_geometric_normal();
    result.m_original_shading_normal = shading_point.get_original_shading_normal();
    result.m_side = shading_point.get_side();

    result.m_assembly_instance = &shading_point.get_assembly_instance();
    result.m_assembly_instance_transform = shading_point.get_assembly_instance_transform();
    result.m_assembly = &shading_point.get_assembly();
    result.m_object_instance = &shading_point.get_object_instance();
    result.m_object = &shading_point.get_object();

    const size_t pa_index = shading_point.get_primitive_attribute_index();

    if (pa_index != Triangle::None)
    {
        const char* material_name =
            result.m_object_instance->get_material_name(pa_index, shading_point.get_side());

        if (material_name)
        {
            result.m_material =
                InputBinder::static_find_entity<Material>(
                    material_name,
                    result.m_object_instance->get_parent());
        }
    }

    if (result.m_material)
    {
        const Entity* parent = result.m_material->get_parent();

        const char* ss_name = result.m_material->get_surface_shader_name();
        result.m_surface_shader = ss_name ? InputBinder::static_find_entity<SurfaceShader>(ss_name, parent) : nullptr;

        const char* bsdf_name = result.m_material->get_bsdf_name();
        result.m_bsdf = bsdf_name ? InputBinder::static_find_entity<BSDF>(bsdf_name, parent) : nullptr;

        const char* bssrdf_name = result.m_material->get_bssrdf_name();
        result.m_bssrdf = bssrdf_name ? InputBinder::static_find_entity<BSSRDF>(bssrdf_name, parent) : nullptr;

        const char* edf = result.m_material->get_edf_name();
        result.m_edf = edf ? InputBinder::static_find_entity<EDF>(edf, parent) : nullptr;
    }

    return result;
}

}   // namespace renderer
<|endoftext|>


<commit_before>//===- llvm/Support/DiagnosticInfo.cpp - Diagnostic Definitions -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the different classes involved in low level diagnostics.
//
// Diagnostics reporting is still done as part of the LLVMContext.
//===----------------------------------------------------------------------===//

#include "LLVMContextImpl.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/Atomic.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Regex.h"
#include <string>

using namespace llvm;

namespace {

/// \brief Regular expression corresponding to the value given in one of the
/// -pass-remarks* command line flags. Passes whose name matches this regexp
/// will emit a diagnostic when calling the associated diagnostic function
/// (emitOptimizationRemark, emitOptimizationRemarkMissed or
/// emitOptimizationRemarkAnalysis).
struct PassRemarksOpt {
  std::shared_ptr<Regex> Pattern;

  void operator=(const std::string &Val) {
    // Create a regexp object to match pass names for emitOptimizationRemark.
    if (!Val.empty()) {
      Pattern = std::make_shared<Regex>(Val);
      std::string RegexError;
      if (!Pattern->isValid(RegexError))
        report_fatal_error("Invalid regular expression '" + Val +
                               "' in -pass-remarks: " + RegexError,
                           false);
    }
  };
};

static PassRemarksOpt PassRemarksOptLoc;
static PassRemarksOpt PassRemarksMissedOptLoc;
static PassRemarksOpt PassRemarksAnalysisOptLoc;

// -pass-remarks
//    Command line flag to enable emitOptimizationRemark()
static cl::opt<PassRemarksOpt, true, cl::parser<std::string>>
PassRemarks("pass-remarks", cl::value_desc("pattern"),
            cl::desc("Enable optimization remarks from passes whose name match "
                     "the given regular expression"),
            cl::Hidden, cl::location(PassRemarksOptLoc), cl::ValueRequired,
            cl::ZeroOrMore);

// -pass-remarks-missed
//    Command line flag to enable emitOptimizationRemarkMissed()
static cl::opt<PassRemarksOpt, true, cl::parser<std::string>> PassRemarksMissed(
    "pass-remarks-missed", cl::value_desc("pattern"),
    cl::desc("Enable missed optimization remarks from passes whose name match "
             "the given regular expression"),
    cl::Hidden, cl::location(PassRemarksMissedOptLoc), cl::ValueRequired,
    cl::ZeroOrMore);

// -pass-remarks-analysis
//    Command line flag to enable emitOptimizationRemarkAnalysis()
static cl::opt<PassRemarksOpt, true, cl::parser<std::string>>
PassRemarksAnalysis(
    "pass-remarks-analysis", cl::value_desc("pattern"),
    cl::desc(
        "Enable optimization analysis remarks from passes whose name match "
        "the given regular expression"),
    cl::Hidden, cl::location(PassRemarksAnalysisOptLoc), cl::ValueRequired,
    cl::ZeroOrMore);
}

int llvm::getNextAvailablePluginDiagnosticKind() {
  static sys::cas_flag PluginKindID = DK_FirstPluginKind;
  return (int)sys::AtomicIncrement(&PluginKindID);
}

DiagnosticInfoInlineAsm::DiagnosticInfoInlineAsm(const Instruction &I,
                                                 const Twine &MsgStr,
                                                 DiagnosticSeverity Severity)
    : DiagnosticInfo(DK_InlineAsm, Severity), LocCookie(0), MsgStr(MsgStr),
      Instr(&I) {
  if (const MDNode *SrcLoc = I.getMetadata("srcloc")) {
    if (SrcLoc->getNumOperands() != 0)
      if (const auto *CI =
              mdconst::dyn_extract<ConstantInt>(SrcLoc->getOperand(0)))
        LocCookie = CI->getZExtValue();
  }
}

void DiagnosticInfoInlineAsm::print(DiagnosticPrinter &DP) const {
  DP << getMsgStr();
  if (getLocCookie())
    DP << " at line " << getLocCookie();
}

void DiagnosticInfoStackSize::print(DiagnosticPrinter &DP) const {
  DP << "stack size limit exceeded (" << getStackSize() << ") in "
     << getFunction();
}

void DiagnosticInfoDebugMetadataVersion::print(DiagnosticPrinter &DP) const {
  DP << "ignoring debug info with an invalid version (" << getMetadataVersion()
     << ") in " << getModule();
}

void DiagnosticInfoSampleProfile::print(DiagnosticPrinter &DP) const {
  if (getFileName() && getLineNum() > 0)
    DP << getFileName() << ":" << getLineNum() << ": ";
  else if (getFileName())
    DP << getFileName() << ": ";
  DP << getMsg();
}

bool DiagnosticInfoOptimizationBase::isLocationAvailable() const {
  return getDebugLoc();
}

void DiagnosticInfoOptimizationBase::getLocation(StringRef *Filename,
                                                 unsigned *Line,
                                                 unsigned *Column) const {
  DILocation *L = getDebugLoc();
  assert(L != nullptr && "debug location is invalid");
  *Filename = L->getFilename();
  *Line = L->getLine();
  *Column = L->getColumn();
}

const std::string DiagnosticInfoOptimizationBase::getLocationStr() const {
  StringRef Filename("<unknown>");
  unsigned Line = 0;
  unsigned Column = 0;
  if (isLocationAvailable())
    getLocation(&Filename, &Line, &Column);
  return (Filename + ":" + Twine(Line) + ":" + Twine(Column)).str();
}

void DiagnosticInfoOptimizationBase::print(DiagnosticPrinter &DP) const {
  DP << getLocationStr() << ": " << getMsg();
}

bool DiagnosticInfoOptimizationRemark::isEnabled() const {
  return PassRemarksOptLoc.Pattern &&
         PassRemarksOptLoc.Pattern->match(getPassName());
}

bool DiagnosticInfoOptimizationRemarkMissed::isEnabled() const {
  return PassRemarksMissedOptLoc.Pattern &&
         PassRemarksMissedOptLoc.Pattern->match(getPassName());
}

bool DiagnosticInfoOptimizationRemarkAnalysis::isEnabled() const {
  return PassRemarksAnalysisOptLoc.Pattern &&
         PassRemarksAnalysisOptLoc.Pattern->match(getPassName());
}

void llvm::emitOptimizationRemark(LLVMContext &Ctx, const char *PassName,
                                  const Function &Fn, const DebugLoc &DLoc,
                                  const Twine &Msg) {
  Ctx.diagnose(DiagnosticInfoOptimizationRemark(PassName, Fn, DLoc, Msg));
}

void llvm::emitOptimizationRemarkMissed(LLVMContext &Ctx, const char *PassName,
                                        const Function &Fn,
                                        const DebugLoc &DLoc,
                                        const Twine &Msg) {
  Ctx.diagnose(DiagnosticInfoOptimizationRemarkMissed(PassName, Fn, DLoc, Msg));
}

void llvm::emitOptimizationRemarkAnalysis(LLVMContext &Ctx,
                                          const char *PassName,
                                          const Function &Fn,
                                          const DebugLoc &DLoc,
                                          const Twine &Msg) {
  Ctx.diagnose(
      DiagnosticInfoOptimizationRemarkAnalysis(PassName, Fn, DLoc, Msg));
}

bool DiagnosticInfoOptimizationFailure::isEnabled() const {
  // Only print warnings.
  return getSeverity() == DS_Warning;
}

void llvm::emitLoopVectorizeWarning(LLVMContext &Ctx, const Function &Fn,
                                    const DebugLoc &DLoc, const Twine &Msg) {
  Ctx.diagnose(DiagnosticInfoOptimizationFailure(
      Fn, DLoc, Twine("loop not vectorized: " + Msg)));
}

void llvm::emitLoopInterleaveWarning(LLVMContext &Ctx, const Function &Fn,
                                     const DebugLoc &DLoc, const Twine &Msg) {
  Ctx.diagnose(DiagnosticInfoOptimizationFailure(
      Fn, DLoc, Twine("loop not interleaved: " + Msg)));
}
<commit_msg>Replace an instance of custom atomics with standard ones.<commit_after>//===- llvm/Support/DiagnosticInfo.cpp - Diagnostic Definitions -*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// This file defines the different classes involved in low level diagnostics.
//
// Diagnostics reporting is still done as part of the LLVMContext.
//===----------------------------------------------------------------------===//

#include "LLVMContextImpl.h"
#include "llvm/ADT/Twine.h"
#include "llvm/IR/Constants.h"
#include "llvm/IR/DebugInfo.h"
#include "llvm/IR/DiagnosticInfo.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Regex.h"
#include <atomic>
#include <string>

using namespace llvm;

namespace {

/// \brief Regular expression corresponding to the value given in one of the
/// -pass-remarks* command line flags. Passes whose name matches this regexp
/// will emit a diagnostic when calling the associated diagnostic function
/// (emitOptimizationRemark, emitOptimizationRemarkMissed or
/// emitOptimizationRemarkAnalysis).
struct PassRemarksOpt {
  std::shared_ptr<Regex> Pattern;

  void operator=(const std::string &Val) {
    // Create a regexp object to match pass names for emitOptimizationRemark.
    if (!Val.empty()) {
      Pattern = std::make_shared<Regex>(Val);
      std::string RegexError;
      if (!Pattern->isValid(RegexError))
        report_fatal_error("Invalid regular expression '" + Val +
                               "' in -pass-remarks: " + RegexError,
                           false);
    }
  };
};

static PassRemarksOpt PassRemarksOptLoc;
static PassRemarksOpt PassRemarksMissedOptLoc;
static PassRemarksOpt PassRemarksAnalysisOptLoc;

// -pass-remarks
//    Command line flag to enable emitOptimizationRemark()
static cl::opt<PassRemarksOpt, true, cl::parser<std::string>>
PassRemarks("pass-remarks", cl::value_desc("pattern"),
            cl::desc("Enable optimization remarks from passes whose name match "
                     "the given regular expression"),
            cl::Hidden, cl::location(PassRemarksOptLoc), cl::ValueRequired,
            cl::ZeroOrMore);

// -pass-remarks-missed
//    Command line flag to enable emitOptimizationRemarkMissed()
static cl::opt<PassRemarksOpt, true, cl::parser<std::string>> PassRemarksMissed(
    "pass-remarks-missed", cl::value_desc("pattern"),
    cl::desc("Enable missed optimization remarks from passes whose name match "
             "the given regular expression"),
    cl::Hidden, cl::location(PassRemarksMissedOptLoc), cl::ValueRequired,
    cl::ZeroOrMore);

// -pass-remarks-analysis
//    Command line flag to enable emitOptimizationRemarkAnalysis()
static cl::opt<PassRemarksOpt, true, cl::parser<std::string>>
PassRemarksAnalysis(
    "pass-remarks-analysis", cl::value_desc("pattern"),
    cl::desc(
        "Enable optimization analysis remarks from passes whose name match "
        "the given regular expression"),
    cl::Hidden, cl::location(PassRemarksAnalysisOptLoc), cl::ValueRequired,
    cl::ZeroOrMore);
}

int llvm::getNextAvailablePluginDiagnosticKind() {
  static std::atomic<int> PluginKindID(DK_FirstPluginKind);
  return ++PluginKindID;
}

DiagnosticInfoInlineAsm::DiagnosticInfoInlineAsm(const Instruction &I,
                                                 const Twine &MsgStr,
                                                 DiagnosticSeverity Severity)
    : DiagnosticInfo(DK_InlineAsm, Severity), LocCookie(0), MsgStr(MsgStr),
      Instr(&I) {
  if (const MDNode *SrcLoc = I.getMetadata("srcloc")) {
    if (SrcLoc->getNumOperands() != 0)
      if (const auto *CI =
              mdconst::dyn_extract<ConstantInt>(SrcLoc->getOperand(0)))
        LocCookie = CI->getZExtValue();
  }
}

void DiagnosticInfoInlineAsm::print(DiagnosticPrinter &DP) const {
  DP << getMsgStr();
  if (getLocCookie())
    DP << " at line " << getLocCookie();
}

void DiagnosticInfoStackSize::print(DiagnosticPrinter &DP) const {
  DP << "stack size limit exceeded (" << getStackSize() << ") in "
     << getFunction();
}

void DiagnosticInfoDebugMetadataVersion::print(DiagnosticPrinter &DP) const {
  DP << "ignoring debug info with an invalid version (" << getMetadataVersion()
     << ") in " << getModule();
}

void DiagnosticInfoSampleProfile::print(DiagnosticPrinter &DP) const {
  if (getFileName() && getLineNum() > 0)
    DP << getFileName() << ":" << getLineNum() << ": ";
  else if (getFileName())
    DP << getFileName() << ": ";
  DP << getMsg();
}

bool DiagnosticInfoOptimizationBase::isLocationAvailable() const {
  return getDebugLoc();
}

void DiagnosticInfoOptimizationBase::getLocation(StringRef *Filename,
                                                 unsigned *Line,
                                                 unsigned *Column) const {
  DILocation *L = getDebugLoc();
  assert(L != nullptr && "debug location is invalid");
  *Filename = L->getFilename();
  *Line = L->getLine();
  *Column = L->getColumn();
}

const std::string DiagnosticInfoOptimizationBase::getLocationStr() const {
  StringRef Filename("<unknown>");
  unsigned Line = 0;
  unsigned Column = 0;
  if (isLocationAvailable())
    getLocation(&Filename, &Line, &Column);
  return (Filename + ":" + Twine(Line) + ":" + Twine(Column)).str();
}

void DiagnosticInfoOptimizationBase::print(DiagnosticPrinter &DP) const {
  DP << getLocationStr() << ": " << getMsg();
}

bool DiagnosticInfoOptimizationRemark::isEnabled() const {
  return PassRemarksOptLoc.Pattern &&
         PassRemarksOptLoc.Pattern->match(getPassName());
}

bool DiagnosticInfoOptimizationRemarkMissed::isEnabled() const {
  return PassRemarksMissedOptLoc.Pattern &&
         PassRemarksMissedOptLoc.Pattern->match(getPassName());
}

bool DiagnosticInfoOptimizationRemarkAnalysis::isEnabled() const {
  return PassRemarksAnalysisOptLoc.Pattern &&
         PassRemarksAnalysisOptLoc.Pattern->match(getPassName());
}

void llvm::emitOptimizationRemark(LLVMContext &Ctx, const char *PassName,
                                  const Function &Fn, const DebugLoc &DLoc,
                                  const Twine &Msg) {
  Ctx.diagnose(DiagnosticInfoOptimizationRemark(PassName, Fn, DLoc, Msg));
}

void llvm::emitOptimizationRemarkMissed(LLVMContext &Ctx, const char *PassName,
                                        const Function &Fn,
                                        const DebugLoc &DLoc,
                                        const Twine &Msg) {
  Ctx.diagnose(DiagnosticInfoOptimizationRemarkMissed(PassName, Fn, DLoc, Msg));
}

void llvm::emitOptimizationRemarkAnalysis(LLVMContext &Ctx,
                                          const char *PassName,
                                          const Function &Fn,
                                          const DebugLoc &DLoc,
                                          const Twine &Msg) {
  Ctx.diagnose(
      DiagnosticInfoOptimizationRemarkAnalysis(PassName, Fn, DLoc, Msg));
}

bool DiagnosticInfoOptimizationFailure::isEnabled() const {
  // Only print warnings.
  return getSeverity() == DS_Warning;
}

void llvm::emitLoopVectorizeWarning(LLVMContext &Ctx, const Function &Fn,
                                    const DebugLoc &DLoc, const Twine &Msg) {
  Ctx.diagnose(DiagnosticInfoOptimizationFailure(
      Fn, DLoc, Twine("loop not vectorized: " + Msg)));
}

void llvm::emitLoopInterleaveWarning(LLVMContext &Ctx, const Function &Fn,
                                     const DebugLoc &DLoc, const Twine &Msg) {
  Ctx.diagnose(DiagnosticInfoOptimizationFailure(
      Fn, DLoc, Twine("loop not interleaved: " + Msg)));
}
<|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qbluetoothlocaldevice_p.h"

#include "qbluetoothlocaldevice.h"
#include <QtCore/QString>
#include "symbian/utils_symbian_p.h"
#include <bttypes.h>
#include <bt_subscribe.h>
#ifdef USING_BTENGCONNMAN
#include "bluetoothsymbianpairingadapter.h"
#endif //USING_BTENGCONNMAN
#ifdef USING_BTENGDEVMAN
#include "bluetoothsymbianregistryadapter.h"
#endif //USING_BTENGDEVMAN

QTM_BEGIN_NAMESPACE

QBluetoothLocalDevicePrivate::QBluetoothLocalDevicePrivate()
    : m_settings(NULL)
{
    TRAPD(err, m_settings = CBTEngSettings::NewL(this));
    if (err != KErrNone) {
        Q_Q(QBluetoothLocalDevice);
        emit q->error(QBluetoothLocalDevice::UnknownError);
        m_settings = NULL;
    }
}

QBluetoothLocalDevicePrivate::~QBluetoothLocalDevicePrivate()
{
    delete m_settings;
}

QString QBluetoothLocalDevicePrivate::name()
{
    CBTEngSettings *settings = NULL;
    TRAPD(err, settings = CBTEngSettings::NewL());
    if (err != KErrNone)
        return QString();
    QString name = QString();
    HBufC *localName = NULL;
    TRAPD(error, localName = HBufC::NewL(256));
    if (error != KErrNone) {
        delete settings;
        return QString();
    }
    TPtr localPtr = localName->Des();
    TInt errorCode = settings->GetLocalName(localPtr);
    if (errorCode == KErrNone) {
        name = s60DescToQString(localPtr);
    }
    delete localName;
    delete settings;
    return name;
}

QBluetoothAddress QBluetoothLocalDevicePrivate::address()
{
    TBuf<20> bluetoothAddress;
    TPckgBuf<TBTDevAddr> addressPackage;

    TInt error = RProperty::Get(KUidSystemCategory, KPropertyKeyBluetoothGetLocalDeviceAddress, addressPackage);

    if (error != KErrNone)
        return QBluetoothAddress();

    addressPackage().GetReadable(bluetoothAddress, KNullDesC, _L(":"), KNullDesC);

    return QBluetoothAddress(s60DescToQString(bluetoothAddress));
}

void QBluetoothLocalDevicePrivate::powerOn()
{
    if (!m_settings)
        return;
    TBTPowerStateValue powerState;
    TInt error = m_settings->GetPowerState(powerState);
    if (error == KErrNone && powerState == EBTPowerOff)
        m_settings->SetPowerState(EBTPowerOn);
    else if (error != KErrNone) {
        Q_Q(QBluetoothLocalDevice);
        emit q->error(QBluetoothLocalDevice::UnknownError);
    }
}
void QBluetoothLocalDevicePrivate::powerOff()
{
    if (!m_settings)
        return;
    TBTPowerStateValue powerState;
    TInt error = m_settings->GetPowerState(powerState);
    if (error == KErrNone && powerState == EBTPowerOn)
        m_settings->SetPowerState(EBTPowerOff);
    else if (error != KErrNone) {
        Q_Q(QBluetoothLocalDevice);
        emit q->error(QBluetoothLocalDevice::UnknownError);
    }
}
void QBluetoothLocalDevicePrivate::setHostMode(QBluetoothLocalDevice::HostMode mode)
{
    if (!m_settings)
        return;

    TInt error = KErrNone;
    switch (mode) {
        case QBluetoothLocalDevice::HostPoweredOff:
            powerOff();
            break;
        case QBluetoothLocalDevice::HostConnectable: {
            TBTPowerStateValue powerState;
            error = m_settings->GetPowerState(powerState);
            if (error == KErrNone) {
                if (powerState == EBTPowerOff) {
                    error = m_settings->SetPowerState(EBTPowerOn);
                }
                TBTVisibilityMode visibilityMode;
                error = m_settings->GetVisibilityMode(visibilityMode);
                if (visibilityMode != EBTVisibilityModeHidden) {
                    error = m_settings->SetVisibilityMode(EBTVisibilityModeHidden);
                }
            }
            break;
        }
        case QBluetoothLocalDevice::HostDiscoverable: {
            TBTPowerStateValue powerState;
            error = m_settings->GetPowerState(powerState);
            if (error == KErrNone) {
                if (powerState == EBTPowerOff) {
                    error = m_settings->SetPowerState(EBTPowerOn);
                }
                TBTVisibilityMode visibilityMode;
                error = m_settings->GetVisibilityMode(visibilityMode);
                if (visibilityMode != EBTVisibilityModeGeneral) {
                    error = m_settings->SetVisibilityMode(EBTVisibilityModeGeneral);
                }
            }
            break;
        }
    }
    if (error != KErrNone) {
        Q_Q(QBluetoothLocalDevice);
        emit q->error(QBluetoothLocalDevice::UnknownError);
    }
}

QBluetoothLocalDevice::HostMode QBluetoothLocalDevicePrivate::hostMode() const
{
    if (!m_settings)
        return QBluetoothLocalDevice::HostPoweredOff;

    TBTVisibilityMode visibilityMode;
    TInt error = m_settings->GetVisibilityMode(visibilityMode);

    if (error != KErrNone)
        return QBluetoothLocalDevice::HostPoweredOff;

    //If we are powered off then we don't are neither connectable or discoverable
    TBTPowerStateValue powerState;
    error = m_settings->GetPowerState(powerState);
    if (error == KErrNone && powerState == EBTPowerOff)
        return QBluetoothLocalDevice::HostPoweredOff;

    switch (visibilityMode) {
        case EBTVisibilityModeHidden:
            return QBluetoothLocalDevice::HostConnectable;
        case EBTVisibilityModeGeneral:
        case EBTVisibilityModeTemporary:
            return QBluetoothLocalDevice::HostDiscoverable;
        default:
            // default value, also includes these new values from Symbian^3 onwards
            // case EBTVisibilityModeNoScans:
            // case EBTVisibilityModeInquiryScanOnly:
            return QBluetoothLocalDevice::HostPoweredOff;
    }
}

void QBluetoothLocalDevicePrivate::PowerStateChanged(TBTPowerStateValue aState)
{
    QBluetoothLocalDevice::HostMode hostMode;
    switch (aState) {
        case EBTPowerOn:
            hostMode = this->hostMode();
            break;
        case EBTPowerOff:
        default:
            hostMode = QBluetoothLocalDevice::HostPoweredOff;
            break;
    }
    Q_Q(QBluetoothLocalDevice);
    emit q->hostModeStateChanged(hostMode);
}

void QBluetoothLocalDevicePrivate::VisibilityModeChanged(TBTVisibilityMode aState)
{
    QBluetoothLocalDevice::HostMode hostMode;
    switch (aState) {
        case EBTVisibilityModeHidden:
            hostMode = QBluetoothLocalDevice::HostConnectable;
            break;
        case EBTVisibilityModeGeneral:
        case EBTVisibilityModeTemporary:
            hostMode = QBluetoothLocalDevice::HostDiscoverable;
            break;
        default:
            // default value, also includes these new values from Symbian^3 onwards
            // case EBTVisibilityModeNoScans:
            // case EBTVisibilityModeInquiryScanOnly:
            hostMode = QBluetoothLocalDevice::HostPoweredOff;
            break;
    }
    Q_Q(QBluetoothLocalDevice);
    emit q->hostModeStateChanged(hostMode);
}

void QBluetoothLocalDevicePrivate::requestPairing(const QBluetoothAddress &address, QBluetoothLocalDevice::Pairing pairing)
{
//#ifdef USING_BTENGCONNMAN
#ifdef USING_BTENGDEVMAN
    Q_Q(QBluetoothLocalDevice);

    BluetoothSymbianRegistryAdapter *registryAdapter = new BluetoothSymbianRegistryAdapter(address,q);
    // do nothing if everything is uptodate.
    if (registryAdapter->pairingStatus() == pairing) {
        _q_pairingFinished(address, pairing);
        return;
    }
    // pass q pointer so that adapter gets deleted when q object is deleted. Not optimal though.
    BluetoothSymbianPairingAdapter *pairingAdapter = new BluetoothSymbianPairingAdapter(address,q);

    // After pairing has completed we emit pairingFinished signal in every case.
    // earlier we checked pairing status from Symbian Bluetooth registry at this point but it
    // was not updated and the result was that we emitted wrong pairing status.
    QObject::connect(pairingAdapter, SIGNAL(pairingFinished(const QBluetoothAddress&,QBluetoothLocalDevice::Pairing)),
        q, SLOT(_q_pairingFinished(const QBluetoothAddress&,QBluetoothLocalDevice::Pairing)));
    // if pairing status changes then emit pairing finished.
    // Currently this is used after removing a paired device from Symbian Bluetooth registry
    QObject::connect(registryAdapter, SIGNAL(pairingStatusChanged(const QBluetoothAddress&,QBluetoothLocalDevice::Pairing)),
        q, SLOT(_q_pairingFinished(const QBluetoothAddress&,QBluetoothLocalDevice::Pairing)));

    switch (pairing) {
    case QBluetoothLocalDevice::Unpaired:
        // this is async method
        registryAdapter->removePairing();
        break;
    case QBluetoothLocalDevice::Paired:
    case QBluetoothLocalDevice::AuthorizedPaired:
        // this is async method
        // TODO: check whether paring succeed
        pairingAdapter->startPairing(pairing);
        break;
    default:
        ASSERT(0);
        break;
    }
#endif //USING_BTENGDEVMAN
//#endif USING_BTENGCONNMAN
}

QBluetoothLocalDevice::Pairing QBluetoothLocalDevicePrivate::pairingStatus(const QBluetoothAddress &address) const
{
#ifdef USING_BTENGDEVMAN
    QScopedPointer<BluetoothSymbianRegistryAdapter> registryAdapter (new BluetoothSymbianRegistryAdapter(address));
    return registryAdapter->pairingStatus();
#endif //USING_BTENGDEVMAN
}

void QBluetoothLocalDevicePrivate::pairingConfirmation(bool confirmation)
{
}

void QBluetoothLocalDevicePrivate::_q_pairingFinished(const QBluetoothAddress &address,QBluetoothLocalDevice::Pairing pairing)
{
    Q_Q(QBluetoothLocalDevice);
    emit q->pairingFinished(address, pairing);
}

QBluetoothLocalDevice::QBluetoothLocalDevice(QObject *parent)
:   QObject(parent), d_ptr(new QBluetoothLocalDevicePrivate())
{
    d_ptr->q_ptr = this;
    if (this->d_ptr->m_settings == NULL) {
        delete this->d_ptr;
        this->d_ptr = NULL;
    }
}

QBluetoothLocalDevice::QBluetoothLocalDevice(const QBluetoothAddress &address, QObject *parent)
: QObject(parent), d_ptr(new QBluetoothLocalDevicePrivate())
{
    d_ptr->q_ptr = this;
    if (this->d_ptr->m_settings == NULL || address != this->d_ptr->address()) {
        delete this->d_ptr;
        this->d_ptr = NULL;
    }
}

QString QBluetoothLocalDevice::name() const
{
    if (!d_ptr)
        return QString();
    return d_ptr->name();
}

QBluetoothAddress QBluetoothLocalDevice::address() const
{
    if (!d_ptr)
        return QBluetoothAddress();
    return d_ptr->address();
}

void QBluetoothLocalDevice::powerOn()
{
    if (!d_ptr)
        return;
    d_ptr->powerOn();
}

void QBluetoothLocalDevice::setHostMode(QBluetoothLocalDevice::HostMode mode)
{
    if (!d_ptr)
        return;
    d_ptr->setHostMode(mode);
}

QBluetoothLocalDevice::HostMode QBluetoothLocalDevice::hostMode() const
{
    if (!d_ptr)
        return HostPoweredOff;
    return d_ptr->hostMode();
}

QList<QBluetoothHostInfo> QBluetoothLocalDevice::allDevices()
{
    QList<QBluetoothHostInfo> localDevices;
    QBluetoothHostInfo hostInfo;
    hostInfo.setName(QBluetoothLocalDevicePrivate::name());
    hostInfo.setAddress(QBluetoothLocalDevicePrivate::address());
    localDevices.append(hostInfo);
    return localDevices;
}

void QBluetoothLocalDevice::requestPairing(const QBluetoothAddress &address, Pairing pairing)
{
    if (!d_ptr)
        return;

    return d_ptr->requestPairing(address, pairing);
}

QBluetoothLocalDevice::Pairing QBluetoothLocalDevice::pairingStatus(const QBluetoothAddress &address) const
{
    if (!d_ptr)
        return QBluetoothLocalDevice::Unpaired;

    return d_ptr->pairingStatus(address);
}

void QBluetoothLocalDevice::pairingConfirmation(bool confirmation)
{
    if (!d_ptr)
        return;

    return d_ptr->pairingConfirmation(confirmation);
}

QTM_END_NAMESPACE
<commit_msg>remove whitespace from qbluetoothlocaldevice_symbian.cpp<commit_after>/****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the Qt Mobility Components.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "qbluetoothlocaldevice_p.h"

#include "qbluetoothlocaldevice.h"
#include <QtCore/QString>
#include "symbian/utils_symbian_p.h"
#include <bttypes.h>
#include <bt_subscribe.h>
#ifdef USING_BTENGCONNMAN
#include "bluetoothsymbianpairingadapter.h"
#endif //USING_BTENGCONNMAN
#ifdef USING_BTENGDEVMAN
#include "bluetoothsymbianregistryadapter.h"
#endif //USING_BTENGDEVMAN

QTM_BEGIN_NAMESPACE

QBluetoothLocalDevicePrivate::QBluetoothLocalDevicePrivate()
    : m_settings(NULL)
{
    TRAPD(err, m_settings = CBTEngSettings::NewL(this));
    if (err != KErrNone) {
        Q_Q(QBluetoothLocalDevice);
        emit q->error(QBluetoothLocalDevice::UnknownError);
        m_settings = NULL;
    }
}

QBluetoothLocalDevicePrivate::~QBluetoothLocalDevicePrivate()
{
    delete m_settings;
}

QString QBluetoothLocalDevicePrivate::name()
{
    CBTEngSettings *settings = NULL;
    TRAPD(err, settings = CBTEngSettings::NewL());
    if (err != KErrNone)
        return QString();
    QString name = QString();
    HBufC *localName = NULL;
    TRAPD(error, localName = HBufC::NewL(256));
    if (error != KErrNone) {
        delete settings;
        return QString();
    }
    TPtr localPtr = localName->Des();
    TInt errorCode = settings->GetLocalName(localPtr);
    if (errorCode == KErrNone) {
        name = s60DescToQString(localPtr);
    }
    delete localName;
    delete settings;
    return name;
}

QBluetoothAddress QBluetoothLocalDevicePrivate::address()
{
    TBuf<20> bluetoothAddress;
    TPckgBuf<TBTDevAddr> addressPackage;

    TInt error = RProperty::Get(KUidSystemCategory, KPropertyKeyBluetoothGetLocalDeviceAddress, addressPackage);

    if (error != KErrNone)
        return QBluetoothAddress();

    addressPackage().GetReadable(bluetoothAddress, KNullDesC, _L(":"), KNullDesC);

    return QBluetoothAddress(s60DescToQString(bluetoothAddress));
}

void QBluetoothLocalDevicePrivate::powerOn()
{
    if (!m_settings)
        return;
    TBTPowerStateValue powerState;
    TInt error = m_settings->GetPowerState(powerState);
    if (error == KErrNone && powerState == EBTPowerOff)
        m_settings->SetPowerState(EBTPowerOn);
    else if (error != KErrNone) {
        Q_Q(QBluetoothLocalDevice);
        emit q->error(QBluetoothLocalDevice::UnknownError);
    }
}
void QBluetoothLocalDevicePrivate::powerOff()
{
    if (!m_settings)
        return;
    TBTPowerStateValue powerState;
    TInt error = m_settings->GetPowerState(powerState);
    if (error == KErrNone && powerState == EBTPowerOn)
        m_settings->SetPowerState(EBTPowerOff);
    else if (error != KErrNone) {
        Q_Q(QBluetoothLocalDevice);
        emit q->error(QBluetoothLocalDevice::UnknownError);
    }
}
void QBluetoothLocalDevicePrivate::setHostMode(QBluetoothLocalDevice::HostMode mode)
{
    if (!m_settings)
        return;

    TInt error = KErrNone;
    switch (mode) {
        case QBluetoothLocalDevice::HostPoweredOff:
            powerOff();
            break;
        case QBluetoothLocalDevice::HostConnectable: {
            TBTPowerStateValue powerState;
            error = m_settings->GetPowerState(powerState);
            if (error == KErrNone) {
                if (powerState == EBTPowerOff) {
                    error = m_settings->SetPowerState(EBTPowerOn);
                }
                TBTVisibilityMode visibilityMode;
                error = m_settings->GetVisibilityMode(visibilityMode);
                if (visibilityMode != EBTVisibilityModeHidden) {
                    error = m_settings->SetVisibilityMode(EBTVisibilityModeHidden);
                }
            }
            break;
        }
        case QBluetoothLocalDevice::HostDiscoverable: {
            TBTPowerStateValue powerState;
            error = m_settings->GetPowerState(powerState);
            if (error == KErrNone) {
                if (powerState == EBTPowerOff) {
                    error = m_settings->SetPowerState(EBTPowerOn);
                }
                TBTVisibilityMode visibilityMode;
                error = m_settings->GetVisibilityMode(visibilityMode);
                if (visibilityMode != EBTVisibilityModeGeneral) {
                    error = m_settings->SetVisibilityMode(EBTVisibilityModeGeneral);
                }
            }
            break;
        }
    }
    if (error != KErrNone) {
        Q_Q(QBluetoothLocalDevice);
        emit q->error(QBluetoothLocalDevice::UnknownError);
    }
}

QBluetoothLocalDevice::HostMode QBluetoothLocalDevicePrivate::hostMode() const
{
    if (!m_settings)
        return QBluetoothLocalDevice::HostPoweredOff;

    TBTVisibilityMode visibilityMode;
    TInt error = m_settings->GetVisibilityMode(visibilityMode);

    if (error != KErrNone)
        return QBluetoothLocalDevice::HostPoweredOff;

    //If we are powered off then we don't are neither connectable or discoverable
    TBTPowerStateValue powerState;
    error = m_settings->GetPowerState(powerState);
    if (error == KErrNone && powerState == EBTPowerOff)
        return QBluetoothLocalDevice::HostPoweredOff;

    switch (visibilityMode) {
        case EBTVisibilityModeHidden:
            return QBluetoothLocalDevice::HostConnectable;
        case EBTVisibilityModeGeneral:
        case EBTVisibilityModeTemporary:
            return QBluetoothLocalDevice::HostDiscoverable;
        default:
            // default value, also includes these new values from Symbian^3 onwards
            // case EBTVisibilityModeNoScans:
            // case EBTVisibilityModeInquiryScanOnly:
            return QBluetoothLocalDevice::HostPoweredOff;
    }
}

void QBluetoothLocalDevicePrivate::PowerStateChanged(TBTPowerStateValue aState)
{
    QBluetoothLocalDevice::HostMode hostMode;
    switch (aState) {
        case EBTPowerOn:
            hostMode = this->hostMode();
            break;
        case EBTPowerOff:
        default:
            hostMode = QBluetoothLocalDevice::HostPoweredOff;
            break;
    }
    Q_Q(QBluetoothLocalDevice);
    emit q->hostModeStateChanged(hostMode);
}

void QBluetoothLocalDevicePrivate::VisibilityModeChanged(TBTVisibilityMode aState)
{
    QBluetoothLocalDevice::HostMode hostMode;
    switch (aState) {
        case EBTVisibilityModeHidden:
            hostMode = QBluetoothLocalDevice::HostConnectable;
            break;
        case EBTVisibilityModeGeneral:
        case EBTVisibilityModeTemporary:
            hostMode = QBluetoothLocalDevice::HostDiscoverable;
            break;
        default:
            // default value, also includes these new values from Symbian^3 onwards
            // case EBTVisibilityModeNoScans:
            // case EBTVisibilityModeInquiryScanOnly:
            hostMode = QBluetoothLocalDevice::HostPoweredOff;
            break;
    }
    Q_Q(QBluetoothLocalDevice);
    emit q->hostModeStateChanged(hostMode);
}

void QBluetoothLocalDevicePrivate::requestPairing(const QBluetoothAddress &address, QBluetoothLocalDevice::Pairing pairing)
{
//#ifdef USING_BTENGCONNMAN
#ifdef USING_BTENGDEVMAN
    Q_Q(QBluetoothLocalDevice);

    BluetoothSymbianRegistryAdapter *registryAdapter = new BluetoothSymbianRegistryAdapter(address,q);
    // do nothing if everything is uptodate.
    if (registryAdapter->pairingStatus() == pairing) {
        _q_pairingFinished(address, pairing);
        return;
    }
    // pass q pointer so that adapter gets deleted when q object is deleted. Not optimal though.
    BluetoothSymbianPairingAdapter *pairingAdapter = new BluetoothSymbianPairingAdapter(address,q);

    // After pairing has completed we emit pairingFinished signal in every case.
    // earlier we checked pairing status from Symbian Bluetooth registry at this point but it
    // was not updated and the result was that we emitted wrong pairing status.
    QObject::connect(pairingAdapter, SIGNAL(pairingFinished(const QBluetoothAddress&,QBluetoothLocalDevice::Pairing)),
        q, SLOT(_q_pairingFinished(const QBluetoothAddress&,QBluetoothLocalDevice::Pairing)));
    // if pairing status changes then emit pairing finished.
    // Currently this is used after removing a paired device from Symbian Bluetooth registry
    QObject::connect(registryAdapter, SIGNAL(pairingStatusChanged(const QBluetoothAddress&,QBluetoothLocalDevice::Pairing)),
        q, SLOT(_q_pairingFinished(const QBluetoothAddress&,QBluetoothLocalDevice::Pairing)));

    switch (pairing) {
    case QBluetoothLocalDevice::Unpaired:
        // this is async method
        registryAdapter->removePairing();
        break;
    case QBluetoothLocalDevice::Paired:
    case QBluetoothLocalDevice::AuthorizedPaired:
        // this is async method
        // TODO: check whether paring succeed
        pairingAdapter->startPairing(pairing);
        break;
    default:
        ASSERT(0);
        break;
    }
#endif //USING_BTENGDEVMAN
//#endif USING_BTENGCONNMAN
}

QBluetoothLocalDevice::Pairing QBluetoothLocalDevicePrivate::pairingStatus(const QBluetoothAddress &address) const
{
#ifdef USING_BTENGDEVMAN
    QScopedPointer<BluetoothSymbianRegistryAdapter> registryAdapter (new BluetoothSymbianRegistryAdapter(address));
    return registryAdapter->pairingStatus();
#endif //USING_BTENGDEVMAN
}

void QBluetoothLocalDevicePrivate::pairingConfirmation(bool confirmation)
{
}

void QBluetoothLocalDevicePrivate::_q_pairingFinished(const QBluetoothAddress &address,QBluetoothLocalDevice::Pairing pairing)
{
    Q_Q(QBluetoothLocalDevice);
    emit q->pairingFinished(address, pairing);
}

QBluetoothLocalDevice::QBluetoothLocalDevice(QObject *parent)
:   QObject(parent), d_ptr(new QBluetoothLocalDevicePrivate())
{
    d_ptr->q_ptr = this;
    if (this->d_ptr->m_settings == NULL) {
        delete this->d_ptr;
        this->d_ptr = NULL;
    }
}

QBluetoothLocalDevice::QBluetoothLocalDevice(const QBluetoothAddress &address, QObject *parent)
: QObject(parent), d_ptr(new QBluetoothLocalDevicePrivate())
{
    d_ptr->q_ptr = this;
    if (this->d_ptr->m_settings == NULL || address != this->d_ptr->address()) {
        delete this->d_ptr;
        this->d_ptr = NULL;
    }
}

QString QBluetoothLocalDevice::name() const
{
    if (!d_ptr)
        return QString();
    return d_ptr->name();
}

QBluetoothAddress QBluetoothLocalDevice::address() const
{
    if (!d_ptr)
        return QBluetoothAddress();
    return d_ptr->address();
}

void QBluetoothLocalDevice::powerOn()
{
    if (!d_ptr)
        return;
    d_ptr->powerOn();
}

void QBluetoothLocalDevice::setHostMode(QBluetoothLocalDevice::HostMode mode)
{
    if (!d_ptr)
        return;
    d_ptr->setHostMode(mode);
}

QBluetoothLocalDevice::HostMode QBluetoothLocalDevice::hostMode() const
{
    if (!d_ptr)
        return HostPoweredOff;
    return d_ptr->hostMode();
}

QList<QBluetoothHostInfo> QBluetoothLocalDevice::allDevices()
{
    QList<QBluetoothHostInfo> localDevices;
    QBluetoothHostInfo hostInfo;
    hostInfo.setName(QBluetoothLocalDevicePrivate::name());
    hostInfo.setAddress(QBluetoothLocalDevicePrivate::address());
    localDevices.append(hostInfo);
    return localDevices;
}

void QBluetoothLocalDevice::requestPairing(const QBluetoothAddress &address, Pairing pairing)
{
    if (!d_ptr)
        return;

    return d_ptr->requestPairing(address, pairing);
}

QBluetoothLocalDevice::Pairing QBluetoothLocalDevice::pairingStatus(const QBluetoothAddress &address) const
{
    if (!d_ptr)
        return QBluetoothLocalDevice::Unpaired;

    return d_ptr->pairingStatus(address);
}

void QBluetoothLocalDevice::pairingConfirmation(bool confirmation)
{
    if (!d_ptr)
        return;

    return d_ptr->pairingConfirmation(confirmation);
}

QTM_END_NAMESPACE
<|endoftext|>


<commit_before>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   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.
*/

#include <Dataflow/Engine/Controller/DynamicPortManager.h>
#include <Dataflow/Network/NetworkInterface.h>
#include <Dataflow/Network/Module.h>
#include <Dataflow/Network/ConnectionId.h>

using namespace SCIRun;
using namespace SCIRun::Dataflow::Engine;
using namespace SCIRun::Dataflow::Networks;

DynamicPortManager::DynamicPortManager(ConnectionAddedSignalType& addedSignal, ConnectionRemovedSignalType& removeSignal, const NetworkEditorController* controller) : controller_(controller), enabled_(true)
{
  ENSURE_NOT_NULL(controller, "DPM needs network controller object");
  addedSignal.connect(boost::bind(&DynamicPortManager::connectionAddedNeedToCloneAPort, this, _1));
  removeSignal.connect(boost::bind(&DynamicPortManager::connectionRemovedNeedToRemoveAPort, this, _1));
}

void DynamicPortManager::connectionAddedNeedToCloneAPort(const SCIRun::Dataflow::Networks::ConnectionDescription& cd)
{
  if (enabled_)
  {
    //std::cout << "need to clone a port: " << ConnectionId::create(cd).id_ << std::endl;
    //TODO: assumption: dynamic = input
    auto moduleIn = controller_->getNetwork()->lookupModule(cd.in_.moduleId_);
    if (moduleIn->get_input_port(cd.in_.port_)->isDynamic())
    {
      Module::Builder builder;
      builder.cloneInputPort(moduleIn, cd.in_.port_);
      portAdded_(moduleIn->get_id(), cd.in_.port_);
    }
  }
}

void DynamicPortManager::connectionRemovedNeedToRemoveAPort(const SCIRun::Dataflow::Networks::ConnectionId& id)
{
  if (enabled_)
  {
    //std::cout << "need to remove a port: " << id.id_ << std::endl;
    auto desc = id.describe();
    auto moduleIn = controller_->getNetwork()->lookupModule(desc.in_.moduleId_);
    if (moduleIn->get_input_port(desc.in_.port_)->isDynamic())
    {
      Module::Builder builder;
      builder.removeInputPort(moduleIn, desc.in_.port_);
      portRemoved_(moduleIn->get_id(), desc.in_.port_);
    }
  }
}

boost::signals2::connection DynamicPortManager::connectPortAdded(const PortAddedSignalType::slot_type& subscriber)
{
  return portAdded_.connect(subscriber);
}

boost::signals2::connection DynamicPortManager::connectPortRemoved(const PortRemovedSignalType::slot_type& subscriber)
{
  return portRemoved_.connect(subscriber);
}

void DynamicPortManager::enable()
{
  enabled_ = true;
}

void DynamicPortManager::disable()
{
  enabled_ = false;
}<commit_msg>Don't think this is needed; disable<commit_after>/*
   For more information, please see: http://software.sci.utah.edu

   The MIT License

   Copyright (c) 2012 Scientific Computing and Imaging Institute,
   University of Utah.

   License for the specific language governing rights and limitations under
   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.
*/

#include <Dataflow/Engine/Controller/DynamicPortManager.h>
#include <Dataflow/Network/NetworkInterface.h>
#include <Dataflow/Network/Module.h>
#include <Dataflow/Network/ConnectionId.h>

using namespace SCIRun;
using namespace SCIRun::Dataflow::Engine;
using namespace SCIRun::Dataflow::Networks;

DynamicPortManager::DynamicPortManager(ConnectionAddedSignalType& addedSignal, ConnectionRemovedSignalType& removeSignal, const NetworkEditorController* controller) : controller_(controller), enabled_(true)
{
  ENSURE_NOT_NULL(controller, "DPM needs network controller object");
  addedSignal.connect(boost::bind(&DynamicPortManager::connectionAddedNeedToCloneAPort, this, _1));
  removeSignal.connect(boost::bind(&DynamicPortManager::connectionRemovedNeedToRemoveAPort, this, _1));
}

void DynamicPortManager::connectionAddedNeedToCloneAPort(const SCIRun::Dataflow::Networks::ConnectionDescription& cd)
{
  if (enabled_)
  {
    //std::cout << "need to clone a port: " << ConnectionId::create(cd).id_ << std::endl;
    //TODO: assumption: dynamic = input
    auto moduleIn = controller_->getNetwork()->lookupModule(cd.in_.moduleId_);
    if (moduleIn->get_input_port(cd.in_.port_)->isDynamic())
    {
      Module::Builder builder;
      builder.cloneInputPort(moduleIn, cd.in_.port_);
      portAdded_(moduleIn->get_id(), cd.in_.port_);
    }
  }
}

void DynamicPortManager::connectionRemovedNeedToRemoveAPort(const SCIRun::Dataflow::Networks::ConnectionId& id)
{
  if (enabled_)
  {
    //std::cout << "need to remove a port: " << id.id_ << std::endl;
    auto desc = id.describe();
    auto moduleIn = controller_->getNetwork()->lookupModule(desc.in_.moduleId_);
    if (moduleIn->get_input_port(desc.in_.port_)->isDynamic())
    {
      Module::Builder builder;
      builder.removeInputPort(moduleIn, desc.in_.port_);
      portRemoved_(moduleIn->get_id(), desc.in_.port_);
    }
  }
}

boost::signals2::connection DynamicPortManager::connectPortAdded(const PortAddedSignalType::slot_type& subscriber)
{
  return portAdded_.connect(subscriber);
}

boost::signals2::connection DynamicPortManager::connectPortRemoved(const PortRemovedSignalType::slot_type& subscriber)
{
  return portRemoved_.connect(subscriber);
}

void DynamicPortManager::enable()
{
  //enabled_ = true;
}

void DynamicPortManager::disable()
{
  //enabled_ = false;
}<|endoftext|>


<commit_before>/**
 * @file replicaStatusChangedSubscription.cc
 * @author Bartek Kryza
 * @copyright (C) 2020 ACK CYFRONET AGH
 * @copyright This software is released under the MIT license cited in
 * 'LICENSE.txt'
 */

#include "events/events.h"
#include "messages/fuse/fileAttr.h"

#include "messages.pb.h"

namespace one {
namespace client {
namespace events {

ReplicaStatusChangedSubscription::ReplicaStatusChangedSubscription(
    std::string fileUuid, std::chrono::milliseconds remoteThreshold,
    EventHandler<FileAttrChanged> handler)
    : m_fileUuid{std::move(fileUuid)}
    , m_remoteThreshold{remoteThreshold}
    , m_handler{std::move(handler)}
{
}

StreamKey ReplicaStatusChangedSubscription::streamKey() const
{
    return StreamKey::REPLICA_STATUS_CHANGED;
}

StreamPtr ReplicaStatusChangedSubscription::createStream(Manager &manager,
    SequencerManager & /*seqManager*/, Scheduler &scheduler) const
{
    auto aggregator = std::make_unique<KeyAggregator<FileAttrChanged>>();
    auto emitter = std::make_unique<TimedEmitter<FileAttrChanged>>(
        streamKey(), DEFAULT_TIMED_EMITTER_THRESHOLD, manager, scheduler);
    auto handler = std::make_unique<LocalHandler<FileAttrChanged>>(m_handler);

    return std::make_unique<AsyncStream>(
        std::make_unique<TypedStream<FileAttrChanged>>(
            std::move(aggregator), std::move(emitter), std::move(handler)));
}

std::string ReplicaStatusChangedSubscription::toString() const
{
    std::stringstream stream;
    stream << "type: 'ReplicaStatusChanged', file UUID: '" << m_fileUuid
           << "', time threshold: " << m_remoteThreshold.count() << "ms";
    return stream.str();
}

ProtoSubscriptionPtr ReplicaStatusChangedSubscription::serialize() const
{
    auto subscriptionMsg = std::make_unique<clproto::Subscription>();
    auto msg = subscriptionMsg->mutable_file_attr_changed();
    msg->set_file_uuid(m_fileUuid);
    msg->set_time_threshold(m_remoteThreshold.count());

    return subscriptionMsg;
}

} // namespace events
} // namespace client
} // namespace one
<commit_msg>VFS-6630 Fixed ReplicaStatusChanged serialization<commit_after>/**
 * @file replicaStatusChangedSubscription.cc
 * @author Bartek Kryza
 * @copyright (C) 2020 ACK CYFRONET AGH
 * @copyright This software is released under the MIT license cited in
 * 'LICENSE.txt'
 */

#include "events/events.h"
#include "messages/fuse/fileAttr.h"

#include "messages.pb.h"

namespace one {
namespace client {
namespace events {

ReplicaStatusChangedSubscription::ReplicaStatusChangedSubscription(
    std::string fileUuid, std::chrono::milliseconds remoteThreshold,
    EventHandler<FileAttrChanged> handler)
    : m_fileUuid{std::move(fileUuid)}
    , m_remoteThreshold{remoteThreshold}
    , m_handler{std::move(handler)}
{
}

StreamKey ReplicaStatusChangedSubscription::streamKey() const
{
    return StreamKey::REPLICA_STATUS_CHANGED;
}

StreamPtr ReplicaStatusChangedSubscription::createStream(Manager &manager,
    SequencerManager & /*seqManager*/, Scheduler &scheduler) const
{
    auto aggregator = std::make_unique<KeyAggregator<FileAttrChanged>>();
    auto emitter = std::make_unique<TimedEmitter<FileAttrChanged>>(
        streamKey(), DEFAULT_TIMED_EMITTER_THRESHOLD, manager, scheduler);
    auto handler = std::make_unique<LocalHandler<FileAttrChanged>>(m_handler);

    return std::make_unique<AsyncStream>(
        std::make_unique<TypedStream<FileAttrChanged>>(
            std::move(aggregator), std::move(emitter), std::move(handler)));
}

std::string ReplicaStatusChangedSubscription::toString() const
{
    std::stringstream stream;
    stream << "type: 'ReplicaStatusChanged', file UUID: '" << m_fileUuid
           << "', time threshold: " << m_remoteThreshold.count() << "ms";
    return stream.str();
}

ProtoSubscriptionPtr ReplicaStatusChangedSubscription::serialize() const
{
    auto subscriptionMsg = std::make_unique<clproto::Subscription>();
    auto msg = subscriptionMsg->mutable_replica_status_changed();
    msg->set_file_uuid(m_fileUuid);
    msg->set_time_threshold(m_remoteThreshold.count());

    return subscriptionMsg;
}

} // namespace events
} // namespace client
} // namespace one
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/perception/obstacle/lidar/tracker/hm_tracker/tracked_object.h"

#include "modules/perception/obstacle/common/geometry_util.h"

namespace apollo {
namespace perception {

TrackedObject::TrackedObject(ObjectPtr obj_ptr) : object_ptr(obj_ptr) {
  if (object_ptr != nullptr) {
    barycenter = GetCloudBarycenter<apollo::perception::pcl_util::Point>(
                     object_ptr->cloud)
                     .cast<float>();
    center = object_ptr->center.cast<float>();
    size = Eigen::Vector3f(object_ptr->length, object_ptr->width,
                           object_ptr->height);
    direction = object_ptr->direction.cast<float>();
    lane_direction = Eigen::Vector3f::Zero();
    anchor_point = barycenter;
    velocity = Eigen::Vector3f::Zero();
    acceleration = Eigen::Vector3f::Zero();
    type = object_ptr->type;
    velocity_uncertainty = Eigen::Matrix3f::Identity() * FLT_EPSILON;
  }
}

void TrackedObject::clone(const TrackedObject& rhs) {
  *this = rhs;
  object_ptr.reset(new Object());
  object_ptr->clone(*rhs.object_ptr);
}

}  // namespace perception
}  // namespace apollo
<commit_msg>Perception: use default value<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo Authors. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *****************************************************************************/

#include "modules/perception/obstacle/lidar/tracker/hm_tracker/tracked_object.h"

#include "modules/perception/obstacle/common/geometry_util.h"

namespace apollo {
namespace perception {

TrackedObject::TrackedObject(ObjectPtr obj_ptr) : object_ptr(obj_ptr) {
  if (object_ptr != nullptr) {
    barycenter = GetCloudBarycenter<apollo::perception::pcl_util::Point>(
                     object_ptr->cloud)
                     .cast<float>();
    center = object_ptr->center.cast<float>();
    size = Eigen::Vector3f(object_ptr->length, object_ptr->width,
                           object_ptr->height);
    direction = object_ptr->direction.cast<float>();
    lane_direction = Eigen::Vector3f::Zero();
    anchor_point = barycenter;
    velocity = Eigen::Vector3f::Zero();
    acceleration = Eigen::Vector3f::Zero();
    type = object_ptr->type;
    velocity_uncertainty = Eigen::Matrix3f::Identity() * 5;
  }
}

void TrackedObject::clone(const TrackedObject& rhs) {
  *this = rhs;
  object_ptr.reset(new Object());
  object_ptr->clone(*rhs.object_ptr);
}

}  // namespace perception
}  // namespace apollo
<|endoftext|>