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

#include "DNA_mesh_types.h"

#include "BLI_atomic_disjoint_set.hh"
#include "BLI_task.hh"

#include "node_geometry_util.hh"

namespace blender::nodes::node_geo_input_mesh_island_cc {

static void node_declare(NodeDeclarationBuilder &b)
{
  b.add_output<decl::Int>("Island Index"_ustr)
      .structure_type(StructureType::Field)
      .description(
          "The index of the each vertex's island. Indices are based on the "
          "lowest vertex index contained in each island");
  b.add_output<decl::Int>("Island Count"_ustr)
      .structure_type(StructureType::Field)
      .description("The total number of mesh islands");
}

class IslandFieldInput final : public bke::MeshFieldInput {
 public:
  IslandFieldInput() : bke::MeshFieldInput(CPPType::get<int>(), "Island Index") {}

  GVArray get_varray_for_context(const Mesh &mesh,
                                 const AttrDomain domain,
                                 const IndexMask & /*mask*/) const final
  {
    const Span<int2> edges = mesh.edges();

    AtomicDisjointSet islands(mesh.verts_num);
    threading::parallel_for(edges.index_range(), 1024, [&](const IndexRange range) {
      for (const int2 &edge : edges.slice(range)) {
        islands.join(edge[0], edge[1]);
      }
    });

    Array<int> output(mesh.verts_num);
    islands.calc_reduced_ids(output);

    return mesh.attributes().adapt_domain<int>(
        VArray<int>::from_container(std::move(output)), AttrDomain::Point, domain);
  }

  void hash_unique(UniqueHashBytes &hash, fn::FieldHashDeep & /*deep_hash_cache*/) const override
  {
    static constexpr int8_t id = 0;
    hash.add(&id);
  }

  std::optional<AttrDomain> preferred_domain(const Mesh & /*mesh*/) const override
  {
    return AttrDomain::Point;
  }

  bke::NativeFieldDomain native_domain_info(const Mesh & /*mesh*/) const override
  {
    /* Domain interpolation will not mix values for separate islands. */
    return bke::NativeFieldDomain::Constant();
  }
};

class IslandCountFieldInput final : public bke::MeshFieldInput {
 public:
  IslandCountFieldInput() : bke::MeshFieldInput(CPPType::get<int>(), "Island Count") {}

  GVArray get_varray_for_context(const Mesh &mesh,
                                 const AttrDomain domain,
                                 const IndexMask & /*mask*/) const final
  {
    const Span<int2> edges = mesh.edges();

    AtomicDisjointSet islands(mesh.verts_num);
    threading::parallel_for(edges.index_range(), 1024, [&](const IndexRange range) {
      for (const int2 &edge : edges.slice(range)) {
        islands.join(edge[0], edge[1]);
      }
    });

    const int islands_num = islands.count_sets();
    return VArray<int>::from_single(islands_num, mesh.attributes().domain_size(domain));
  }

  void hash_unique(UniqueHashBytes &hash, fn::FieldHashDeep & /*deep_hash_cache*/) const override
  {
    static constexpr int8_t id = 0;
    hash.add(&id);
  }

  std::optional<AttrDomain> preferred_domain(const Mesh & /*mesh*/) const override
  {
    return AttrDomain::Point;
  }

  bke::NativeFieldDomain native_domain_info(const Mesh & /*mesh*/) const override
  {
    return bke::NativeFieldDomain::Constant();
  }
};

static void node_geo_exec(GeoNodeExecParams params)
{
  if (params.output_is_required("Island Index"_ustr)) {
    params.set_output("Island Index"_ustr, Field<int>::from_input<IslandFieldInput>());
  }
  if (params.output_is_required("Island Count"_ustr)) {
    params.set_output("Island Count"_ustr, Field<int>::from_input<IslandCountFieldInput>());
  }
}

static void node_register()
{
  static bke::bNodeType ntype;
  geo_node_type_base(&ntype, "GeometryNodeInputMeshIsland"_ustr, GEO_NODE_INPUT_MESH_ISLAND);
  ntype.ui_name = "Mesh Island";
  ntype.ui_description = "Retrieve information about separate connected regions in a mesh";
  ntype.enum_name_legacy = "MESH_ISLAND";
  ntype.nclass = NODE_CLASS_INPUT;
  ntype.declare = node_declare;
  ntype.geometry_node_execute = node_geo_exec;
  bke::node_register_type(ntype);
}
NOD_REGISTER_NODE(node_register)

}  // namespace blender::nodes::node_geo_input_mesh_island_cc
