import netgen.meshing as ngm
from netgen.webgui import Draw

backend = "occ"
#backend = "spline"
#backend = "csg2d"

if backend == "occ":
    from netgen.occ import Circle, OCCGeometry
    disk = Circle((0,0), 1).Face()
    geo = OCCGeometry(disk, dim=2)
    shift = -1

elif backend == "spline":
    from netgen.geom2d import SplineGeometry
    geo = SplineGeometry()
    geo.AddCircle(c=(0, 0), r=1.0)
    shift = 0

elif backend == "csg2d":
    from netgen.geom2d import CSG2d, Circle
    geo = CSG2d()
    geo.Add(Circle(center=(0, 0), radius=1, bc="surface"))
    shift = 0

else:
    raise ValueError("Unexpected backend")

ngmesh = geo.GenerateMesh(maxh=0.5)
dim = ngmesh.dim
geo = ngmesh.GetGeometry()

# This refines the mesh without projecting the points to the boundary
ngmesh.SetGeometry(None)
ngmesh.Refine()
coordinates = ngmesh.Coordinates()

# Construct a new mesh and project the points on the boundary
rngmesh = ngm.Mesh(dim=dim)
rngmesh.SetGeometry(geo)
rngmesh.AddPoints(coordinates)

# Add cells
cells_np = ngmesh.Elements2D().NumPy()
nodes = cells_np["nodes"][:, :dim+1]
index = cells_np["index"][0]
index = rngmesh.Add(ngm.FaceDescriptor(bc=index))
rngmesh.AddElements(dim=dim,
                    index=index,
                    data=nodes, base=1,
                    project_geometry=True)


# Add edges
edges = ngmesh.Elements1D()
edges_np = edges.NumPy()
nodes = edges_np["nodes"][:, :dim]
index = edges_np["index"][0]

descr = ngm.EdgeDescriptor()
descr.index = index
descr.edgenr = index
index = rngmesh.Add(descr)
rngmesh.AddElements(dim=dim-1,
                    index=index,
                    data=nodes, base=1,
                    project_geometry=True)
rngmesh.Save("disk.vol")
Draw(rngmesh, filename="mesh.html")
