Code/SliceMesh.cs
namespace Sandbox;

[Title( "Mesh Slicer" )]
[Category( "SliceMesh" )]
[Icon( "content_cut" )]
public sealed class MeshSlicerComponent : Component
{
	[Property] public ModelRenderer Target { get; set; }

	[Property] public Material CrossSectionMaterial { get; set; }

	[Property] public MeshSliceRegion CrossSectionRegion { get; set; } = MeshSliceRegion.Full;

	[Property] public bool DisableSourceAfterSlice { get; set; }

	public MeshSliceResult SliceWorld( Vector3 worldPosition, Vector3 worldNormal )
	{
		var target = ResolveTarget();
		if ( target is null )
			return null;

		return MeshSlicer.Slice( target, worldPosition, worldNormal, CrossSectionRegion, CrossSectionMaterial );
	}

	public GameObject[] SliceAndSpawnWorld( Vector3 worldPosition, Vector3 worldNormal )
	{
		return SliceAndSpawnWorld( worldPosition, worldNormal, autoCopyPhysics: false );
	}

	public GameObject[] SliceAndSpawnWorld( Vector3 worldPosition, Vector3 worldNormal, bool autoCopyPhysics )
	{
		var result = SliceWorld( worldPosition, worldNormal );
		if ( result is null )
			return null;

		var source = ResolveTarget()?.GameObject;
		if ( source is null )
			return null;

		return result.CreateHulls( source, DisableSourceAfterSlice, autoCopyPhysics );
	}

	private ModelRenderer ResolveTarget()
	{
		return Target ?? GameObject?.GetComponent<ModelRenderer>( true );
	}
}