package d2isometricimg

import (
	
	
	
	

	
	
	
	
	
	
	
	
	
)

type nativeAnimatedNode struct{ first, last int }

// Round solids retain their physical caps and curved walls. Every other
// component uses D2's own contour and paint implementation, independent of
// decoration, including the chosen cloud and person relief silhouettes.
func nativeCanonicalNode( d2isometric.Node) bool {
	return !nativeSolidNode()
}

func nativeReliefSymbol( d2isometric.Node) bool {
	switch .Type {
	case d2target.ShapeCloud, d2target.ShapePerson, d2target.ShapeC4Person:
		return true
	}
	return false
}

// Symbol depth follows the source footprint without changing X/Z coordinates
// or print allocation. Geometry and projection estimates share this calculation.
func nativeCanonicalHeight( d2isometric.Node,  float64) float64 {
	 := math.Max(.10, .Size.Y*1.15)
	switch .Type {
	case d2target.ShapeClass, d2target.ShapeSQLTable:
		 = .46
	case d2target.ShapeCloud:
		 = .24 * math.Min(.Size.X, .Size.Z)
	case d2target.ShapePerson, d2target.ShapeC4Person:
		 = .19 * math.Min(.Size.X, .Size.Z)
	case d2target.ShapeText:
		 = .018
		if nativeMarkdownCard() {
			 = .115
		}
	}
	if .Metadata.Original.ThreeDee {
		if  <= 0 {
			 = .01
			if .Metadata.Original.Width > 0 {
				 = .Size.X / float64(.Metadata.Original.Width)
			}
		}
		 += d2target.THREE_DEE_OFFSET * 
	}
	return 
}

func nativeFaceSource( d2isometric.Node,  string) d2target.Shape {
	 := .Metadata.Original
	.ID, .Pos = "native-face", d2target.NewPoint(0, 0)
	if .Width <= 0 {
		.Width = max(1, int(math.Ceil(.Size.X/.01)))
	}
	if .Height <= 0 {
		.Height = max(1, int(math.Ceil(.Size.Z/.01)))
	}
	.Text = d2target.Text{}
	.Icon, .Link, .Tooltip = nil, "", ""
	.PrettyLink, .TooltipPosition, .LabelPosition = "", "", ""
	// Keep the source border-label aperture in native face geometry without
	// painting its text twice. The separately printed label retains the real
	// content and font; a transparent space reserves its compiled mask box.
	if label.FromString(.Metadata.Original.LabelPosition).IsBorder() && .Metadata.Original.Label != "" {
		.Text = d2target.Text{Label: " ", LabelWidth: .Metadata.Original.LabelWidth, LabelHeight: .Metadata.Original.LabelHeight, FontSize: max(1, .Metadata.Original.FontSize), Color: "transparent", LabelFill: "transparent"}
		.LabelPosition = .Metadata.Original.LabelPosition
	}
	.Classes = nil
	.Class, .SQLTable = d2target.Class{}, d2target.SQLTable{}
	.Multiple, .Shadow, .Animated, .ThreeDee, .Blend = false, false, false, false, false
	.Opacity, .Fill, .Stroke = 1, , .Stroke
	.StrokeWidth, .StrokeDash = .StrokeWidth, .StrokeDash
	if .Type == d2target.ShapeClass || .Type == d2target.ShapeSQLTable {
		// The structured document owns row/header fills. Avoid painting an
		// extra translucent background beneath that document.
		.Fill, .Stroke = "transparent", .Fill
	}
	if .Type == d2target.ShapeClass || .Type == d2target.ShapeSQLTable || .Type == d2target.ShapeText || .Type == d2target.ShapeCode || .Type == d2target.ShapeImage {
		.Type = d2target.ShapeRectangle
	}
	return 
}

// Face paint is generated by the same bounded native scene renderer as SVG
// export. That retains D2's dash phase, pattern tile, border-radius, inner
// outline and fold-line behavior instead of approximating them independently.
func ( *meshBuilder) ( d2target.Shape) (*image.RGBA, labelSurface) {
	return .nativeFaceLayer(, nativeFaceCombined)
}

type nativeFaceLayer uint8

const (
	nativeFaceCombined nativeFaceLayer = iota
	nativeFaceFill
	nativeFaceInk
)

// Both layers retain the original document viewport. In particular, the ink
// viewport includes the entire centered stroke, not just its centerline.
// Splitting paint does not spend another node's texture allocation.
func ( *meshBuilder) ( d2target.Shape,  ...float64) (,  *image.RGBA,  labelSurface) {
	 := .faceMaxPixels
	if  > 0 {
		.faceMaxPixels = max(1, /2)
	}
	defer func() { .faceMaxPixels =  }()
	,  = .nativeFaceLayer(, nativeFaceFill)
	if .err == nil {
		, _ = .nativeFaceLayer(, nativeFaceInk)
	}
	if .err == nil && len() > 0 && [0] < 1 &&  != nil &&  != nil {
		.nativeFaceOpacity(, , max(0, [0]))
	}
	return
}

// Splitting one source paint into two physical materials must not apply its
// group opacity twice where ink covers fill. Compensate the lower layer so
// source-over produces exactly opacity*(ink + fill*(1-ink)) coverage.
func ( *meshBuilder) (,  *image.RGBA,  float64) {
	if  := nativeVectorForTexture(.ctx, );  != nil {
		.inkCoverage = nativeVectorForTexture(.ctx, )
		.coverageOpacity = 
	}
	for  := .Bounds().Min.Y;  < .Bounds().Max.Y; ++ {
		if (-.Bounds().Min.Y)%64 == 0 {
			if  := .ctx.Err();  != nil {
				.err = 
				return
			}
		}
		for  := .Bounds().Min.X;  < .Bounds().Max.X; ++ {
			 := float64(.Pix[.PixOffset(, )+3]) / 255
			 := (1 - ) / (1 - *)
			 := .PixOffset(, )
			for  := 0;  < 4; ++ {
				.Pix[+] = uint8(math.Round(float64(.Pix[+]) * ))
			}
		}
	}
}

func nativeSelectFaceLayer( *d2scene.Node,  nativeFaceLayer) {
	if  == nil ||  == nativeFaceCombined {
		return
	}
	 := func( *d2scene.Paint,  **d2scene.Stroke) {
		if  == nativeFaceFill {
			* = nil
		} else {
			* = nil
		}
	}
	switch p := .Primitive.(type) {
	case d2scene.Rect:
		(&.Fill, &.Stroke)
		.Primitive = 
	case d2scene.Ellipse:
		(&.Fill, &.Stroke)
		.Primitive = 
	case d2scene.Path:
		(&.Fill, &.Stroke)
		.Primitive = 
	case d2scene.TextRun:
		// The only face text is an invisible border-aperture placeholder.
		.Primitive = nil
	}
	for ,  := range .Children {
		(, )
	}
}

func ( *meshBuilder) ( d2target.Shape,  nativeFaceLayer) (*image.RGBA, labelSurface) {
	 := d2target.NewDiagram()
	.Root.Fill, .Root.Stroke = "transparent", "none"
	.Shapes = []d2target.Shape{}
	 := int64(0)
	,  := d2scenebuild.Build(.ctx, , d2scenebuild.Options{Pad: &, MaxNodes: 20000, MaxPathCommands: 250000,
		LinkBudget: d2scenebuild.LinkBudget{MaxRegions: 2, MaxStringBytes: 4096}})
	if  != nil {
		.err = fmt.Errorf("native shape face: %w", )
		return nil, labelSurface{}
	}
	if .Type == d2target.ShapePage &&  == nativeFaceInk && nativePaint(.Fill, "white").A > 0 {
		nativeRemovePageGlyph(.Root)
	}
	nativeSelectFaceLayer(.Root, )
	 := richRasterOptions()
	.Scale = math.Min(2, 1024/math.Max(.ViewBox.Width, .ViewBox.Height))
	if .faceMaxPixels > 0 {
		.Scale = math.Min(.Scale, math.Sqrt(float64(.faceMaxPixels)/(.ViewBox.Width*.ViewBox.Height))) * .999
	}
	.MaxDecodedAssetBytes = 32 * 1024 * 1024
	 := int64(math.Ceil(.ViewBox.Width*.Scale)) * int64(math.Ceil(.ViewBox.Height*.Scale))
	 := int64(1024 * 1024)
	if .faceMaxPixels > 0 &&  > .faceMaxPixels {
		// A square-root scale limit alone can overshoot by one row/column
		// after raster dimensions round up. Allocate integral dimensions.
		 := max(1, int(math.Ceil(max(.ViewBox.Width, .ViewBox.Height)*.Scale)))
		,  := surfaceTextureDimensions(.ViewBox.Width, .ViewBox.Height, , int(.faceMaxPixels))
		.LogicalWidth, .LogicalHeight = float64(), float64()
		.ViewportFit, .Scale = d2scene.ViewportStretch, 1
		 = int64() * int64()
	}
	if .outputDensity > 0 && captionFinite(.outputDensity) {
		// Source paint stays in its authored coordinate system; only its
		// sampling resolution follows the projected physical face size.
		 := .scale
		if  <= 0 {
			 = .01
		}
		 = 4 * 1024 * 1024
		 := 
		if .faceMaxPixels > 0 {
			 = min(, .faceMaxPixels)
		}
		,  := surfaceTextureDimensionsAtDensity(.ViewBox.Width*, .ViewBox.Height*, 4096, int(), .outputDensity)
		.LogicalWidth, .LogicalHeight = float64(), float64()
		.ViewportFit = d2scene.ViewportStretch
		.Scale = 1
		 = int64() * int64()
	}
	if  <= 0 ||  >  || .facePixels > 24*1024*1024- {
		.err = fmt.Errorf("native shape faces exceed texture pixel budget")
		return nil, labelSurface{}
	}
	.facePixels += 
	,  := d2raster.Render(.ctx, , )
	if  != nil {
		.err = fmt.Errorf("native shape face raster: %w", )
		return nil, labelSurface{}
	}
	 := image.NewRGBA(.Bounds())
	draw.Draw(, .Bounds(), , .Bounds().Min, draw.Src)
	if  := retainNativeVectorSurface(.ctx, , );  != nil {
		.err = 
		return nil, labelSurface{}
	}
	 := labelSurface{center: nv(.ViewBox.X+.ViewBox.Width/2, 0, .ViewBox.Y+.ViewBox.Height/2), width: .ViewBox.Width, depth: .ViewBox.Height}
	if  != nativeFaceFill {
		.nativeFaceBorderAperture(, , )
	}
	 := false
	for  := 3;  < len(.Pix);  += 4 {
		if .Pix[] != 0 {
			 = true
			break
		}
	}
	if ! {
		 = nil
	}
	return , 
}

// Border labels have a narrow opening in the shape outline. Text is printed
// separately on the mesh, so retain that opening in the face texture using the
// same source box and two-pixel label padding as D2's border-label mask.
func ( *meshBuilder) ( *image.RGBA,  labelSurface,  d2target.Shape) {
	 := label.FromString(.LabelPosition)
	if .Label == "" || !.IsBorder() || .StrokeWidth <= 0 {
		return
	}
	 := geo.NewBox(geo.NewPoint(float64(.Pos.X), float64(.Pos.Y)), float64(.Width), float64(.Height))
	 := .GetPointOnBox(, label.PADDING, float64(.LabelWidth), float64(.LabelHeight))
	 := float64(.StrokeWidth)
	, , ,  := 0., 0., 0., 0.
	switch  {
	case label.BorderTopLeft, label.BorderTopCenter, label.BorderTopRight:
		, , ,  = .X-2, .TopLeft.Y-/2, float64(.LabelWidth+4), 
	case label.BorderBottomLeft, label.BorderBottomCenter, label.BorderBottomRight:
		, , ,  = .X-2, .TopLeft.Y+.Height-/2, float64(.LabelWidth+4), 
	case label.BorderLeftTop, label.BorderLeftMiddle, label.BorderLeftBottom:
		, , ,  = .TopLeft.X-/2, .Y-2, , float64(.LabelHeight+4)
	case label.BorderRightTop, label.BorderRightMiddle, label.BorderRightBottom:
		, , ,  = .TopLeft.X+.Width-/2, .Y-2, , float64(.LabelHeight+4)
	}
	if  := nativeVectorForTexture(.ctx, );  != nil {
		nativeVectorAperture(, d2scene.Box{X: , Y: , Width: , Height: })
	}
	,  := float64(.Bounds().Dx())/.width, float64(.Bounds().Dy())/.depth
	,  := (-.center.X+.width/2)*, (-.center.Z+.depth/2)*
	,  := +*, +*
	for  := max(0, int(math.Floor()));  < min(.Bounds().Dy(), int(math.Ceil())); ++ {
		for  := max(0, int(math.Floor()));  < min(.Bounds().Dx(), int(math.Ceil())); ++ {
			 := (math.Min(float64(+1), ) - math.Max(float64(), )) * (math.Min(float64(+1), ) - math.Max(float64(), ))
			 := .PixOffset(+.Bounds().Min.X, +.Bounds().Min.Y)
			for  := 0;  < 4; ++ {
				.Pix[+] = uint8(math.Round(float64(.Pix[+]) * (1 - )))
			}
		}
	}
}

func ( *meshBuilder) ( d2isometric.Node,  string) {
	 := .scale
	if  <= 0 {
		 = .01
	}
	 := .Fill
	if nativeToken(.Metadata.Original.Fill) && !.FillExplicit {
		 = "#dce5eb"
	}
	if .Type == d2target.ShapeClass || .Type == d2target.ShapeSQLTable {
		 = .Stroke
	}
	 := nativeFaceSource(, )
	,  := nativeShapeProfiles()
	if  != nil {
		.err = 
		return
	}
	 := .Opacity
	if nativeClassicRim() {
		 = 1
	}
	, ,  := .nativeFaceLayers(, )
	if .err != nil {
		return
	}
	,  := .Size.X, .Size.Z
	,  := /float64(.Width), /float64(.Height)
	 := .Position.Y - .Size.Y/2
	 := nativeCanonicalHeight(, )
	 :=  + 
	 := nativeMaterial(, .68, 0, .Opacity)
	 := *
	for  := 1;  >= 0; -- {
		if  == 1 && !.Metadata.Original.Multiple {
			continue
		}
		// D2's multiple modifier preserves its source offset right and up.
		, ,  := float64()*d2target.MULTIPLE_OFFSET*, -float64()*d2target.MULTIPLE_OFFSET*, -float64()*math.Min(.045, *.25)
		var  []Vec
		for ,  := range  {
			 := make([]Vec, len())
			for ,  := range  {
				[] = nv(.Position.X-/2+float64(.X*)+, +, .Position.Z-/2+float64(.Z*)+)
			}
			if .Type == d2target.ShapePage {
				 = 
			}
			var  *Material
			if .options.vector && .Opacity == 1 && nativePaint(, "transparent").A == 255 {
				// The raster cap writes depth through its texture alpha. SVG
				// resolves that coverage with the same source contour, while
				// retaining the original vector paint above it.
				 = 
			}
			 := len(.triangles)
			.extrudedProfile(, ++.nodeSupportDrop, , &)
			if  != nil {
				for  := ;  < len(.triangles); ++ {
					if .triangles[].Material ==  {
						.triangles[].svgCoverageOnly = true
						.triangles[].CastShadow = false
					}
				}
			}
		}
		 := 
		.center = nv(.Position.X-/2+float64(.center.X*)+, ++.0005, .Position.Z-/2+float64(.center.Z*)+)
		.width, .depth = .width*, .depth*
		 := len(.triangles)
		.surfaceTexture(, , .Opacity)
		for  := ;  < len(.triangles); ++ {
			.triangles[].Material.Unlit = false
			.triangles[].Material.Roughness = .68
			.triangles[].Material.Metalness = 0
			.triangles[].NoDepthWrite = false
			.triangles[].CastShadow = true
		}
		// Authored linework keeps its actual ink color instead of being
		// washed out by the physical cap's lighting response.
		if !nativeClassicRim() {
			.surfaceTexture(, , .Opacity)
		}
		if .Type == d2target.ShapePage {
			.nativePageFold(, , , , , , +, )
		}
	}
	.canonicalNodeContent(, , , )
}

func ( *meshBuilder) ( d2isometric.Node,  d2target.Shape,  string,  float64) {
	// Structured row coordinates use the entire allocated D2 face. Other
	// labels retain their compiled placement in that same coordinate system.
	 := nativeNodeLabelSurface(, , +.0015)
	 := readableSurfaceInk(, .Opacity)
	if .FontExplicit {
		 = .FontColor
	}
	if .Metadata.Original.Icon != nil {
		// Artwork belongs to the shape face, even when its caption is outside
		// that face. Image shapes use the complete source footprint; ordinary
		// symbols share the inner face with any inside-positioned label.
		 := nativeNodeIconSurface(, , +.0015)
		 := .Metadata.Original
		if .Type == d2target.ShapeImage {
			.Label = ""
		}
		 := .shapeIcon(, , .Opacity, "node")
		 := label.FromString(.Metadata.Original.LabelPosition)
		if .Type != d2target.ShapeImage && !.IsOutside() && !.IsBorder() {
			 = 
		}
	}
	.shapeLabel(.Metadata.Original, , , .Opacity, "node")
}

func nativeNodeIconSurface( d2isometric.Node,  d2target.Shape,  float64) labelSurface {
	if .Type == d2target.ShapeImage || .Type == d2target.ShapeClass || .Type == d2target.ShapeSQLTable {
		return labelSurface{center: nv(.Position.X, , .Position.Z), width: .Size.X, depth: .Size.Z}
	}
	 := shape.NewShape(d2target.DSL_SHAPE_TO_SHAPE_TYPE[.Type], geo.NewBox(geo.NewPoint(0, 0), float64(.Width), float64(.Height)))
	 := .GetInnerBox()
	,  := .Size.X/float64(.Width), .Size.Z/float64(.Height)
	return labelSurface{center: nv(.Position.X-.Size.X/2+(.TopLeft.X+.Width/2)*, , .Position.Z-.Size.Z/2+(.TopLeft.Y+.Height/2)*), width: .Width * , depth: .Height * }
}

// A front-facing sidewall occupies some of the outside caption's projected
// gap. Expand that gap by exactly the wall's projected height, retaining the
// source side/alignment, text dimensions and horizontal print plane.
func ( *meshBuilder) ( d2isometric.Node,  int,  float64) {
	if .err != nil || .Metadata.Original.Label == "" || len(.triangles) < +2 {
		return
	}
	 := .triangles[len(.triangles)-2:]
	for ,  := range  {
		if !.NoDepthWrite || .Material == nil || .Material.Texture == nil {
			return
		}
	}
	 := nativeViewDirection()
	 := math.Max(0, [0].V[0].Position.Y-(.Position.Y-.Size.Y/2)) * 
	 := .X*.X + .Z*.Z
	,  := 0., 0.
	switch label.FromString(.Metadata.Original.LabelPosition) {
	case label.OutsideBottomLeft, label.OutsideBottomCenter, label.OutsideBottomRight:
		 =  *  / (.Y * .Z)
	case label.OutsideRightTop, label.OutsideRightMiddle, label.OutsideRightBottom:
		 =  *  / (.Y * .X)
	default:
		return
	}
	for  := range  {
		for  := range [].V {
			[].V[].Position.X += 
			[].V[].Position.Z += 
		}
	}
}

func nativeNodeLabelSurface( d2isometric.Node,  d2target.Shape,  float64) labelSurface {
	,  := .Size.X/float64(.Width), .Size.Z/float64(.Height)
	if .Type == d2target.ShapeClass || .Type == d2target.ShapeSQLTable {
		return labelSurface{center: nv(.Position.X, , .Position.Z), width: .Size.X, depth: .Size.Z}
	}
	 := shape.NewShape(d2target.DSL_SHAPE_TO_SHAPE_TYPE[.Type], geo.NewBox(geo.NewPoint(0, 0), float64(.Width), float64(.Height)))
	 := label.FromString(.Metadata.Original.LabelPosition)
	if  == label.Unset {
		 = label.InsideMiddleCenter
	}
	 := .GetInnerBox()
	if .IsOutside() || .IsBorder() {
		 = .GetBox().Copy()
		if .Metadata.Original.ThreeDee {
			 := float64(d2target.THREE_DEE_OFFSET)
			if .Type == d2target.ShapeHexagon {
				 /= 2
			}
			.TopLeft.Y -= 
			.Height += 
			.Width += d2target.THREE_DEE_OFFSET
		} else if .Metadata.Original.Multiple {
			.TopLeft.Y -= d2target.MULTIPLE_OFFSET
			.Height += d2target.MULTIPLE_OFFSET
			.Width += d2target.MULTIPLE_OFFSET
		}
	}
	,  := float64(.Metadata.Original.LabelWidth), float64(.Metadata.Original.LabelHeight)
	if  <= 0 ||  <= 0 {
		,  = .Width, .Height
	}
	 := .GetPointOnBox(, label.PADDING, , )
	return labelSurface{center: nv(.Position.X-.Size.X/2+(.X+/2)*, , .Position.Z-.Size.Z/2+(.Y+/2)*), width:  * , depth:  * }
}

// Flatten source paths in source pixels before applying the one scene scale.
// All shapes use absolute M/L/C/Z commands; cubic subdivision is bounded and
// quarter-pixel accurate for ordinary D2 dimensions.
func nativeShapeProfile( d2target.Shape,  ...*[][]Vec) ([]Vec, error) {
	,  := float64(max(1, .Width)), float64(max(1, .Height))
	 := shape.NewShape(d2target.DSL_SHAPE_TO_SHAPE_TYPE[.Type], geo.NewBox(geo.NewPoint(0, 0), , ))
	 := shape.GetPathCommands()
	if len() == 0 {
		if .Type == d2target.ShapeCircle || .Type == d2target.ShapeOval {
			 := make([]Vec, 96)
			for  := range  {
				 := 2 * math.Pi * float64() / float64(len())
				[] = nv(/2+/2*math.Cos(), 0, /2+/2*math.Sin())
			}
			return , nil
		}
		 := math.Min(float64(.BorderRadius), math.Min(, )/2)
		if  <= 0 {
			return []Vec{nv(0, 0, 0), nv(, 0, 0), nv(, 0, ), nv(0, 0, )}, nil
		}
		 := make([]Vec, 0, 36)
		for ,  := range []Vec{nv(-, 0, ), nv(-, 0, -), nv(, 0, -), nv(, 0, )} {
			for  := 0;  <= 8; ++ {
				 := -math.Pi/2 + float64()*math.Pi/2 + float64()*math.Pi/16
				 = append(, nv(.X+*math.Cos(), 0, .Z+*math.Sin()))
			}
		}
		return , nil
	}
	var  []Vec
	 := 0.
	for ,  := range  {
		var  []Vec
		var  Vec
		 := false
		 := func( Vec) error {
			if len() >= 2048 {
				return fmt.Errorf("native shape profile exceeds 2048 vertices")
			}
			if len() == 0 || nlen(nsub([len()-1], )) > 1e-8 {
				 = append(, )
			}
			return nil
		}
		for ,  := range  {
			 := nv(.End.X, 0, .End.Y)
			switch .Kind {
			case svg.PathCommandClose:
				 = true
			case svg.PathCommandMove, svg.PathCommandLine:
				if  := ();  != nil {
					return nil, 
				}
				 = 
			case svg.PathCommandCubic:
				,  := nv(.Control1.X, 0, .Control1.Y), nv(.Control2.X, 0, .Control2.Y)
				 := max(4, min(64, int(math.Ceil((nlen(nsub(, ))+nlen(nsub(, ))+nlen(nsub(, )))/4))))
				for  := 1;  <= ; ++ {
					 := float64() / float64()
					 := 1 - 
					 := nadd(nadd(nmul(, **), nmul(, 3***)), nadd(nmul(, 3***), nmul(, **)))
					if  := ();  != nil {
						return nil, 
					}
				}
				 = 
			}
		}
		if len() > 1 && nlen(nsub([0], [len()-1])) < 1e-7 {
			 = true
			 = [:len()-1]
		}
		 := math.Abs(nativePolygonArea())
		if  && len() >= 3 && len() > 0 {
			*[0] = append(*[0], )
		}
		if  >  {
			,  = , 
		}
	}
	if len() < 3 {
		return nil, fmt.Errorf("native shape %q has no closed profile", .Type)
	}
	return , nil
}

func nativeShapeProfiles( d2target.Shape) ([][]Vec, error) {
	var  [][]Vec
	,  := nativeShapeProfile(, &)
	if  != nil {
		return nil, 
	}
	if len() == 0 {
		return [][]Vec{}, nil
	}
	 := func( Vec,  []Vec) bool {
		 := false
		for ,  := range  {
			 := [(+1)%len()]
			,  := .X-.X, .Z-.Z
			if math.Abs((.X-.X)*-(.Z-.Z)*) < 1e-6 && .X >= min(.X, .X)-1e-6 && .X <= max(.X, .X)+1e-6 && .Z >= min(.Z, .Z)-1e-6 && .Z <= max(.Z, .Z)+1e-6 {
				return true
			}
			if (.Z > .Z) != (.Z > .Z) && .X < (.X-.X)*(.Z-.Z)/(.Z-.Z)+.X {
				 = !
			}
		}
		return 
	}
	var  [][]Vec
	for ,  := range  {
		 := false
		for ,  := range  {
			if  ==  || math.Abs(nativePolygonArea()) <= math.Abs(nativePolygonArea()) {
				continue
			}
			 := true
			for ,  := range  {
				if !(, ) {
					 = false
					break
				}
			}
			if  {
				 = true
				break
			}
		}
		if ! {
			 = append(, )
		}
	}
	return , nil
}

func nativePolygonArea( []Vec) float64 {
	 := 0.
	for  := range  {
		 := ( + 1) % len()
		 += [].X*[].Z - [].X*[].Z
	}
	return  / 2
}

func ( *meshBuilder) ( []Vec,  float64, ,  *Material) {
	if len() < 3 {
		return
	}
	 := nativePolygonArea()
	 := 1.
	if  < 0 {
		 = -1
	}
	,  := make([]Vec, len()), make([]Vec, len())
	 := make([]bool, len())
	for ,  := range  {
		 := [(+1)%len()]
		[] = nunit(nv((.Z-.Z)*, 0, (.X-.X)*))
	}
	for ,  := range  {
		,  := (+len()-1)%len(), (+1)%len()
		,  := nsub(, []), nsub([], )
		 := (.X*.Z - .Z*.X) * 
		// Smooth only gentle convex turns. Concave joints and real corners
		// retain their separate wall normals; positions never move.
		if  >= 0 && ndot([], []) > math.Cos(math.Pi/6) {
			[] = true
			[] = nunit(nadd([], []))
		}
	}
	 := func(,  int) Vec {
		if [] {
			return []
		}
		return []
	}
	for ,  := range  {
		 := ( + 1) % len()
		 := []
		,  := (, ), (, )
		if  < 0 {
			,  = , 
			,  = , 
		}
		,  := , 
		.Y, .Y = , 
		,  := Vertex{Position: , Normal: }, Vertex{Position: , Normal: }
		,  := Vertex{Position: , Normal: }, Vertex{Position: , Normal: }
		.triangle(, , , , true)
		.triangle(, , , , true)
	}
	if  == nil {
		return
	}
	 := make([]int, len())
	for  := range  {
		[] = 
	}
	 := func(, ,  Vec) float64 { return ((.X-.X)*(.Z-.Z) - (.Z-.Z)*(.X-.X)) *  }
	 := 0
	for len() > 2 {
		 := false
		for ,  := range  {
			, ,  := [[(+len()-1)%len()]], [], [[(+1)%len()]]
			if (, , ) <= 1e-12 {
				continue
			}
			 := true
			for ,  := range  {
				++
				if %4096 == 0 {
					if  := .ctx.Err();  != nil {
						.err = 
						return
					}
				}
				if  > 4_000_000 {
					.err = fmt.Errorf("native shape triangulation exceeds work budget")
					return
				}
				if  == [(+len()-1)%len()] ||  ==  ||  == [(+1)%len()] {
					continue
				}
				 := []
				if (, , ) > 1e-10 && (, , ) > 1e-10 && (, , ) > 1e-10 {
					 = false
					break
				}
			}
			if  {
				.flat(, , , , true)
				 = append([:], [+1:]...)
				 = true
				break
			}
		}
		if ! { // Only redundant collinear contour points can remain.
			return
		}
	}
}