/* SPDX-FileCopyrightText: 2024 Blender Authors
 *
 * SPDX-License-Identifier: GPL-2.0-or-later */

#include "node_geometry_util.hh"

namespace blender::nodes::node_geo_viewport_transform_cc {

static void node_declare(NodeDeclarationBuilder &b)
{
  b.add_output<decl::Matrix>("Projection"_ustr)
      .description(
          "Transforms points in view space to region space (\"clip space\" or \"normalized device "
          "coordinates\")");
  b.add_output<decl::Matrix>("View"_ustr)
      .description(
          "Transforms points from object space to view space using the viewport's location and "
          "rotation");
  b.add_output<decl::Bool>("Is Orthographic"_ustr)
      .description("Whether the viewport is using orthographic projection");
}

static void node_geo_exec(GeoNodeExecParams params)
{
  if (!check_tool_context_and_error(params)) {
    return;
  }
  const Object &self_object = *params.self_object();
  const GeoNodesOperatorData &data = *params.user_data()->call_data->operator_data;

  params.set_output("Projection"_ustr, data.viewport_winmat);
  params.set_output("View"_ustr, data.viewport_viewmat * self_object.object_to_world());
  params.set_output("Is Orthographic"_ustr, !data.viewport_is_perspective);
}

static void node_register()
{
  static bke::bNodeType ntype;
  geo_node_type_base(
      &ntype, "GeometryNodeViewportTransform"_ustr, GEO_NODE_TOOL_VIEWPORT_TRANSFORM);
  ntype.ui_name = "Viewport Transform";
  ntype.ui_description = "Retrieve the view direction and location of the 3D viewport";
  ntype.enum_name_legacy = "VIEWPORT_TRANFORM";
  ntype.nclass = NODE_CLASS_INPUT;
  ntype.declare = node_declare;
  ntype.geometry_node_execute = node_geo_exec;
  ntype.gather_link_search_ops = search_link_ops_for_tool_node;
  bke::node_register_type(ntype);
}
NOD_REGISTER_NODE(node_register)

}  // namespace blender::nodes::node_geo_viewport_transform_cc
