perspective projection 2D onto 3D

 From:  pressure (PEER)
10807.4 In reply to 10807.2 
Hello,

The ray tracing script above didn't quite do what I want, so I spent the day trying to modify it. Now it does what I want about 2/3 of the time:



but sometimes it hangs (Calculating...) after doing a couple points.



If I terminate the script by hitting Save then I see that all rays were committed, but only the first 2 intersections were found:



I'm running this in v5beta on macOS. Please help me find my bug.

To test:
open attached 3dm file
run ViewManager script and select view1
select "test pts" from Objects
select top face of object
run script

code:
//v2 August 9, 2022

//convert a vector into a unit vector (length = 1)
function LengthSq( v )
{
	return ( v.x * v.x ) + ( v.y * v.y ) + ( v.z * v.z );
}

function Normalize( v )
{
	var lensq = LengthSq( v );
	if ( lensq > 1.0e-12 )
		v.scale( 1.0 / Math.sqrt( lensq ) );
}

//appends elements of 2nd object list to first
function CombineLists( targetlist, fromlist )
{
for ( var i = 0; i < fromlist.length; ++i )
targetlist.addObject( fromlist.item(i) );
}

//draw rays from selected point(s), through camera point, and beyond
function DoViewRaysThroughPoints()
{
	var pts = moi.geometryDatabase.getSelectedObjects().getPoints();

	if ( pts.length == 0 )
	{
		moi.ui.alert( 'error - no point objects selected' );
		return;
	}
	
	
	var faces = moi.geometryDatabase.getSelectedObjects().getFaces(); //ObjectList
	
		if ( faces.length == 0 )
	{
		moi.ui.alert( 'error - no face objects selected' );
		return;
	}

	var camerapt = moi.ui.mainWindow.viewpanel.getViewport('3D').cameraPt;

	for ( var i = 0; i < pts.length; ++i )
	{
		var ptobj = pts.item( i );

		var dir = moi.vectorMath.makeVector( camerapt, ptobj.pt );
		Normalize( dir );

		var line_length = 150.0;
		var startpt = ptobj.pt; //ray starts at selected point
		//ray goes through camera point and line_length beyond
		var endpt = moi.vectorMath.createPoint( camerapt.x - dir.x * line_length, camerapt.y - dir.y * line_length, camerapt.z - dir.z * line_length );
		var factory = moi.command.createFactory( 'line' ); //create ray
		factory.setInput( 0, startpt );
		factory.setInput( 1, endpt );
		
		var ray = factory.calculate(); 	
		factory.commit(); //plot intersections only and not rays by commenting out this line
		
		CombineLists(ray,faces) //append face Objects to ray ObjectList so that ray can be intersected with faces
		var iFactory = moi.command.createFactory('intersect');
		iFactory.setInput(0, ray);
		iFactory.commit();	
		
	}

}

DoViewRaysThroughPoints();

EDITED: 3 Mar 2024 by PEER