Purpose of this example
This example demonstrates 3D point transformations using p-Shell matrix operations and illustrates how geometric calculations can be performed without implementing the underlying coordinate arithmetic in Tcl.
The mesh subdivision algorithm is specifically designed for closed volumes consisting of triangular faces with shared edges. It uses an octahedron as its starting geometry and projects newly created edge midpoints onto a unit sphere. It is not intended as a general-purpose mesh subdivision algorithm.
The example also demonstrates how Tcl can be used to organize the application logic while delegating computational geometry operations to p-Shell's native commands.
This example is based on the Tcl Wiki article 3D polyhedra with simple tk canvas. The original implementation has been adapted to use p-Shell point, line and matrix operations instead of performing the geometric calculations directly in Tcl.
The example runs smoothly on my computer with 2,048 faces, 1,026 vertices and 6,144 edges.
Projection Method:
This example uses parallel (orthographic) projection, which is commonly used in CAD applications because it preserves geometric proportions without perspective distortion. Although p-Shell's matrix operations also support perspective transformations, they are not used here.
More information you will find here: Tcl for Creo
#
# Just a simple example how to use it
#
proc Simple {} {
# Create the Matrix, the Point to Transform and the Euler Value
ps_matrix Matrix
ps_point P1 -x 10 -y 0 -z 0
ps_point PE -x 0 -y 0 -z 90
PE set_euler_angles_to_rot_matrix Matrix
P1 transform Matrix PT
# Rotate P1 by 90 degrees around the Z axis.
# Expected result: 0.0 10.0 0.0
set res [PT 3d]
return $res
}
Simple
# Output: 0.0 10.0 0.0
Next, the help output for the MatrixObj and PointObj commands.
ps_point p1
p1
p1 -help
Command options for p1 are:
cget Option
configure ?Option?
transform matrixObj resultPointObj
rotate_vector matrixObj resultPointObj
copy resultPointObj
product point2Obj
angle point2Obj
lenght
normalize
cross_product point2Obj resultPointObj
dircos
add point2Obj ?resultPointObj?
move point2Obj resultPointObj
diff point2Obj resultPointObj
2d_values XY_List
3d_values XYZ_List
multiply matrixObj resultPointObj
is_parallel_to point2Obj
equal point2Obj
incrx DoubleVal
incry DoubleVal
incrz DoubleVal
reset
dot_product point2Obj
set_euler_angles_to_rot_matrix matrixObj
scale DoubleVal
distance csysObj
-help
ps_matrix matrix
matrix
Command options for matrix are:
cget Option
configure Option ?Value?
rot2d angle
invert
normalize ?matrixOut?
reset
identity
copy matrixOut
product matrixObj ?matrixOut?
row_0_set 00Val 01Val 02Val
row_1_set 10Val 11Val 12Val
row_2_set 20Val 21Val 22Val
projection_set 03Val 13Val 23Val
col_0_set 00Val 10Val 20Val
col_1_set 01Val 11Val 21Val
col_2_set 02Val 12Val 22Val
origin_set 30Val 31Val 32Val
scale_set 33Val
x_to_vector pointObj
y_to_vector pointObj
z_to_vector pointObj
origin_to_vector pointObj
x_from_vector pointObj
y_from_vector pointObj
z_from_vector pointObj
origin_from_vector pointObj
shift_to_vector pointObj
shift_from_vector pointObj
scale_xyz ScaleValue
get_euler_angles_from_rot_matrix PointAngleObj
set_euler_angles_to_rot_matrix PointAngleObj
is_orthogonale
jacobi3 PointEigenValuesObj MatrixEigenVectorsObj
-help Here is the final adapted code:
#
##l https://wiki.tcl-lang.org/page/3D+polyhedra+with+simple+tk+canvas| Original Code
#
##+ "Model Set and Activate"
#
# ps_Model_Data_Activate
#
# Main callback for displaying the data.
# this is called if a model type is picked
# Initializes the display and starts the rotation loop.
#
# Step 1
# Get all vertices, the face definitions and their color values.
# Step 2
# Calculate the face normals and dot products.
# Step 3
# Create the initial canvas polygons.
# Store the model data globally for access by the display loops.
# Using arrays avoids passing thousands of list elements as arguments.
# Rotation Loop
# Step 1
# Calculate the transformation for each point
# Step 2
# Get the color for each face
# Step 3
# Configure the item coordinates within the canvas
# And make sure to Incr the rotation angle for the next display
proc ps_Model_Data_Activate {c DataSet} {
global stop
global display
global ax ay az tx ty tz
global form
global iterations
# stop current running loop
# and do a clean up
after cancel $::run
$c delete all
set stop 0
# Step 1
# Get all verticies
# The face triangles linked with the verticies
# and a color value list
foreach {VertexList FaceVerticesList FaceColorList} [ps_Model_Data_Read $c $DataSet] {}
# get the normals
# and the dot products
foreach {FaceNormalList FaceDotProductList} [ps_Face_Normals_Get $FaceVerticesList ] {}
# Get the Initial Polygons for the canvas
set FacePolygonList [ps_Canvas_Polygons_Get $c $d $FaceVerticesList $FaceColorList]
# use an array rather to get thousands of list elements in one argument
set ::APP_GLOB(VertexList) $VertexList
set ::APP_GLOB(FaceVerticesList) $FaceVerticesList
set ::APP_GLOB(FaceNormalList) $FaceNormalList
set ::APP_GLOB(FaceDotProductList) $FaceDotProductList
set ::APP_GLOB(FacePolygonList) $FacePolygonList
# just decide which Display Type to use
if { $display eq "Wireframe" } {
set ::run [after 0 [list ps_WireFrame_Loop $c ]]
} else {
set ::run [after 0 [list ps_Shaded_Loop $c ]]
}
}
#
# Data structure for models with vertices and connectivity
# -------------------------------------------------------------------
#
proc ps_Model_Data_Read {c DataSet } {
set VertexList {}
set FaceVerticesList {}
set FaceColorList {}
set txt ""
switch $DataSet {
tetrahedron {
set txt "tetrahedron: 4 faces 4 vertices 5 edges"
set a [expr {1.0/sqrt(3.0)}]
# Create the point Data
Point_Init p0 $a $a $a
Point_Init p1 $a -$a -$a
Point_Init p2 -$a $a -$a
Point_Init p3 -$a -$a $a
# A list of all points or vertices
set VertexList [list p0 p1 p2 p3]
# A lface list in a list of points
set FaceVerticesList {
{p0 p3 p1}
{p2 p0 p1}
{p3 p0 p2}
{p1 p3 p2}
}
}
cube {
set txt "cube: 6 faces 8 vertices 12 edges"
Point_Init p0 +0.7 +0.7 +0.7
Point_Init p1 -0.7 +0.7 +0.7
Point_Init p2 -0.7 -0.7 +0.7
Point_Init p3 +0.7 -0.7 +0.7
Point_Init p4 +0.7 +0.7 -0.7
Point_Init p5 -0.7 +0.7 -0.7
Point_Init p6 -0.7 -0.7 -0.7
Point_Init p7 +0.7 -0.7 -0.7
set VertexList [list p0 p1 p2 p3 p4 p5 p6 p7 ]
set FaceVerticesList {
{p4 p7 p6 p5}
{p0 p1 p2 p3}
{p3 p2 p6 p7}
{p4 p5 p1 p0}
{p0 p3 p7 p4}
{p5 p6 p2 p1}
}
}
octahedron {
set txt "octahedron 8 faces 6 vertices 16 edges"
foreach {VertexList FaceVerticesList} [Octahedron_Model_Data_Get] {}
}
spheremesh {
global Segments
unset -nocomplain Segments
foreach {VertexList FaceVerticesList} [Octahedron_Model_Data_Get] {}
# the value here can be changed
# This will result in 2,048 faces, 1,026 vertices and 6,144 edges.
# from 8 -32 -128 - 512 - 2048
set RecursLevel 4
# used later
ps_line $::APP_GLOB(LINE.MIDPNT)
for {set i 0} {$i < $RecursLevel} {incr i} {
set NewFaceVerticesList {}
set NewVertexList $VertexList
foreach FaceVertices $FaceVerticesList {
# Debug "-------------------" yellow
foreach {MidVertexList NewMeshList} [Octahedron_Face_Mesh_Divide $FaceVertices] {}
# Debug_Var MidVertexList NewMeshList
lappend NewFaceVerticesList {*}$NewMeshList
lappend NewVertexList {*}$MidVertexList
set nf [llength $NewFaceVerticesList]
set nv [llength $NewVertexList]
# Debug_Var nv NewVertexList nf NewFaceVerticesList
}
set VertexList $NewVertexList
set FaceVerticesList $NewFaceVerticesList
# Debug_Var VertexList FaceVerticesList
}
set txt "spheremesh $nf faces $nv vertices [expr {$nf*3} ] edges"
Break
}
dodecahedron {
set txt "dodecahedron 12 faces 20 vertices 30 edges"
set s3 [expr sqrt(3)]
set s5 [expr sqrt(5)]
set alpha [expr {sqrt(2.0/(3 + $s5))/$s3}]
set beta [expr {(1.0 + sqrt(6.0/(3 + $s5) - 2 + 2*sqrt(2.0/(3.0 + $s5))))/$s3}]
set gamma [expr {1.0/$s3}]
Point_Init p0 -$alpha 0 $beta
Point_Init p1 $alpha 0 $beta
Point_Init p2 -$gamma -$gamma -$gamma
Point_Init p3 -$gamma -$gamma $gamma
Point_Init p4 -$gamma $gamma -$gamma
Point_Init p5 -$gamma $gamma $gamma
Point_Init p6 $gamma -$gamma -$gamma
Point_Init p7 $gamma -$gamma $gamma
Point_Init p8 $gamma $gamma -$gamma
Point_Init p9 $gamma $gamma $gamma
Point_Init p10 $beta $alpha 0
Point_Init p11 $beta -$alpha 0
Point_Init p12 -$beta $alpha 0
Point_Init p13 -$beta -$alpha 0
Point_Init p14 -$alpha 0 -$beta
Point_Init p15 $alpha 0 -$beta
Point_Init p16 0 $beta $alpha
Point_Init p17 0 $beta -$alpha
Point_Init p18 0 -$beta $alpha
Point_Init p19 0 -$beta -$alpha
set VertexList [list p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 p12 p13 p14 p15 p16 p17 p18 p19 ]
set FaceVerticesList {
{p0 p1 p9 p16 p5}
{p1 p0 p3 p18 p7}
{p1 p7 p11 p10 p9}
{p11 p7 p18 p19 p6}
{p8 p17 p16 p9 p10}
{p2 p14 p15 p6 p19}
{p2 p13 p12 p4 p14}
{p2 p19 p18 p3 p13}
{p3 p0 p5 p12 p13}
{p6 p15 p8 p10 p11}
{p4 p17 p8 p15 p14}
{p4 p12 p5 p16 p17}
}
}
icosahedron {
set txt "icosahedron: 20 faces 12 vertices 30 edges"
set X 0.525731112119133606
set Z 0.850650808352039932
Point_Init p0 -$X 0.0 $Z
Point_Init p1 $X 0.0 $Z
Point_Init p2 -$X 0.0 -$Z
Point_Init p3 $X 0.0 -$Z
Point_Init p4 0.0 $Z $X
Point_Init p5 0.0 $Z -$X
Point_Init p6 0.0 -$Z $X
Point_Init p7 0.0 -$Z -$X
Point_Init p8 $Z $X 0.0
Point_Init p9 -$Z $X 0.0
Point_Init p10 $Z -$X 0.0
Point_Init p11 -$Z -$X 0.0
set VertexList [list p0 p1 p2 p3 p4 p5 p6 p7 p8 p9 p10 p11 ]
set FaceVerticesList {
{p4 p0 p1}
{p9 p0 p4}
{p5 p9 p4}
{p5 p4 p8}
{p8 p4 p1}
{p10 p8 p1}
{p3 p8 p10}
{p3 p5 p8}
{p2 p5 p3}
{p7 p2 p3}
{p10 p7 p3}
{p6 p7 p10}
{p11 p7 p6}
{p0 p11 p6}
{p1 p0 p6}
{p1 p6 p10}
{p0 p9 p11}
{p11 p9 p2}
{p2 p9 p5}
{p2 p7 p11}
}
}
}
set DefColor "0000[format %2.2x 255]"
foreach item $FaceVerticesList {
lappend FaceColorList $DefColor
}
set ::TEXT $txt
set ::TEXTID [$c create text $::TEXTX $::TEXTY -anchor w -fill white -text $txt]
return [list $VertexList $FaceVerticesList $FaceColorList]
}
##-
##+ {Octahedron Calls}
#
# /\
# /__\
# /\ /\
# /__\/__\
#
# This example demonstrates how to create a spherical mesh by subdividing
# the eight triangular faces of an octahedron. Each face is divided into four
# smaller triangles. New edge midpoints are calculated using p-Shell point
# and line operations and normalized to maintain a unit sphere.
# Shared edges are detected and reused to avoid duplicate vertices.
# The algorithm assumes an original radius of 1.0; otherwise, the resulting
# coordinates must be scaled accordingly.
#
# This procedure divides one triangle into four smaller triangles.
# The face is defined by three vertices.
# Calculate the midpoint of each edge and extend it to a length of 1.0.
# The resulting point lies on the sphere.
# Each new midpoint is shared by two faces:
#
# Each new midpoint belongs to three of the four new resulting triangles.
# In total at the end, one point is shared with 6 triangles.
# Faces are defined counterclockwise, with the normal pointing outwards.
# Only newly created midpoints are returned.
# Each vertex is shared by six faces.
proc Octahedron_Face_Mesh_Divide {FaceVertices} {
global Segments
# ShortCut, this obj is reused
set LineMidPnt $::APP_GLOB(LINE.MIDPNT)
# just get the point vars
foreach {P1 P2 P3} $FaceVertices {}
# This may empty on return
set NewMidPoints [list]
# Get the first Start
set StartVertex [lindex $FaceVertices 0]
# and put the first at the end for looping
# P1 P2 P3 P1
lappend FaceVertices $StartVertex
# Init the List of Mid Points
set MidPoints [list]
# Now run from P2 over P3 and end at P1
# -> P1 P2 + P2 P3 + P3 P1
foreach EndVertex [lrange $FaceVertices 1 end] {
# Debug "-------------------" lightblue
set start $StartVertex
set end $EndVertex
set idx $StartVertex.$EndVertex
set idxr $EndVertex.$StartVertex
if { [info exists Segments($idx)] } {
# Debug "idx $idx exists" green
lappend MidPoints $Segments($idx)
} elseif { [info exists Segments($idxr)] } {
# Debug "idxr $idxr (idx $idx) exists" orange
set idx $idxr
lappend MidPoints $Segments($idx)
} else {
# Debug "idx not exists $start <-> $end" red
set SegmentID [incr Segments(ID)]
set pnt m$SegmentID
set Segments($idx) $pnt
#
#Hack with join but no quotes
#
$LineMidPnt 3d [join [list [$start 3d] [$end 3d] ] ]
# get mid point
$LineMidPnt uval 0.5 $pnt
# extent to reach the sphere diameter of 1.0
$pnt normalize
# add to our mid point list
lappend MidPoints $pnt
# A new Mid Point Vertex
lappend NewMidPoints $pnt
}
# next start is current end
set StartVertex $EndVertex
}
# Prepare to use
foreach {M1 M2 M3} $MidPoints {}
# Create Unique Segments
# counter clock wise
set NewMeshList [list [list $P1 $M1 $M3 ] [list $P2 $M2 $M1 ] [list $P3 $M3 $M2 ] [list $M1 $M2 $M3 ] ]
return [list $NewMidPoints $NewMeshList]
}
#
# 8 flat surfaces, with radius 1.0
#
proc Octahedron_Model_Data_Get {} {
Point_Init p0 +1.0 +0.0 +0.0
Point_Init p1 0.0 +1.0 0.0
Point_Init p2 -1.0 0.0 0.0
Point_Init p3 0.0 -1.0 0.0
Point_Init p4 0.0 0.0 1.0
Point_Init p5 0.0 0.0 -1.0
set VertexList [list p0 p1 p2 p3 p4 p5 ]
set FaceVerticesList {
{p0 p1 p4}
{p1 p2 p4}
{p2 p3 p4}
{p3 p0 p4}
{p1 p0 p5}
{p2 p1 p5}
{p3 p2 p5}
{p0 p3 p5}
}
return [list $VertexList $FaceVerticesList]
}
##-
##+ "Normals and Colors"
# Compute normal vector and norm for each face
# this vector is later transformed
# a face is one triangle
# FaceNormalList contains the normal-vector objects.
# FaceDotProductList contains the squared lengths of those normals.
# the normal len is sqrt(FaceDotProductList[i]).
# -------------------------------------------------------------------
proc ps_Face_Normals_Get {FaceVerticesList} {
set FaceNormalList {}
set FaceDotProductList {}
# Debug_Var faces
set fn -1
foreach FaceVertex $FaceVerticesList {
# Debug_Var FaceVertex
foreach {vec1 vec2 vec3} $FaceVertex {
# Debug_Var vec1 vec2 vec3
# prepare the name for the Normal
set normal pn.face[incr fn]
# move to origin of vec1
$vec2 diff $vec1 vecu
$vec3 diff $vec1 vecv
# get the normal
vecu cross_product vecv $normal
# and append to the list
lappend FaceNormalList $normal
#
# Vector Dot Product inclding a numerical safeguard for small values
#
lappend FaceDotProductList [$normal dot_product $normal ]
# stop if we have more than 3
break
}
}
return [list $FaceNormalList $FaceDotProductList]
}
# Compute diffuse light intensity for each face.
# Returns values from 0.0 (unlit) to 1.0 (fully lit).
# This implements Lambertian diffuse lighting: the dot product measures
# how directly a face points toward the light.
# Negative values become zero, and the result is clamped to the range 0–1
proc ps_Face_Color_Intensity_Get {FaceNormalList FaceDotProductList LightVector} {
set Intensities {}
set lightLen2 [$LightVector dot_prod $LightVector]
if {$lightLen2 <= 0.0} {
error "LightVector can not have zero or less length"
}
foreach normal $FaceNormalList normalLen2 $FaceDotProductList {
set dot [$normal dot_prod $LightVector]
if {$normalLen2 <= 0.0} {
set intensity 0.0
} else {
set intensity [expr {
max(0.0, min(1.0,
$dot / sqrt($normalLen2 * $lightLen2))
)
}]
}
lappend Intensities $intensity
}
# Debug_Var Intensities
return $Intensities
}
##-
##+ Canvas
# Initialization of canvas with polygonal objects filled or not
# -------------------------------------------------------------------
proc ps_Canvas_Polygons_Get {c d FaceVerticesList FaceColorList} {
# Init the Euler Rotation Values
# for the first transforamtion matrix
set pnt $::APP_GLOB(ROT.VALUES)
ps_point $pnt
$pnt config -x $::APP_GLOB(ROT.DEF.X) -y $::APP_GLOB(ROT.DEF.Y) -z $::APP_GLOB(ROT.DEF.Z)
# Debug_Var FaceVerticesList FaceColorList
set FacePolygonList {}
set FirstItem [lindex $FaceVerticesList 0]
set n [llength $FirstItem ]
set InitialCoords [string repeat " 0" [expr {2*$n}]]
if {$d == "Shaded"} then {
# The number of points per face are alwasy equal
# for a triangle with 3 points we have 6 times 0.0
# Create the initial cancas Items
foreach cnx $FaceVerticesList FaceColor $FaceColorList {
# the polygon
set id [$c create polygon $InitialCoords -fill #$FaceColor -tags "geom poly"]
# add to the list
lappend FacePolygonList $id
}
} else {
foreach cnx $FaceVerticesList {
set id [$c create polygon $InitialCoords -fill black -tags "geom poly" -outline blue]
lappend FacePolygonList $id
}
}
return $FacePolygonList
}
##-
##+ Display Loops
# Flat shaded display with gradient color
# c Our Canvas Widget
# VertexList the vertex list
# FaceVerticesList the list of contours/faces
# FacePolygonList the canvas ids
# FaceNormalList the normals
# FaceDotProductList the normals dot values
# -------------------------------------------------------------------
proc ps_Shaded_Loop {c} {
if {$::stop} return
# use an array rather to get thousands of list elements in one argument
set VertexList $::APP_GLOB(VertexList)
set FaceVerticesList $::APP_GLOB(FaceVerticesList)
set FaceNormalList $::APP_GLOB(FaceNormalList)
set FaceDotProductList $::APP_GLOB(FaceDotProductList)
set FacePolygonList $::APP_GLOB(FacePolygonList)
global iterations
global ax ay az
$c delete circ
set SurfColors {}
foreach {RotMatrix VertexRotList FaceNormalRotList} [ps_Model_Data_Transform $VertexList $FaceNormalList] {}
# Light vector is set to <1 1 -1>
ps_point light.vect -x 1 -y 1 -z -1
set Intensities [ps_Face_Color_Intensity_Get $FaceNormalRotList $FaceDotProductList light.vect ]
# Light vector is set to <1 1 -1>
foreach Intensity $Intensities {
# Ambient blue: 40
# Additional diffuse blue: 215
# max sum is 255 = ff
set col [expr {round(40 + 215*$Intensity)}]
lappend SurfColors [format "#0000%02X" $col]
}
# Wireframe: -fill {} makes the faces transparent, so you can see the mesh lines.
# Shaded: -outline {} removes the edges, leaving only the filled surfaces.
# And hiding all geom items at the beginning of the shaded loop ensures that
# back-facing polygons don't remain visible from the previous wireframe frame.
# Now show only the faces that pass your backface culling.
# In Wireframe we see everything
#default, eliminate an else
$c itemconfigure geom -outline {} -state hidden
#
# No lindex just loop the list vars
#
foreach FaceVertex $FaceVerticesList \
FaceNormalRot $FaceNormalRotList \
FacePolygon $FacePolygonList \
SurfColor $SurfColors {
# get the rotated coords list
set lcoords {}
foreach Vertex $FaceVertex {
lappend lcoords [$Vertex.rot 2d]
}
# Backface culling for hidden face
set zVal [$FaceNormalRot cget -z]
if {$zVal < 0} {
# for display a small circle on each vertex
#foreach {x y} [join $lcoords] {
# Circle $x $y 2 -fill green
#}
# Update the canvas triangle
$c coords $FacePolygon [join $lcoords]
$c itemconfigure $FacePolygon -fill $SurfColor -outline {} -state normal
$c raise $FacePolygon
}
}
# this is to support the switch withput stopping
if { $::display eq "Wireframe" } {
set ::run [after $::speed [list ps_WireFrame_Loop $c ]]
} else {
set ::run [after $::speed [list ps_Shaded_Loop $c ]]
}
}
proc ps_WireFrame_Loop {c} {
if {$::stop} return
# use an array rather to get thousands of list elements in one argument
set VertexList $::APP_GLOB(VertexList)
set FaceVerticesList $::APP_GLOB(FaceVerticesList)
set FaceNormalList $::APP_GLOB(FaceNormalList)
set FaceDotProductList $::APP_GLOB(FaceDotProductList)
set FacePolygonList $::APP_GLOB(FacePolygonList)
$c delete circ
foreach {RotMatrix VertexRotList FaceNormalRotList} [ps_Model_Data_Transform $VertexList $FaceNormalList] {}
# This will configure the current shaded ones
$c itemconfigure geom -state normal -fill {}
#
# No lindex just loop the list vars
#
foreach FaceVertex $FaceVerticesList \
FaceNormalRot $FaceNormalRotList \
FacePolygon $FacePolygonList {
# get the rotated coords list
set lcoords {}
foreach Vertex $FaceVertex {
lappend lcoords [$Vertex.rot 2d]
}
#foreach {x y} [join $lcoords] {
# Circle $x $y 2 -fill green
#}
# Update the canvas triangle
$c coords $FacePolygon [join $lcoords]
$c itemconfigure $FacePolygon -fill {} -outline #CC00AA
}
# this is to support the switch withput stopping
if { $::display eq "Wireframe" } {
set ::run [after $::speed [list ps_WireFrame_Loop $c ]]
} else {
set ::run [after $::speed [list ps_Shaded_Loop $c ]]
}
}
##n Main Rotation
#
# Apply transformations to vertex coordinates and normals
# -------------------------------------------------------------------------
# The original model data remains unchanged.
# Each iteration creates transformed copies of the vertices
# and normals using the current rotation matrix.
proc ps_Model_Data_Transform {VertexList FaceNormalList} {
global ax ay az
set VertexRotList {}
set FaceNormalRotList {}
# Compute matrix rotation
# With pntEul set the rotation Matrix
# the values for x,y and z are kept in the range of 0 to 360 on this call
# ShortCut
set RotMatrix $::APP_GLOB(ROT.MATRIX)
set pntEul $::APP_GLOB(ROT.VALUES)
$pntEul set_euler_angles_to_rot_matrix $RotMatrix
#
# Now Rotate the Euler Point a bit
# So the first Value is not already transforrmed
# on matrix set
# the value is kept in the range of 0 to 360
# so we don't get a huge value
#
$pntEul incrx -2
$pntEul incry -2
$pntEul incrz +3
# This currently hardoded
$RotMatrix scale_set 200
# Apply projection
# append .rot to the name
# -> for each Vertex we get Vertex.rot
#
foreach Vertex $VertexList {
set VertexRot $Vertex.rot
$Vertex transform $RotMatrix $VertexRot
lappend VertexRotList $VertexRot
}
# append .rot to the name
# -> for each Normal we get Normal.rot
# # Normal vector rotation
foreach FaceNormal $FaceNormalList {
set FaceNormlRot $FaceNormal.rot
$FaceNormal rotate $RotMatrix $FaceNormlRot
lappend FaceNormalRotList $FaceNormlRot
}
return [list $RotMatrix $VertexRotList $FaceNormalRotList]
}
##-
##+ "GUI Building Block"
##n Main Call to Start the App
proc ps_Main {} {
# global APP_GLOB
# Debug "In ps_Main"
global stop
global display
global scx scy vdist speed
set ::run {}
set w .tdc
catch {destroy $w}
toplevel $w
wm withdraw .
wm title $w "Rotating polyhedra in Tk canvas "
set display Shaded
set scx 420
set scy 420
set vdist 1200
set ::scaspeed 40
set ::speed 40
set ::TEXT {}
set ::TEXTID {}
set ::APP_GLOB(ROT.VALUES) pntEul
set ::APP_GLOB(ROT.MATRIX) matRot
# First/Init Rotation/Euler Values
set ::APP_GLOB(ROT.DEF.X) 45
set ::APP_GLOB(ROT.DEF.Y) 45
set ::APP_GLOB(ROT.DEF.Z) 60
set ::APP_GLOB(CANVAS) $w.c
# Static line to calc a midpoint
set ::APP_GLOB(LINE.MIDPNT) GetMidPoint
set canv $w.c
# pack [canvas $w.c -width $scx -height $scy -bg white -bg black -bd 0 -bg #222] -expand y -fill both
pack [canvas $w.c -bg white -bg #555 -bd 0 -bg #222] -expand y -fill both
# $w.c delete all
bind $w.c <Destroy> {
after cancel $::run
}
set f1 [frame $w.f1 -relief sunken -borderwidth 2]
pack $f1 -fill x
button $f1.brun -text Stop -command {set stop 1}
button $f1.bq -text Quit -command exit
label $f1.l1 -text " "
radiobutton $f1.rbs -text "Shaded" -variable display -value Shaded
radiobutton $f1.rbw -text "Wireframe" -variable display -value Wireframe
pack {*}[winfo children $f1] -side left
set f2 [frame $w.f2 -relief sunken -borderwidth 2]
pack $f2 -fill x
foreach DataSet {tetrahedron cube octahedron dodecahedron icosahedron spheremesh} {
button $f2.b$DataSet -text $DataSet -command "ps_Model_Data_Activate $canv $DataSet"
}
pack {*}[winfo children $f2] -side left
set f3 [frame $w.f3 -relief sunken -borderwidth 2]
pack $f3 -fill x
label $f3.l1 -text "View distance " -width 12
scale $f3.sca -from 300 -to 1600 -length 300 \
-orient horiz -bd 1 -showvalue true -variable vdist
pack {*}[winfo children $f3] -side left
set f4 [frame $w.f4 -relief sunken -borderwidth 2]
pack $f4 -fill x
label $f4.l1 -text "Speed " -width 12
scale $f4.speed -from 1 -to 99 -length 300 \
-orient horiz -bd 1 -showvalue true -variable scaspeed \
-command {set speed [expr {100-$scaspeed}];#}
pack {*}[winfo children $f4] -side left
Circle 0 0 20 -fill red -tags CENTER
bind $::APP_GLOB(CANVAS) <Configure> [list Configure_Callback %W]
}
proc Configure_Callback {c} {
# Debug_Var c
set ww [winfo width $c]
set wh [winfo height $c]
set w [$c cget -width]
set h [$c cget -height]
set w2 [expr {$ww/2}]
set h2 [expr {$wh/2}]
# Debug_Var wh w h w2 h2
set offset 20
set ::TEXTX [expr {-$w2+20}]
set ::TEXTY [expr {-$h2+20}]
set scrollregion [list -$w2 -$h2 $w2 $h2 ]
set outline [list [expr {-$w2+$offset}] [expr {-$h2+$offset}] [expr {$w2-$offset}] [expr {$h2-$offset}] ]
# Debug "scrollregion $scrollregion"
# Debug "outline $outline"
$c config -scrollregion $scrollregion
$c delete OUTLINE
# Wait 200
eval $c create rectangle $outline -tag OUTLINE -outline green
#Redraw the text
$c coords $::TEXTID $::TEXTX $::TEXTY
}
##-
##+ Util and Dump Items Code
proc Point_Init {p x y z} {
ps_point $p -x $x -y $y -z $z
}
proc Circle {x y {r 10} args} {
# Debug_Var x y r
set x1 [expr {$x - $r}]
set y1 [expr {$y - $r}]
set x2 [expr {$x + $r}]
set y2 [expr {$y + $r}]
set itemid [eval $::APP_GLOB(CANVAS) create oval $x1 $y1 $x2 $y2 $args ]
$::APP_GLOB(CANVAS) itemconfig $itemid -tags "geom circ"
# Debug "circ itemid $itemid"
return $itemid
}
proc Line_Dump {lineObj {txt {}} } {
return
# Debug "Line Dump $lineObj"
set startlineObj LineStartObj
set endlineObj LineEndObj
foreach {x1 y1 z1 x2 y2 z2} [$lineObj 3d] {
set x1d [format %+.3f $x1]
set y1d [format %+.3f $y1]
set z1d [format %+.3f $z1]
set x2d [format %+.3f $x2]
set y2d [format %+.3f $y2]
set z2d [format %+.3f $z2]
}
# Debug "Line ($lineObj) Note: $txt"
# Debug "Start $x1d $y1d $z1d"
# Debug "End $x2d $y2d $z2d"
}
proc Point_Dump {pointObj {txt {}} } {
# return
# Debug "Point Dump $pointObj Note: $txt"
set vals [list]
foreach num [$pointObj 3d] {
lappend vals [format %+.3f $num]
}
# Debug "xyz $vals ($pointObj len [format %.3f [$pointObj len]]) Note: $txt"
}
proc Matrix_Dump2 {matrixObj {txt {}} } {
return
# Debug "Matrix Dump '$matrixObj' $txt"
foreach i {0 1 2 3} {
set vals [list]
foreach j {0 1 2 3} {
set idx [format "-ind%d%d" $i $j]
lappend vals [ format %+.3f [$matrixObj cget $idx]]
}
# Debug "$i [join $vals \t]"
}
}
##-
bind all <Escape> {exit}