set Initted 0

set Overlay overlay
# look to see if overlays are available, use popups otherwise
if { [glx_getgdesc bits_over_sng_cmode] < 2 } {
    set Overlay popup
    if { [glx_getgdesc bits_pup_sng_cmode] < 2 } { 
	puts "Cannot run with no overlays or popups"
	exit
    }
}
		
set gfx [glxwin .gfx  -rgb true -ref image -width 300 -height 300]
$gfx $Overlay create -bufsize 2

set msg [text .msg -relief groove -borderwidth 3 -height 6 -wrap word]
$msg insert 0.0 "\
 Left: change $Overlay drawing color,

 Middle: drop a yellow rect in normal framebuffer planes, 

 Right: clear."


button .q -text "Quit" -command "destroy ."
pack append .  .gfx {expand fill} .msg {fillx} .q {fillx}

bind $gfx <Map> {init_graphics %W}


bind $gfx <Expose> {
    if [%W islinked] {
	%W winset
	set_RGBcolor 0 0 0
	clear
    }
}

set Color 0

bind $gfx <1> {
    %W $Overlay winset
    incr Color
    if {$Color >= 4} {set Color 0}
    set_color 0
    clear
    set_color $Color
    draw_rect %W %x %y
    %W winset
}

bind $gfx <2> {
    %W winset
    set_RGBcolor 255 255 0
    draw_rect %W %x %y
}

bind $gfx <3> {
    %W winset
    set_RGBcolor 0 0 0
    clear
}

bind $gfx <Any-Motion> {
    %W $Overlay winset
    set_color 0
    clear
    set_color $Color
    draw_rect %W %x %y
    %W winset
}    


bind $gfx <Configure> {
    if [%W islinked] {
	%W winset
	glx_viewport %w %h

	%W $Overlay winset
	glx_viewport %w %h
    }
}
    
proc draw_rect {w mx my} {
    set ww [winfo width  $w] 
    set wh [winfo height $w] 

    set x [expr "(1.0 * $mx / $ww) * 1000.0"]
    set y [expr "(1.0 * $my / $wh) * 1000.0"]
    
    box $x $y [expr "$x - 100"] [expr "$y - 100"]
}
    
proc glx_install_colormaps {w} {
    # colorfocus is a command provided in a patch for the "photo" widget.
    # if it exists, it will install its own colormap property list, 
    # which doesn't include our subwindows.  Tell colorfocus not to 
    # try and do anything for us....

    if {[info commands colorfocus] != ""} {
	colorfocus remove $w
	$w installcolormaps
    }
}

proc init_graphics {w} {
    global Initted Overlay
    
    if {! $Initted} {
	set Initted 1
	glx_install_colormaps $w
	$w normal winset
	render_init
	set_RGBcolor 0 0 0
	clear
    
	$w $Overlay winset
	render_init
	mapcolor 1 255 0 0
	mapcolor 2 0 255 0
	mapcolor 3 0 0 255
	set_color 0
	clear
	$w normal winset
    }
}

wm minsize . 200 200
wm geometry . 500x500
