# Copyright 2004, Rick Wilson 

# THIS SOFTWARE IS PROVIDED "AS IS" AND WITHOUT ANY EXPRESS OR
# IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.

# Name :          Curve Stitcher 2.2
# Description :   stitches 2 faces together
# Author :        RW
# Usage :         select 2 curves - edges & faces will be
#                 created between them
# Date :          18.Aug.2004
# Type :		tool
# History:
#			2.2 (6.Nov.2005) - fixed bug in finding the selected curves
#						(introduced with SU 5.0)
#			2.1 (18.Aug.2004) - fixed bug where last line occasionally
#						  not drawn
#			2.0 (10.Aug.2004) - modified for different numbers
#						  of vertices per curve
#			1.0 (02.Aug.2004) - first version

require 'sketchup.rb'

def stitch_curves
#	CHECK THE SELECTIONS
	model = Sketchup.active_model
	entities = model.active_entities
	ss = model.selection
	curves=[]
	ss.each do |s|
		if s.curve
			curves.push(s.curve)
		else
			return UI.messagebox("Please select only 2 curves")
		end
	end
	curves.uniq!
	if curves.length>2
		return UI.messagebox("Please select only 2 curves")
	end
	$ss1=curves[0]
	$ss2=curves[1]

	if (($ss1.vertices.length) < ($ss2.vertices.length))
		$curve1 = $ss2
		$curve2 = $ss1
	else
		$curve1 = $ss1
		$curve2 = $ss2
	end

	$c1=$curve1.vertices
	$c2=$curve2.vertices
	$curve1q = $curve1.vertices.length
	$curve2q = $curve2.vertices.length
	$b = ($curve1q.to_f-$curve2q.to_f)/$curve1q
	lines = []

	model.start_operation "Stitcher"
	1.upto($curve1q-1) do |a|
		c = (a * $b).to_i
		lines[lines.length]=entities.add_line($c1[a-1].position,$c2[(a-1)-c].position)
		entities[entities.length-1].find_faces if (entities[entities.length-1].class == Sketchup::Edge)
		lines[lines.length]=entities.add_line($c1[a].position,$c2[(a-1)-c].position)
		entities[entities.length-1].find_faces if (entities[entities.length-1].class == Sketchup::Edge)
	end

	lines[lines.length]=entities.add_line($c1.last.position,$c2.last.position) #DRAW LAST LINE - JUST IN CASE

	0.upto(lines.length-1) do |a|
		lines[a].find_faces
		lines[a].smooth=true
		lines[a].soft=true
	end
		
	model.commit_operation
end

if( not file_loaded?("curvestitcher.rb") )
#    add_separator_to_menu("Plugins")
if $submenu
	$submenu.add_item("Curve Stitcher") { stitch_curves }
else
    UI.menu("Plugins").add_item("Curve Stitcher") { stitch_curves }
end
end
#-----------------------------------------------------------------------------
file_loaded("curvestitcher.rb")
