
! script name: 3dcpaths.d/alignnormal
! 3dtopic: align surface normal vector

!A
!A NAME:
!A
!A 	Group: Normal Direction
!A
!A DESCRIPTION:
!A
!A 	This script aligns normal vector direction on a surface or solid.
!A
!B INSTRUCTIONS:
!B
!B 	PICK SURFACE, Proceed: Pick the surface
!B 		to have its normal vectors aligned.
!B
!B 		P - Proceed may be used to exit the script.
!B
!B 	PICK WHICH SIDE OF SURFACE: Pick which side
!B 		of the surface the normal vectors are to be aligned on.
!B

Stat=ChangeLabelStr("ScriptNameStatus","Function: align normal direction ")

DIM Destination$[256]
DIM Answer$[256]
DIM Surface_dir$[256]
DIM Name$[256]

DeActivateUndo
Normal_len=NamedVarVal("3D Normal Length",Ws3DSystemVars,1.0)
Forward_color=3
Reverse_color=4
Start:!

Stat=SetPickMask(WsPickSurfOnly)
Stat=SetInputFormat("a1",",P,")
Surface=PickEntity("PICK SURFACE, Proceed ",Answer$)
IF ExitScript(Destination$) THEN Leave
IF Answer$="P" THEN Leave
IF NOT ValidGeometry(Surface) THEN Start

UVpoint=LastUVSurfPick(Surface)
IF NOT ValidGeometry(UVpoint) THEN Start
U=XPointValue(UVpoint)
V=YPointValue(UVpoint)
Stat=DeleteEntity(UVPoint)


Stat=SetNormalDir(Surface,WsForward)
GOSUB Orient_normal
IF Norm_sign=1 THEN 
	Stat=SetNormalDir(Surface,WsForward)
ELSE
	Stat=SetNormalDir(Surface,WsReverse)
END IF

GOTO Start

Orient_normal:!
	GOSUB ShowNormalDir
Pick_normal:L1=PickSpecificEnt("PICK WHICH SIDE OF SURFACE",WsPickLines)
	IF ExitScript(Destination$) THEN Leave
	IF NOT ValidGeometry(L1) THEN Orient_normal
	Norm_sign=0
	Pt=ParameterPt(L1,1.0)
	D1=DistTwoPts(Pt,Pforward)
	D2=DistTwoPts(Pt,Preverse)
	Norm_sign=1
	IF D2<D1 THEN Norm_sign=-1
	IF NOT Norm_sign THEN Pick_normal
Stat=DeleteEntity(Forward_normal)
Stat=DeleteEntity(Reverse_normal)
Stat=DeleteEntity(Pt)
Stat=DeleteEntity(Pforward)
Stat=DeleteEntity(Preverse)
RETURN

ShowNormalDir:!
	Forward_normal=SurfNormalLine(Surface,U,V,Normal_len,WsForward)
	Pforward=ParameterPt(Forward_normal,1.0)

	Reverse_normal=SurfNormalLine(Surface,U,V,Normal_len,WsReverse)
	Preverse=ParameterPt(Reverse_normal,1.0)

	Stat= SetForceVisible(Forward_normal,WsTrue)
        Stat= SetForceVisible(Pforward,WsTrue)
        Stat= SetForceVisible(Reverse_normal,WsTrue)
        Stat= SetForceVisible(Preverse,WsTrue)

        Stat=SetColor(Forward_normal,Forward_color)
        Stat=SetColor(Pforward,Forward_color)
        Stat=SetColor(Reverse_normal,Reverse_color)
        Stat=SetColor(Preverse,Reverse_color)
RETURN

Leave:!
Stat=SetPickMask(WsPickAll)
Stat=DeleteEntity(Nline)
Stat=DeleteEntity(Forward_normal)
Stat=DeleteEntity(Reverse_normal)
Stat=DeleteEntity(Pt)
Stat=DeleteEntity(Pforward)
Stat=DeleteEntity(Preverse)
Stat=DeleteEntity(UVPoint)
IF NOT LEN(Destination$) THEN
	LOAD "typecontrol"
ELSE
	LOAD Destination$
END IF
END
