(***********************************************************************

                    Mathematica-Compatible Notebook

This notebook can be used on any computer system with Mathematica 4.0,
MathReader 4.0, or any compatible application. The data for the notebook 
starts with the line containing stars above.

To get the notebook into a Mathematica-compatible application, do one of 
the following:

* Save the data starting with the line of stars above into a file
  with a name ending in .nb, then open the file inside the application;

* Copy the data starting with the line of stars above to the
  clipboard, then use the Paste menu command inside the application.

Data for notebooks contains only printable 7-bit ASCII and can be
sent directly in email or through ftp in text mode.  Newlines can be
CR, LF or CRLF (Unix, Macintosh or MS-DOS style).

NOTE: If you modify the data for this notebook not in a Mathematica-
compatible application, you must delete the line below containing the 
word CacheID, otherwise Mathematica-compatible applications may try to 
use invalid cache data.

For more information on notebooks and Mathematica-compatible 
applications, contact Wolfram Research:
  web: http://www.wolfram.com
  email: info@wolfram.com
  phone: +1-217-398-0700 (U.S.)

Notebook reader applications are available free of charge from 
Wolfram Research.
***********************************************************************)

(*CacheID: 232*)


(*NotebookFileLineBreakTest
NotebookFileLineBreakTest*)
(*NotebookOptionsPosition[     13515,        364]*)
(*NotebookOutlinePosition[     15281,        416]*)
(*  CellTagsIndexPosition[     15237,        412]*)
(*WindowFrame->Normal*)



Notebook[{
Cell[TextData[{
  "Pick Events and Delaunay Algorithm\n",
  StyleBox["\tby Konrad Polthier\n\t",
    FontSize->16],
  StyleBox["(v. 1.04, 14.11.04)",
    FontSize->16,
    FontWeight->"Plain",
    FontVariations->{"CompatibilityType"->0}]
}], "Chapter",
  CellGroupingRules->"SectionGrouping",
  TextAlignment->Left],

Cell[CellGroupData[{

Cell[TextData[{
  "This notebook demonstrates a use of real-time heavy computations by ",
  StyleBox["Mathematica",
    FontSlant->"Italic"],
  " while interacting with the JavaView display. We show a planar \
triangulation and drag vertices around while ",
  StyleBox["Mathematica",
    FontSlant->"Italic"],
  " simultaneously calculates the Delaunay triangulation."
}], "Text"],

Cell[TextData[{
  "When the JavaView display is open, then drag a vertex of the geometry and \
wait a second. ",
  StyleBox["Mathematica",
    FontSlant->"Italic"],
  " will catch the update event of the geometry and recompute the \
triangulation to remain Delaunay. This notebook does not fulfill 'real-time' \
but I think it can be tuned and will try so."
}], "Text"],

Cell[TextData[{
  "Other Experiments:\nInitially the major mode of the display is \
PvDisplayIf`MODE_PICK which means that vertices may be picked and dragged.\n\
1. After some vertex dragging you might want to try to add another vertex. \
Just keep pressing the a-key and pick somewhere to add another vertex (even \
outside the geometry). Since the geometry is updated after this event the ",
  StyleBox["Mathematica",
    FontSlant->"Italic"],
  " handler is also called and recomputes the new triangulation.\n2. Or \
delete some vertices: keep pressing the m-key and drag a rectangle to mark \
all vertices inside. Then open the control window using ctrl-s or via popup \
menu and choose the menu entry Method -> Delete -> Remove Marked Vertices."
}], "Text"],

Cell["\<\
The notebook is a little bit longer since I rewrote one command in the \
package DiscreteMath`ComputationalGeometry` which does not handle vertices \
with triple valence correctly.\
\>", "Text"],

Cell["\<\
I use the asynchronous event handling to get a smoother perception when \
dragging the mouse.\
\>", "Text"]
}, Open  ]],

Cell[CellGroupData[{

Cell[TextData[{
  "Load Java runtime into ",
  StyleBox["Mathematica",
    FontSlant->"Italic"],
  " and load JavaView."
}], "MathCaption"],

Cell[BoxData[{
    \(<< JavaView`JLink`\), "\n", 
    \(\(viewer = InstallJavaView[];\)\)}], "Input",
  CellLabel->"In[170]:="],

Cell["Load Computational Geometry Package.", "MathCaption"],

Cell[BoxData[
    \(<< DiscreteMath`ComputationalGeometry`\)], "Input",
  CellLabel->"In[172]:="],

Cell["\<\
Get the current JavaView display and select pick mode in xy-projection.\
\>", "MathCaption"],

Cell[BoxData[{
    \(\(disp = viewer@getDisplay[];\)\), "\[IndentingNewLine]", 
    \(disp@selectCamera[PvDisplayIf`CAMERAUORTHOUXY]; 
    disp@setMajorMode[PvDisplayIf`MODEUPICK];\)}], "Input",
  CellLabel->"In[173]:="],

Cell["\<\
Create an empty geometry which will become the planar point set.\
\>", "MathCaption"],

Cell[BoxData[
    \(\(\(geom\  = \ 
        JavaNew["\<jv.geom.PgElementSet\>", 3];\)\(\ \)\)\)], "Input",
  CellLabel->"In[175]:="],

Cell["\<\
Compute a sample plane mesh and register it inside the display.\
\>", "MathCaption"],

Cell[BoxData[{
    \(\(geom@
        computePlane[4, 4, 0. , 0. , 2. , 1. ];\)\), "\[IndentingNewLine]", 
    \(\(geom@
        setName["\<Delaunay Triangulation\>"];\)\), "\[IndentingNewLine]", 
    \(\(geom@showIndices[True];\)\), "\[IndentingNewLine]", 
    \(\(geom@showVertices[True];\)\), "\[IndentingNewLine]", 
    \(\(JavaView[geom];\)\)}], "Input",
  CellLabel->"In[176]:="],

Cell[CellGroupData[{

Cell["\<\
The next function will be called upon pick and drag events. We do not use the \
mouse event since we just operate on the geometry one of whose vertex has \
been changed by the vertex dragging. Given a xy-planar geometry this method \
computes a Delaunay triangulation and updates the geometry. Method makes use \
of the Computational Geometry package of Mathematica.\
\>", "Text"],

Cell["\<\
Compute a Delaunay triangulation of a given point set upon pick events.\
\>", "MathCaption"],

Cell[BoxData[
    RowBox[{\(delaunay[geom_]\), ":=", "\[IndentingNewLine]", 
      RowBox[{"Module", "[", 
        RowBox[{\({}\), ",", 
          "\[IndentingNewLine]", \( (*\ \(PsDebug`message["\<Start Delaunay \
...\>" + JavaNew["\<java.util.Date\>"]@toString[]];\)*) \), 
          "\[IndentingNewLine]", 
          
          RowBox[{\(vertex\  = \ geom@getVertices[]\), ";", 
            "\[IndentingNewLine]", \(data3d = \ PdVector`getEntries[vertex]\),
             ";", "\[IndentingNewLine]", \(dim\  = geom@getDimOfVertices[]\), 
            ";", "\[IndentingNewLine]", \(vertexData2d\  = \ 
              Partition[Flatten[data3d], 2, dim]\), ";", 
            "\[IndentingNewLine]", 
            RowBox[{"(*", " ", 
              RowBox[{
                RowBox[{
                "This", " ", "gives", " ", "the", " ", "counterclockwise", 
                  " ", "vertex", " ", "adjacency", " ", "list", " ", "for", 
                  " ", "each", " ", "point", " ", "in", " ", "the", " ", 
                  "Delaunay", " ", \(triangulation . \ For\), " ", "example", 
                  " ", "the", " ", "entry", 
                  RowBox[{
                    StyleBox["{",
                      "MR"], 
                    RowBox[{
                      StyleBox["1",
                        "MR"], 
                      StyleBox[",",
                        "MR"], " ", 
                      RowBox[{
                        StyleBox["{",
                          "MR"], 
                        RowBox[{
                          StyleBox["4",
                            "MR"], 
                          StyleBox[",",
                            "MR"], " ", 
                          StyleBox["3",
                            "MR"], 
                          StyleBox[",",
                            "MR"], " ", 
                          StyleBox["2",
                            "MR"]}], 
                        StyleBox["}",
                          "MR"]}]}], 
                    StyleBox["}",
                      "MR"]}], "indicates", " ", "that", " ", "the", " ", 
                  "first", " ", "point", " ", "in", 
                  StyleBox["data2D",
                    "MR"], "is", " ", "connected", " ", "in", " ", 
                  "counterclockwise", " ", "order", " ", "to", " ", "the", 
                  " ", "fourth"}], ",", "third", 
                ",", \(and\ second\ \(\(points\)\(.\)\)\)}], " ", "*)"}], 
            "\[IndentingNewLine]", \(val = 
              DelaunayTriangulation[vertexData2d]\), ";", 
            "\[IndentingNewLine]", \(elemData = 
              adjacenyListToTriangulation[val]\), ";", 
            "\[IndentingNewLine]", \(element = PiVector`copyNew[elemData]\), 
            ";", "\[IndentingNewLine]", \(geom@
              setNumElements[Length[element]]\), ";", 
            "\[IndentingNewLine]", \(geom@setElements[element]\), ";", 
            "\[IndentingNewLine]", "elemData"}]}], "\[IndentingNewLine]", 
        "]"}]}]], "Input",
  CellLabel->"In[181]:="],

Cell["\<\
Helper module to convert a vertex adjacency list to connectivity of a \
triangulation.\
\>", "MathCaption"],

Cell[BoxData[
    \(adjacenyListToTriangulation[
        val : {{_Integer, {_Integer .. }} .. }] \
:= \[IndentingNewLine]Module[{nov, i, j, k, adj, vali, a1, a2, a1Adj, vala1, 
          elem}, \[IndentingNewLine]nov\  = \ 
          Length[val]; \[IndentingNewLine]elem\  = \ {}; \
\[IndentingNewLine]For[i = 1, 
          i <= nov, \(i++\), \[IndentingNewLine]adj\  = \ \
\(val[\([i]\)]\)[\([2]\)]; \[IndentingNewLine]vali\  = \ 
            Length[adj]; \[IndentingNewLine]For[j = 1, 
            j <= vali, \(j++\), \[IndentingNewLine]a1\  = \ 
              adj[\([j]\)] + 0; \[IndentingNewLine]a2\  = 
              adj[\([Mod[j, vali] + 1]\)] + 0; \[IndentingNewLine]If[
              a1 < i\  || a2 < i, 
              Continue[]]; \[IndentingNewLine]a1Adj = \(val[\([a1]\)]\)[\([2]\
\)]; \[IndentingNewLine]vala1 = Length[a1Adj]; \[IndentingNewLine]For[k = 1, 
              k <= vala1, \(k++\), \[IndentingNewLine]If[
                a1Adj[\([k]\)] != a2, Continue[]]; \[IndentingNewLine]elem = 
                Append[elem, {i - 1, a1 - 1, 
                    a2 - 1}]\[IndentingNewLine]];\[IndentingNewLine]];\
\[IndentingNewLine]]; \[IndentingNewLine]elem\[IndentingNewLine]]\)], "Input",\

  CellLabel->"In[182]:="],

Cell["\<\
This function will be called upon update events of the geometry. We do not \
use the mouse event since we just operate on the geometry one of whose vertex \
has been changed by the vertex dragging. Print timing messages into the \
JavaView console.\
\>", "MathCaption"],

Cell[BoxData[
    \(updateDelaunay[evt_, 
        message_] := \[IndentingNewLine]JavaBlock[\[IndentingNewLine] \
(*\(PsDebug`message[
              JavaNew["\<java.lang.String\>", "\<Start: \>"]@
                concat[date]];\)*) \[IndentingNewLine]delaunay[
          geom]; \[IndentingNewLine] (*\ \(PsDebug`message[
              JavaNew["\<java.lang.String\>", "\<End:   \>"]@
                concat[date]];\)\ *) \[IndentingNewLine] (*\ 
          Redraw\ geometry\ in\ display . \ Do\ not\ call\ geom@
              update[geom]\ to\ avoid\ getting\ into\ a\ loop, \ 
          since\ this\ handler\ is\ invoked\ on\ every\ update\ of\ \
\(\(geom\)\(.\)\)\ *) \[IndentingNewLine]disp@
          update[geom]; \[IndentingNewLine] (*\ Do\ not\ release\ event, \ 
          as\ one\ is\ usually\ advised, \[IndentingNewLine]since\ this\ \
event\ is\ the\ geometry\ ' geom' . \ If\ I\ release\ evt\ here\ then\ ' 
            geom'\ becomes\ a\ removed\ object\ and\ further\ access\ to\ it\ \
leads\ to\ error\ \(\(messages\)\(.\)\)\ *) \[IndentingNewLine] (*\ 
          ReleaseObject[evt]\ *) \[IndentingNewLine]]\)], "Input",
  CellLabel->"In[183]:="]
}, Open  ]],

Cell["\<\
Register an update listener of the geometry. We do not use the mouse events \
in the display since we just operate on the geometry one of whose vertex has \
been changed by the vertex dragging.\
\>", "MathCaption"],

Cell[BoxData[{
    \(\(listener\  = \ 
        JavaNew["\<jvx.math.MathUpdateListener\>"];\)\), "\n", 
    \(\(listener@
        setHandler["\<update\>", \ "\<updateDelaunay\>"];\)\), "\n", 
    \(\(geom@addUpdateListener[listener];\)\)}], "Input",
  CellLabel->"In[184]:="],

Cell["\<\
Let us print the current time to the JavaView console (press ctrl-d inside \
the JavaView display to open the console) to measure the time spent inside \
the Delaunay computation.\
\>", "MathCaption"],

Cell[BoxData[
    \(\(date\  := JavaNew["\<java.util.Date\>"]@toString[];\)\)], "Input",
  CellLabel->"In[187]:="],

Cell[TextData[{
  "After calling ShareKernel[] start dragging vertices around in the display. \
",
  StyleBox["Mathematica",
    FontSlant->"Italic"],
  " will compute the Delaunay triangulation in a different thread in the \
background."
}], "MathCaption"],

Cell[CellGroupData[{

Cell[BoxData[
    \(ShareKernel[]\)], "Input",
  CellLabel->"In[188]:="],

Cell[BoxData[
    \(8\)], "Output",
  CellLabel->"Out[188]="]
}, Open  ]]
}, Open  ]],

Cell[CellGroupData[{

Cell[TextData[{
  "When done with interaction, then call UnshareKernel[]. After calling \
UnshareKernel[] ",
  StyleBox["Mathematica",
    FontSlant->"Italic"],
  " will no longer receive events from ",
  StyleBox["JavaView",
    FontSlant->"Italic"],
  " unless ShareKernel[] is called again."
}], "MathCaption"],

Cell[BoxData[
    \(UnshareKernel[]\)], "Input",
  CellLabel->"(sharing) In[189]:="]
}, Open  ]]
},
FrontEndVersion->"4.0 for Microsoft Windows",
ScreenRectangle->{{0, 1400}, {0, 998}},
ScreenStyleEnvironment->"Brackets",
CellGrouping->Manual,
WindowSize->{782, 962},
WindowMargins->{{Automatic, 17}, {Automatic, 0}},
PrintingCopies->1,
PrintingPageRange->{Automatic, Automatic},
PageHeaders->{{Cell[ 
        TextData[ {
          CounterBox[ "Page"]}], "PageNumber"], Inherited, Cell[ 
        TextData[ {"Konrad Polthier"}], "PageHeader"]}, {Cell[ 
        TextData[ {"The ", 
          StyleBox[ "JavaView", FontSlant -> "Italic"], " Packages"}], 
        "PageHeader"], Inherited, Cell[ 
        TextData[ {
          CounterBox[ "Page"]}], "PageNumber"]}},
PageFooters->{{Inherited, Cell[ 
        TextData[ {
          "\[Copyright]1999 Wolfram Research, Inc. All rights reserved."}], 
        "PageFooter"], Inherited}, {Inherited, Cell[ 
        TextData[ {
          "\[Copyright]1999 Wolfram Research, Inc. All rights reserved."}], 
        "PageFooter"], Inherited}},
PageFooterLines->{True, True},
PrintingOptions->{"PrintingMargins"->{{56.6875, 56.6875}, {56.6875, \
56.6875}},
"PrintCellBrackets"->True,
"PrintRegistrationMarks"->False,
"PrintMultipleHorizontalPages"->False,
"FacingPages"->True},
Magnification->1.25,
StyleDefinitions -> "HelpBrowser.nb"
]


(***********************************************************************
Cached data follows.  If you edit this Notebook file directly, not using
Mathematica, you must remove the line containing CacheID at the top of 
the file.  The cache data will then be recreated when you save this file 
from within Mathematica.
***********************************************************************)

(*CellTagsOutline
CellTagsIndex->{}
*)

(*CellTagsIndex
CellTagsIndex->{}
*)

(*NotebookFileOutline
Notebook[{
Cell[1717, 49, 316, 10, 124, "Chapter",
  CellGroupingRules->"SectionGrouping"],

Cell[CellGroupData[{
Cell[2058, 63, 380, 9, 67, "Text"],
Cell[2441, 74, 369, 8, 67, "Text"],
Cell[2813, 84, 762, 12, 167, "Text"],
Cell[3578, 98, 204, 4, 48, "Text"],
Cell[3785, 104, 117, 3, 29, "Text"]
}, Open  ]],

Cell[CellGroupData[{
Cell[3939, 112, 139, 5, 36, "MathCaption"],
Cell[4081, 119, 127, 3, 54, "Input"],
Cell[4211, 124, 59, 0, 36, "MathCaption"],
Cell[4273, 126, 97, 2, 33, "Input"],
Cell[4373, 130, 102, 2, 36, "MathCaption"],
Cell[4478, 134, 220, 4, 75, "Input"],
Cell[4701, 140, 95, 2, 36, "MathCaption"],
Cell[4799, 144, 132, 3, 33, "Input"],
Cell[4934, 149, 94, 2, 36, "MathCaption"],
Cell[5031, 153, 384, 8, 117, "Input"],

Cell[CellGroupData[{
Cell[5440, 165, 390, 6, 86, "Text"],
Cell[5833, 173, 102, 2, 36, "MathCaption"],
Cell[5938, 177, 3048, 64, 411, "Input"],
Cell[8989, 243, 117, 3, 36, "MathCaption"],
Cell[9109, 248, 1230, 22, 453, "Input"],
Cell[10342, 272, 279, 5, 74, "MathCaption"],
Cell[10624, 279, 1159, 19, 369, "Input"]
}, Open  ]],
Cell[11798, 301, 224, 4, 55, "MathCaption"],
Cell[12025, 307, 274, 6, 75, "Input"],
Cell[12302, 315, 210, 4, 55, "MathCaption"],
Cell[12515, 321, 114, 2, 33, "Input"],
Cell[12632, 325, 257, 7, 55, "MathCaption"],

Cell[CellGroupData[{
Cell[12914, 336, 72, 2, 33, "Input"],
Cell[12989, 340, 61, 2, 27, "Output"]
}, Open  ]]
}, Open  ]],

Cell[CellGroupData[{
Cell[13099, 348, 313, 9, 55, "MathCaption"],
Cell[13415, 359, 84, 2, 50, "Input"]
}, Open  ]]
}
]
*)




(***********************************************************************
End of Mathematica Notebook file.
***********************************************************************)

