Q4: Callbacks, Import Namespace's, Send or Socket-Programing

Tom G. Smith smitty at kcc.com
Fri Oct 29 09:29:22 EDT 1999


> 
> Hallo,
> 
> i would like to pass some variables to a tcl script that is  evaluated
> by vtk as follows:
> 
> #aVtkScript.tcl
> puts "$someName"
> #end aVtkScript.tcl
> 
> 
> #some tcl script that calls vtk via exec
> set someName toNobody
> exec vtk  aVtkScript.tcl
> #end some tcl script that calls vtk via exec
> 
> This dose not work since  "vtk  aVtkScript.tcl" lives in a different
> namespace.
> 
> Could you please tell me what is the best (or most pragmatic) way to
> pass the variable "someName" into "vtk  aVtkScript.tcl namespace".
> (Callbacks, Import Namespace's, Send or Socket-Programing )
> 
> Many thanks to you Now !
> 
> Sincerely, Alexander Kraemer
> 
-- 
I think you have a couple of choices.  Here's a sample script to illustrate:

	#!/usr/bin/sh
	cd /home/smitty/vtkstuff
	echo points with default radius
	./points.pl | vtk points_test
	echo points with radius .25
	./points.pl | vtk points_test -- -r .25
	echo points with radius 1.5
	export RADIUS=1.5
	./points.pl | vtk points_test

points_test is a Tcl script that puts a sphere at each point specified
on stdin.  I used a small perl script, points.pl, to generate
coordinates for points evenly distributed about the surface of a globe.
I've attached it, and several other examples you might find useful
at the end of this e-mail.

points_test first calculates the radius of each sphere based on the
range of coordinate values in the input, then looks for an override on
the command line, and finally checks for the environment (namespace)
variable RADIUS:

	set radius [expr ($max-$min)/10.0]
	if {$argc} {
		set radius [lindex $argv 0]
	}
	if {[info exists env(RADIUS)]} {
		set radius $env(RADIUS)
	}



........................................................................
points.pl:
	#!/usr/local/bin/perl
	$degrees=atan2(0,-1)/180;
	for($a=90; $a<=270; $a+=30) {
		$z=sin($a*$degrees);
		$radius=-cos($a*$degrees);
		for($b=0; $b<360; $b+=30) {
			$x=$radius*cos($b*$degrees);
			$y=$radius*sin($b*$degrees);
			print("$x $y $z\n");
			last if($radius<10**-13);
		}
	}

........................................................................
points:
	#!/usr/bin/tcl
	#-----------------------------------------------------------------------
	# Description:  This Tcl script, when run under vtk, visualizes a set
	# of points in 3D space, given their (x,y,z) coordinates on stdin.
	# The coordinates for one point should appear on each line of stdin,
	# blank-delimited.  A sample call sequence would be -
	#	echo 1 2 3 | vtk points
	# which causes the visualization of a single point, x=1, y=2, z=3.
	#-----------------------------------------------------------------------
	# Changelog:
	# 990928 Smitty created.
	#-----------------------------------------------------------------------
	
	proc dospheres {} {
	#-----------------------------------------------------------------------
	# Called to activate vtk objects to put spheres at each input point.
	#-----------------------------------------------------------------------
		global geometry radius
		vtkSphereSource geometry
		# vtkSphereSource creates a sphere (represented by polygons)
		# of specified radius centered at the origin. The resolution
		# (polygonal discretization) in both the latitude (phi) and
		# longitude (theta) directions can be specified. It also is
		# possible to create partial spheres by specifying maximum phi
		# and theta angles.
	
		# vtkSphereSource is of the superclass vtkPolyDataSource, which
		# is if the superclass vtkSource.
		#
		# Other vtkPolyDataSource types are -
		#
		#	vtkPolyDataReader, vtkAxes, vtkBYUReader, vtkConeSource
		#	vtkCubeSource, vtkCursor3D, vtkCyberReader, vtkCylinderSource
		#	vtkDiskSource, vtkLineSource, vtkMCubesReader, vtkOutlineSource
		#	vtkPlaneSource, vtkPointSource, vtkSTLReader, vtkSphereSource
		#	vtkTextSource, vtkUGFacetReader, vtkVectorText
		geometry SetRadius $radius
	} ;# End dospheres.
	
	# ---------------------------------------------------------------
	# Mainline starts here.
	source startup ;# Initialize vtk.
	source getpoints ;# Get the getpoints routine.
	getpoints ;# Read 3d point coordinates from stdin.
	source getopts; # Get the getopts and defaultopts routines.
	getopts {c/color/:r/radius/:}; # Get command line argument.
	dospheres ;# Display spheres at each point.
	
	vtkGlyph3D glyphs
		# vtkGlyph3D is a filter that copies a geometric representation
		# (called a glyph) to every point in the input dataset. The
		# glyph is defined with polygonal data from a source filter
		# input. The glyph may be oriented along the input vectors or
		# normals, and it may be scaled according to scalar data or
		# vector magnitude. More than one glyph may be used by creating
		# a table of source objects, each defining a different glyph. If
		# a table of glyphs is defined, then the table can be indexed
		# into by using either scalar value or vector magnitude. To
		# use this object you'll have to provide an input dataset and
		# a source to define the glyph. Then decide whether you want
		# to scale the glyph and how to scale the glyph (using scalar
		# value or vector magnitude). Next decide whether you want to
		# orient the glyph, and whether to use the vector data or normal
		# data to orient it. Finally, decide whether to use a table of
		# glyphs, or just a single glyph. If you use a table of glyphs,
		# you'll have to decide whether to index into it with scalar
		# value or with vector magnitude.
	  glyphs SetScaleModeToDataScalingOff
		# Without SetScaleModeToDataScalingOff, you get just one big sphere.
	  glyphs SetInput ugrid
		# Tell glyphs to get the locations from ugrid where each
		# sphere is to be placed.
	  glyphs SetSource [geometry GetOutput]
		# Tell glyphs that geometry is the source for the geometric object
		# to be drawn at each point described by input ugrid.
	
	vtkDataSetMapper glyphsMapper
	  glyphsMapper SetInput [glyphs GetOutput]
	vtkActor glyphsActor
	  glyphsActor SetMapper glyphsMapper
	ren1 AddActor glyphsActor ;# assign our actor to the renderer
	
	source go ;# start the Interactor and display the image.
	
........................................................................
startup:
	#!/usr/bin/tcl
	#-----------------------------------------------------------------------
	# Description:  This Tcl script can be sourced to get the typical
	# vtk initialization.
	#-----------------------------------------------------------------------
	# Changelog:
	# 991007 Smitty created.
	#-----------------------------------------------------------------------
	catch {load vtktcl} ;# Load the shared vtk libraries.
	source /opt/vtk/examplesTcl/vtkInt.tcl ;# Get the interactor ui.
	vtkRenderer ren1
		# vtkRenderer provides an abstract specification for renderers. A
		# renderer is an object that controls the rendering process for
		# objects. Rendering is the process of converting geometry,
		# a specification for lights, and a camera view into an
		# image. vtkRenderer also performs coordinate transformation
		# between world coordinates, view coordinates (the computer
		# graphics rendering coordinate system), and display coordinates
		# (the actual screen coordinates on the display device). 
	vtkRenderWindow renWin
		# vtkRenderWindow is an abstract object to specify the behavior
		# of a rendering window. A rendering window is a window
		# in a graphical user interface where renderers draw their
		# images. Methods are provided to synchronize the rendering
		# process, set window size, and control double buffering.
	  renWin AddRenderer ren1
		# Associate renderer ren1 with renWin.
	vtkRenderWindowInteractor iren
		# vtkRenderWindowInteractor is a convenience object that provides
		# event bindings to common graphics functions.  Here's a brief
		# summary.  See http://www.kitware.com/vtkhtml/vtkdata/manhtml/
		# vtkRenderWindowInteractor.html for more detail:
		# Mouse bindings:
		# 	camera: Button 1 - rotate
		# 		Button 2 - pan
		# 		Button 3 - zoom
		# 		ctrl-Button 1 - spin
		# 	actor:  Button 1 - rotate
		# 		Button 2 - pan
		# 		Button 3 - uniform scale
		# 		ctrl-Button 1 - spin
		# 		ctrl-Button 2 - dolly.
		# Keyboard bindings (upper or lower case):
		# j - joystick like mouse interactions
		# t - trackball like mouse interactions
		# o - object/actor interaction
		# c - camera interaction
		# r - reset camera view
		# w - turn all actors wireframe
		# s - turn all actors surface
		# u - execute user defined function
		# p - pick actor under mouse pointer (if pickable)
		# 3 - toggle in/out of 3D mode (if supported by renderer)
		# e - exit
		# q - exit
	  iren SetRenderWindow renWin
		# Associate renderwindow renWin with interactor iren.

........................................................................
getpoints:
	#!/usr/bin/tcl
	#-----------------------------------------------------------------------
	# Description:  When sourced in a Tcl script run under vtk, enables
	# subroutine getpoints that reads the (x,y,z) coordinates on stdin
	# for a set of points in 3D space. The coordinates for each point
	# should appear on one line of stdin, blank-delimited.
	#-----------------------------------------------------------------------
	# Changelog:
	# 991008 Smitty created.
	#-----------------------------------------------------------------------
	
	proc getpoints {} {
	#-----------------------------------------------------------------------
	# Called to read the (x,y,z) point coordinates from stdin, storing
	# them in global array vtkPoints object points.  These global
	# variables are set:
	# cells = vtkPolyVertex object.  Each cell contains the id of a point
	#	in object points, e.g. cell 0 has point 0, cell 1 has point 1,
	#	etc.
	# points = vtkPoints object containing (x,y,z) coordinates.
	# pointcount = the number of points read, i.e. the count of items in
	#	each of the arrays x, y, and z.
	# radius = the desired radius of the spheres that will represent each
	#	point in the scene.  The value is the magnitude of the range
	#	of coordinates, divided by 10.
	# ugrid = vtkUnstructuredGrid object.
	#-----------------------------------------------------------------------
		set names {x y z}
		foreach n $names {
			set $n {} ;# Initialize list to empty.
		}
		while {[gets stdin line] >= 0} {
			set i 0
			foreach n $names {
				set v [lindex $line $i] ;# Get value from input line.
				lappend $n $v ;# Append value to list.
				if {![info exists max] || $v > $max } {
					set max $v
				}
				if {![info exists min] || $v < $min } {
					set min $v
				}
				incr i
			}
		}
		global pointcount
		set pointcount [llength $x]
		global radius
		set radius [expr ($max-$min)/10.0] ;# radius of sphere at each point.
		# Put the points in vtkpoints object.
		global points
		vtkPoints points
			# vtkPoints represents 3D points. The data model for vtkPoints
			# is an array of vx-vy-vz triplets accessible by (point or
			# cell) id.
		points SetNumberOfPoints $pointcount
			# Subroutine getpoints (see above) set global $pointcount to
			# the number of (x,y,z) point coordinate sets it read from
			# stdin and stored in global arrays x, y, and z.  The following
			# loop uses method InsertPoint to add all of the coordinate
			# sets read from stdin to the vtkpoints object named points.
		set n 0
		while {$n < $pointcount} {
			points InsertPoint $n \
				[lindex $x $n] [lindex $y $n] [lindex $z $n]
			incr n
		}
	
		global cells
		vtkPolyVertex cells
			# vtkPolyVertex is a member of the superclass vtkPointSet,
			# which is a member of the abstract class vtkDataSet, which
			# is a member of the superclass vtkDataObject, and is
			# a concrete implementation of vtkCell to represent a set of
			# 3D vertices. 
		
			# vtkCell is an abstract class that specifies the
			# interfaces for data cells. Data cells are simple
			# topological elements like points, lines, polygons,
			# and tetrahedra of which visualization datasets are
			# composed. In some cases visualization datasets may
			# explicitly represent cells (e.g., vtkPolyData,
			# vtkUnstructuredGrid), and in some cases, the
			# datasets are implicitly composed of cells (e.g.,
			# vtkStructuredPoints).
	
		[cells GetPointIds] SetNumberOfIds $pointcount
			# You have to know all the class relationships
			# because method GetPointIds is associated
			# with class vtkCell, and on the html pages at
			# http://www.kitware.com/vtkhtml/vtkdata/manhtml/,
			# the only source for online documentation on vtk that
			# most closely resembles traditional man pages, you
			# find the description for GetPointIds under vtkCell,
			# and there is no reference to it under vtkPolyVertex,
			# the first place you'd most likely look for it.
	 
			# Further, there is no cross-reference for methods,
			# nor is there a search capability at kitware.com.
			# You have to scan up the hierarchy of classes in
			# order to find documentation on any inherited method.
	 
			# According to the man page, GetPointIds "For cell
			# point i, return the actual point id,"  but its C
			# declaration indicates it returns a pointer to an
			# object of type vtkIdList.  Apparently in this Tcl
			# context, the method GetpointIds of the vtkPolyVertex
			# object named cells returns a reference to an object
			# of type vtkIdList, and its method SetNumberOfIds
			# is then used to set the number of Ids in the list.
	
			# From the context, it wouldn't make sense that the
			# object of type vtkIdList is temporary
	
		set n 0
		while {$n < $pointcount} {
			[cells GetPointIds] SetId $n $n
			incr n
		}
	
		global ugrid
		vtkUnstructuredGrid ugrid
			# vtkUnstructuredGrid is a data object that is a concrete
			# implementation of vtkDataSet. vtkUnstructuredGrid represents
			# any combinations of any cell types. This includes 0D (e.g.,
			# points), 1D (e.g., lines, polylines), 2D (e.g., triangles,
			# polygons), and 3D (e.g., hexahedron, tetrahedron).
	
			# Dataset objects are the fundamental visualization data
			# types.  They are input and output from sources, filters,
			# and mappers.
	
			# vtkDataSet is an abstract class that specifies an interface
			# for dataset objects. vtkDataSet also provides methods to
			# provide information about the data, such as center, bounding
			# box, and representative length. In vtk a dataset consists of
			# a structure (geometry and topology) and attribute data. The
			# structure is defined implicitly or explicitly as a collection
			# of cells. The geometry of the structure is contained in
			# point coordinates plus the cell interpolation functions. The
			# topology of the dataset structure is defined by cell types
			# and how the cells share their defining points. Attribute data
			# in vtk is either point data (data at points) or cell data
			# (data at cells). Typically filters operate on point data,
			# but some may operate on cell data, both cell and point data,
			# either one, or none.
	
		ugrid Allocate 1 1
			# 1st arg is size of connectivity list.
			# 2nd arg is amount to extend storage (if necessary).
		ugrid InsertNextCell [cells GetCellType] [cells GetPointIds]
		ugrid SetPoints points
	} ;# End getpoints.

........................................................................
getopts:
	#!/usr/bin/tcl
	#-----------------------------------------------------------------------
	# Description:  When sourced in a Tcl script run under vtk, enables
	# subroutine getopts that reads the command line arguments and
	# sets global variables accordingly, and defaultopt that can be
	# invoked to set a default.
	#-----------------------------------------------------------------------
	# Changelog:
	# 991013 Smitty created.
	#-----------------------------------------------------------------------
	
	proc defaultopt {opt {default 0}} {
	#-----------------------------------------------------------------------
	# Called to set the default for a command line argument.
	#-----------------------------------------------------------------------
		upvar $opt t
		if {![info exists t]} {
			set t $default
		}
	} ;# End defaultopt.
	
	proc getopts {optstring} {
	#-----------------------------------------------------------------------
	# Called to get the command line arguments.
	# optstring contains the option letters to be recognized.
	# ->	Each option letter may optionally be followed by a slash-delimited
	#	name.  If the option letter is found on the command line, the
	#	global variable with that name will either be set
	#	to the argument (see below), or if there is no argument expected,
	#	will be set to 1 to indicate the option letter was found.
	#	If not supplied, the name used will be the option letter itself.
	# ->	If a letter, and possibly its slash-delimited name (see above) is
	#	followed by a colon, the option is expected to
	#	have an argument, which should be separated from it by white
	#	space on the command line.
	# ->	One or more semicolons at the end of optstring each signify
	#	positional parameters.  Values for positional parameters will
	#	be set to corresponding locations in global list pos.
	# Examples:
	#-----------------------------------------------------------------------
		global argc argv
	
		set a 0
		while {$a < $argc} {
			set arg [lindex $argv $a]
			incr a
			if {0 != [string first - $arg]} break
			set b 1
			while {$b < [string length $arg]} {
				set optletter [string index $arg $b]
				incr b
				set a [getopts_sub $optstring $optletter $a]
			}
		}
	} ;# End getopts.
	
	proc getopts_sub {optstring optletter a} {
	#-----------------------------------------------------------------------
	# Called from getopts to process an option letter parsed from the
	# command line. If the option has an argument, it will be extracted
	# from $argv, and the index $a+1 will be returned.  Otherwise index $a
	# will be returned.
	#-----------------------------------------------------------------------
		global argc argv
	 
		set match 0; # Indicates optletter matched in optstring.
		set state 0; # Looking for option letter in optstring.
		set b 0
		while {$b < [string length $optstring]} {
			set letter [string index $optstring $b]
			incr b
			switch -exact -- $state {
				0 { ;# Looking for matching option letter.
					if {0 == [string compare $letter ";"]} break
					if {0 == [string compare $letter $optletter]} {
						set match 1
						set name $letter; # Default name.
						set value 1; # Default value.
					}
					set state 1; # Look for slash.
				  }
				1 { ;# Looking for slash.
					if {0 == [string compare $letter /]} {
						set name {}; # Empty out default name.
						while {$b < [string length $optstring]} {
							set letter [string index $optstring $b]
							incr b
							if {0 == [string compare $letter /]} break; # Found end of name.
							if {$b == [string length $optstring]} {
								puts "ERROR: missing trailing slash"
								exit 1
							}
							set name "$name$letter"
						}
					} else {
						incr b -1; # Back up parse cursor.
					}
					set state 2; # Look for colon.
				  }
				2 { ;# Looking for colon.
					if {0 == [string compare $letter {:}]} {
						if {$match} {
							if {$a == $argc} {
								puts "ERROR: $name has no argument"
								exit 1 
							}
							set value [lindex $argv $a]
							incr a
							break; # All done.
						}
						set state 0; # Look for next option.
					} else {
						if {$match} break
						set state 0; # Look for next option.
						incr b -1; # Back up parse cursor.
					}
				  }
			} ;# End switch.
		}
		if {!$match} {
			puts "ERROR: $optletter is an unknown option."
			exit 1
		}
		upvar #0 $name t
		set t $value
		return $a
	} ;# End getopts_sub.

........................................................................
go:
	#!/usr/bin/tcl
	#-----------------------------------------------------------------------
	# Description:  This Tcl script can be sourced to get the typical
	# vtk code to start the interactor, and to display the final image.
	#-----------------------------------------------------------------------
	# Changelog:
	# 991013 Smitty created.
	#-----------------------------------------------------------------------
	iren SetUserMethod {wm deiconify .vtkInteract}; # Enable user interactor.
	iren Initialize; # render the image
	wm withdraw .;  # prevent tk window from showing up, then start the event loop.
	


-----------------------------------------------------------------------------
This is the private VTK discussion list.  Please keep messages on-topic.
Check the FAQ at: <http://www.automatrix.com/cgi-bin/vtkfaq>
To UNSUBSCRIBE, send message body containing "unsubscribe vtkusers" to
<majordomo at gsao.med.ge.com>.  For help, send message body containing
"info vtkusers" to the same address.     Live long and prosper.
-----------------------------------------------------------------------------




More information about the vtkusers mailing list