# pickdepth.tcl
#
# An example of the OpenGL red book modified to work with Tcl3D.
# The original C sources are Copyright (c) 1993-2003, Silicon Graphics, Inc.
# The Tcl3D sources are Copyright (c) 2005-2026, Paul Obermeier.
# See file LICENSE for complete license information.
#
# Picking is demonstrated in this program.  In 
# rendering mode, three overlapping rectangles are 
# drawn.  When the left mouse button is pressed, 
# selection mode is entered with the picking matrix.  
# Rectangles which are drawn under the cursor position
# are "picked."  Pay special attention to the depth 
# value range, which is returned.

package require tcl3d

tcl3dConsoleCreate .tcl3dOutputConsole "# " "Pickdepth Output"

set BUFSIZE 512
set selectBuffer [tcl3dVector GLuint $::BUFSIZE]

# Font to be used in the Tk listbox.
set listFont {-family {Courier} -size 10}

# Show errors occuring in the Togl callbacks.
proc bgerror { msg } {
    tk_messageBox -icon error -type ok -message "Error: $msg\n\n$::errorInfo"
    exit
}

# Print info message into widget a the bottom of the window.
proc PrintInfo { msg } {
    if { [winfo exists .fr.info] } {
        .fr.info configure -text $msg
    }
}

proc CreateCallback { toglwin } {
    glClearColor 0.0 0.0 0.0 0.0
    glEnable GL_DEPTH_TEST
    glShadeModel GL_FLAT
    glDepthRange 0.0 1.0 ;  # The default z mapping
}

# The three rectangles are drawn.  In selection mode, 
# each rectangle is given the same name.  Note that 
# each rectangle is drawn with a different z value.
#
proc drawRects { mode } {
    if { $mode == $::GL_SELECT } {
      glLoadName 1
    }
    glBegin GL_QUADS
    glColor3f 1.0 1.0 0.0
    glVertex3i 2 0 0
    glVertex3i 2 6 0
    glVertex3i 6 6 0
    glVertex3i 6 0 0
    glEnd
    if { $mode == $::GL_SELECT } {
        glLoadName 2
    }
    glBegin GL_QUADS
    glColor3f 0.0 1.0 1.0
    glVertex3i 3 2 -1
    glVertex3i 3 8 -1
    glVertex3i 8 8 -1
    glVertex3i 8 2 -1
    glEnd
    if { $mode == $::GL_SELECT } {
        glLoadName 3
    }
    glBegin GL_QUADS
    glColor3f 1.0 0.0 1.0
    glVertex3i 0 2 -2
    glVertex3i 0 7 -2
    glVertex3i 5 7 -2
    glVertex3i 5 2 -2
    glEnd
}

# processHits() prints out the contents of the 
# selection array.
#
proc processHits { hits } {
    set count 0
    puts  "hits = $hits"
    for { set i 0 } { $i < $hits } { incr i } {
        set names [$::selectBuffer get $count]
        puts " number of names for hit = $names"
        incr count
        puts -nonewline [format "  z1 is %g;"  \
               [expr double ([$::selectBuffer get $count]) / 0x7fffffff]]
        incr count
        puts [format " z2 is %g" \
               [expr double ([$::selectBuffer get $count]) / 0x7fffffff]]
        incr count
        puts -nonewline "   the name is "
        for { set j 0 } { $j < $names } { incr j } {
            puts -nonewline [format "%d " [$::selectBuffer get $count]]
            incr count
        }
        puts ""
    }
}

# pickRects() sets up selection mode, name stack, 
# and projection matrix for picking.  Then the objects 
# are drawn.
#

proc pickRects { x y } {
    set viewport [tcl3dVector GLint 4]
    glGetIntegerv GL_VIEWPORT $viewport

    glSelectBuffer $::BUFSIZE $::selectBuffer
    glRenderMode GL_SELECT

    glInitNames
    glPushName 0

    glMatrixMode GL_PROJECTION
    glPushMatrix
    glLoadIdentity
    # create 5x5 pixel picking region near cursor location
    gluPickMatrix $x [expr [$viewport get 3] - $y] 5.0 5.0 $viewport
    glOrtho 0.0 8.0 0.0 8.0 -0.5 2.5
    drawRects $::GL_SELECT
    glPopMatrix
    glFlush

    set hits [glRenderMode GL_RENDER]
    $viewport delete
    processHits $hits
}

proc DisplayCallback { toglwin } {
    glClear [expr $::GL_COLOR_BUFFER_BIT | $::GL_DEPTH_BUFFER_BIT]

    # Viewport command is not really needed, but has been inserted for
    # Mac OSX. Presentation framework (Tk) does not send a reshape event,
    # when switching from one demo to another.
    glViewport 0 0 [$toglwin width] [$toglwin height]

    drawRects $::GL_RENDER
    glFlush
    $toglwin swapbuffers
}

proc ReshapeCallback { toglwin { w -1 } { h -1 } } {
    set w [$toglwin width]
    set h [$toglwin height]

    glViewport 0 0 $w $h
    glMatrixMode GL_PROJECTION
    glLoadIdentity
    glOrtho 0.0 8.0 0.0 8.0 -0.5 2.5
    glMatrixMode GL_MODELVIEW
    glLoadIdentity
}

frame .fr
pack .fr -expand 1 -fill both
togl .fr.toglwin -width 400 -height 400 -double true -depth true \
                 -createcommand CreateCallback \
                 -reshapecommand ReshapeCallback \
                 -displaycommand DisplayCallback 
listbox .fr.usage -font $::listFont -height 2
label   .fr.info
grid .fr.toglwin -row 0 -column 0 -sticky news
grid .fr.usage   -row 1 -column 0 -sticky news
grid .fr.info    -row 2 -column 0 -sticky news
grid rowconfigure .fr 0 -weight 1
grid columnconfigure .fr 0 -weight 1
wm title . "Tcl3D demo: OpenGL Red Book example pickdepth"

bind . <Key-Escape> "exit"

bind .fr.toglwin <1> "pickRects %x %y"

.fr.usage insert end "Key-Escape Exit"
.fr.usage insert end "Mouse-L    Get pick results"
.fr.usage configure -state disabled

PrintInfo [tcl3dOglGetInfoString]
