JavaView Packages for Mathematica

Overview

Copyright (C) 2001-2006 by Konrad Polthier. All rights reserved.
Mathematica and J/Link are trademarks of Wolfram Research.
Java and JDK are trademarks of Sun Microsystems, Inc.
Use of the software is bound by the JavaView license agreement, which is available from the JavaView website at http://www.javaview.de.
[17.09.2006] Typo in Section RunThrough corrected which prevented geometry to load, additional quotes around pathname with blanks.

Introduction

JavaView is an interactive geometry viewer and a visualization toolkit. Its main focus is to supply visualization tools simultaneously for local applications as well as interactive online publications. These notes describe how to use JavaView as an integrated viewer for Mathematica graphics, as an online publication tool, and as a geometric toolbox to enhance Mathematica graphics. JavaView can be used either as an external program using the JavaView`RunThrough` package, or fully integrated with Mathematica via J/Link using the JavaView`JLink` package.

JavaView is designed for end-users and developers. End-users may work with the JavaView control panels and dialogs, or steer JavaView from Mathematica by calling documented commands from a notebook. Developers may additionally access the full functionality of the JavaView user interface and algorithms via the open programming API of JavaView either from Mathematica or from Java. Using JavaView from Mathematica requires only little familiarity with Java like the notion of classes and methods.

({{"◼  View Mathematica graphics in an interactive 3D JavaView display "}, {\(◼\ \ Apply\ transparency, \ 
                  smooth\ shading\ and\ texture\ images\ to\ Mathematica\ graphics\)}, {"◼  Write Mathematica programs that use pick information from the JavaView display"}, {"◼  Export Mathematica graphics to a variety of file formats (e.g. VRML, Maple, JavaView JVX, STL, OBJ, ...) "}, {"◼  Apply advanced geometry algorithms and visualization operations on Mathematica graphics"}, {"◼  Create webpages and webMathematica services with interactive Mathematica graphics "}})

Some uses for JavaView.

J/Link is an add-on package of Mathematica developed by Todd Gayley allowing realtime interaction between Mathematica and Java programs. It is a great achievement for the seemless integration of mathematical software, and I am very excited about the diversity of its applications.

The two JavaView packages JavaView`RunThrough` and JavaView`JLink` extend Mathematica with interactive 3D visualization functionality and the integration of Mathematica graphics into online publications. The main focus here lies on the package JavaView`JLink` which provides simple commands for viewing and modifying Mathematica graphics by making use of the 2-way connection between Mathematica and JavaView provided by J/Link. The simpler package JavaView`RunThrough` restricts to utility commands to export and view Mathematica graphics in the classical way via files; it does not need a J/Link installation.

Note, the commands in both packages are provided as a convenience to simplify calling JavaView. For example, experts may directly access the JavaView classes and methods using J/Link as described in more detail in the notebook Applications.nb.

These tutorial paragraphs are user's notes and provide first steps to use JavaView as 3D viewer of Mathematica graphics. The basic JavaView keyboard shortcuts are listed at the end of this document.

Requirements

JavaView for Mathematica requires J/Link. J/Link is an add-on package of Mathematica 4.0 or later which is available from Wolfram Research and which is compatible with all platforms on which Mathematica is available. JavaView has the same requirements as J/Link for Mathematica.

Requirements for JavaView for Mathematica:

1. Mathematica 4.0 or higher.

2. JavaView 2.21 or higher (jv_math.zip from www.javaview.de/download/ ).

3. J/Link (add-on component, pre-installed with Mathematica 4.2 and later).

4. Java runtime 1.1 or higher (pre-installed with Mathematica 4.2 and later).

The JavaView package JavaView`JLink` provides a full integration of JavaView with Mathematica via J/Link. This package requires Mathematica 4.0 or higher and J/Link to be installed. J/Link must be installed in the Mathematica installation before installing JavaView. J/Link comes pre-installed with Mathematica 4.2 and higher, and it may be downloaded for version 4.0 and 4.1 for free from Wolfram Research. The newest version of J/Link can always be obtained from http://www.wolfram.com/solutions/mathlink/jlink.

JavaView requires a Java runtime that is version 1.1 or later. A Java runtime is included in all Mathematica distributions since Mathematica 4.2. Users of Mathematica 4.0 and 4.1 should read the section Obtaining Java below to get Java.

The JavaView package JavaView`RunThrough` provides only a partial integration of JavaView with Mathematica but has the advantage that it runs already with Mathematica 3.0 and that it does not require a J/Link installation. When using this package then JavaView is able to display Mathematica graphics but not to provide feedback into Mathematica. Although this package does not need an installation of J/Link it still requires a Java runtime.

Obtaining Java for Mathematica 4.0 and 4.1

Note on Microsoft Windows Java Runtime

Until end of 2003 most users of Microsoft Windows had a Java runtime installed as part their Microsoft Windows operating system. Previous versions of the JavaView packages (before JavaView`JLink` v1.00) used that Microsoft Java runtime by default in order to avoid a separate installation process for Java.

Since Microsoft dropped all support for their Java runtime and no longer delivers a Java runtime with their operating system we decided to drop support too. Therefore the command InstallJavaView[] no longer launches the Microsoft Java runtime by default but now fully relies on the default settings of J/Link respectively on the settings of a user.

Users who still want to use the Microsoft Java runtime are advised to follow the comments given in section Using Microsoft Java.

Obtaining Java (copied from J/Link User Guide, version 2.1.0)

This information about obtaining a Java runtime is primarily for users with Mathematica 4.0 and 4.1. Beginning with version 4.2, the Mathematica distribution includes its own Java runtime for use by J/Link. An exception to this is the Macintosh, which already has a Java runtime suitable for J/Link.

Here are some useful links to help you obtain a suitable Java runtime or full JDK (Java Development Kit) for your platform. Many systems already have a recent Java runtime installed. Try the following command line to see if you have Java installed and, if so, what version it is:

java -version

It is strongly recommended that you get the latest version of Java available for your platform. In particular, the jump from the 1.1 to the 1.2 version of Java was very significant. You should be using a 1.3 or later version if at all possible.

You will sometimes see the abbreviations JRE and JDK when dealing with Java distributions. JRE stands for Java Runtime Environment, and JDK stands for Java Development Kit. A JRE has just the tools needed to run existing Java programs, not compile new ones. If you want to write your own Java language programs, you will need the full JDK.

Java Development Kits are available for free on all platforms that Mathematica supports.

Microsoft Windows

Sun and IBM both have excellent Java distributions. Before you download one, try the java -version command; you may already have at least a JRE installed on your machine somewhere. J/Link has been tested most extensively on Sun’s Java, which is currently at version 1.4 and can be obtained from http://java.sun.com/j2se.

Macintosh

J/Link is available in a native version for Mac OS X. The current version of J/Link is not supported on System 8 or 9, although older versions of J/Link work. All OS X users already have an appropriate Java installation to run J/Link.

Linux

Java distributions are available from Blackdown, IBM, and Sun. Some very recent Linux distributions include Java, but many users will have to download it. Sun’s 1.4 version for Linux is available at http://java.sun.com/j2se. IBM has an excellent Java for Linux, available at http://www.ibm.com/developerworks/java/jdk/index.html. The Blackdown version is also popular, and can be obtained from http://www.blackdown.org.

Solaris

Java can be obtained from http://www.sun.com/software/solaris/java. The 1.4 version is available now.

AIX

Java can be obtained from http://www.ibm.com/developerworks/java/jdk/aix. Java versions 1.2.2 and later are available for AIX 4.3.3 and later.

HP-UX

Java can be obtained from http://www.hp.com/products1/unix/java.

HP Tru64 Unix

Java can be obtained from http://www.hp.com/java.

Installing JavaView

The JavaView packages for Mathematica include the standard JavaView libraries and some documentary notebooks which must be downloaded from the JavaView homepage http://www.javaview.de and copied to the installation directory of Mathematica.

The required libraries for the JavaView system consists of two Java archives javaview.jar and jvx.jar. If JavaView runs within Mathematica, then two initialization files RunThrough.m and JLink.m plus this Overview.nb notebook must be available. Optionally, some models, localization files, and a tutorial directory with source code for Java programming may be downloaded.

Installation of JavaView for Mathematica:

1. Goto http://www.javaview.de/.

2. Goto menu "Download".

3. Download the archive "jv_math.zip" to a temporary place, say c:\tmp.

4. Uncompress the archive to a new directory of your choice, say c:\tmp. This will generate a new directory c:\tmp\JavaView including subdirectories. Assure that uncompression keeps the directory structure and is case sensitive on filenames.

5. Move the whole directory c:\tmp\JavaView to <path to Mathematica dir>\AddOns\Applications.

The directory <path to Mathematica dir>\AddOns\Applications\JavaView\Java will then contain the JavaView jar-archives. Mathematica will locate the JavaView jar-archives automatically, i.e. there is no need to worry about classpath settings.

Note on uncompression: on MS Windows you may use the program winzip. On Unix, use the shell command "unzip -U javaview.zip" where the argument -U ensures that decompression works case sensitive on filenames.

Note, for the display of precomputed geometries there exists an additional version jvLite of JavaView which is optimized for fast download and startup time (about 150KB). This version includes the full display functionality and a number of file loaders such as the Mathematica parser, but it does not include the control window, dialogs, or more sophisticated geometry classes and algorithms. jvLite is intended to run as applet showing precomputed geometries inside web pages. jvLite is included with the installation of JavaView.

Using Microsoft Java

Previous to JavaView`JLink` 1.00 the default configuration provided by JavaView`JLink` was set up to use the Java virtual machine provided by Microsoft. Beginning with JavaView`JLink` 1.00 the default configuration is better synchronized with the installation suggested by J/Link. That means, the command InstallJavaView calls the J/Link command InstallJava with no arguments and relies on the settings a user has done before calling InstallJavaView. Especially InstallJavaView no longer launches the Microsoft virtual machine by default.

If you determine that you need to use any of the options to InstallJava on a regular basis, you should put a SetOptions command in your Mathematica init.m file. Here are example lines for an init.m file for a Windows user who wants to use the Microsoft Java runtime ( the file init.m is located in <path to Mathematica dir>\Configuration\Kernel\ ):

<<JLink`
SetOptions[InstallJava, ClassPath->None]
SetOptions[InstallJava, CommandLine->wjview]
SetOptions[InstallJava, MicrosoftJava->True]
SetOptions[InstallJava, Java1->True]

Running JavaView via RunThrough

The package JavaView`RunThrough` accesses JavaView by invoking an executable file (MS-Windows) or shell script (Unix) called "javaview". Using RunThrough simplifies the Java setup since it does not use J/Link but it does not provide any feedback from JavaView back to Mathematica.

Access to the JavaView executable can be accomplished in different ways:

If a Microsoft Java runtime is available then the preferred way on MS Windows is to use the executable version <path to JavaView dir>\bin\javaview.exe. Include this executable in your path or move the file, for example, into the windows directory (c:\windows or c:\winnt). Then JavaView may be invoked either from the DOS prompt to view models, or from inside Mathematica using RunJavaView[g]. JavaView may also be associated with geometry file extensions such as *.mgs using the Windows file association mechanism.

An alternative method is the usage of a shell skript respectively batch file called "javaview" respectively "javaview.bat". Either file must be in the path such that Mathematica is able to find and launch JavaView from within Mathematica. Sample skript and batch files are provided in <path to JavaView dir>\bin both for Unix and MS Windows. Further, you need to edit the classpath in these files such that the JavaView archives are found by the virtual machine.

Trouble Shooting a JavaView Installation

Different reasons may lead to a failure of a JavaView installation. Some are related to the installation of the Java runtime system, some to the Mathematica package J/Link, and finally some to the installation of JavaView. Here we provide some step by step directions to locate the source of trouble. Note, failures appearing in step 1 and 2 of this section are not related to JavaView.

1. Test Java

This information about obtaining a Java runtime is primarily for users with Mathematica 4.0 and 4.1. Beginning with version 4.2, the Mathematica distribution includes its own Java runtime. An exception to this is the Macintosh, which already has a Java runtime.

Many systems already have a recent Java runtime installed. Try the following command line to see if you have Java installed and, if so, what version it is:

From the command line in a DOS window or Unix shell try the following command.

java -version

If you see a message that java cannot be found, then you do not have the Java binaries directory on your system path. You can either add it to your path in the usual way for your platform, or later use the CommandLine option to InstallJava to point at the runtime:

If java -version succeeds, it will print out some version information. This proves that the system can find the Java runtime. The version number of Java should be at least 1.2. If it is 1.1.x, obtain and install the latest version of Java from your operating system vendor. It is strongly recommended that you get the latest version of Java available for your platform. In particular, the jump from the 1.1 to the 1.2 version of Java was very significant. You should be using a 1.3 or later version if at all possible.

2. Test the J/Link Installation

J/Link is a package of Mathematica which provides the link between JavaView and Mathematica. J/Link is pre-installed with Mathematica 4.2 and later, and it must be obtained and installed separately when using the previous versions 4.0 or 4.1 of Mathematica.

2.1  Loading the J/Link Package

The first step is to load the J/Link package file. If you have installed J/Link, you will be able to load the package with the following line:

Needs["JLink`"]

2.2  Version Information

Check the version number of J/Link. You must need J/Link v2.0.0 or higher.

J/Link version information.

Check the version number of J/Link.

JLink`Information`$Version

2.3 InstallJava

The next step is to launch the Java runtime and “install” it into Mathematica. The function for this is InstallJava.

Launching the Java runtime.

Check if J/Link can be loaded.

InstallJava[]

If InstallJava succeeds, it will return a LinkObject. The most common failure mode is that InstallJava does not return. If this happens, use the Kernel/Abort Evaluation menu command to abort the call. If you have Mathematica 4.2 or later, then InstallJava[] should work when called with the default options. If it fails, make sure that you have not altered the default installation of J/Link by, for example, moving files out of the JLink directory tree.
If InstallJava fails with an error message that the class com.wolfram.jlink\Install cannot be found then you probably use v4.0 or v4.0 and the classpath does not include jlink.jar. Please, consult the installation section in of J/Link.

3. Test the JavaView Installation

The package JavaView`JLink` is an Add-On component of Mathematica which must be installed separately after a Mathematica installation. Since JavaView relies on a working Java runtime and J/Link installation, the following steps assume that step 1 and 2 of this section have been checked.

3.1  Loading the JavaView Package

The first step is to load the JavaView package file. If you have installed JavaView, you will be able to load the package with the following line:

<< JavaView`JLink`

3.2 Invoking JavaView

The next step is to launch the Java runtime and “install” it into Mathematica. The function for this is InstallJava.

Launching the Java runtime.

Check if JavaView can be loaded.

viewer = InstallJavaView[]

3.3 Show the JavaView Display

If the installation steps above worked fine, then the command JavaView[g] opens a JavaView display showing the Mathematica graphics as an interactive 3D geometry.

Create a sample geometry and view it in a JavaView display.

<< 
      Graphics`Polyhedra`
dode =  
        Graphics3D[Dodecahedron[]];
JavaView[dode]

Using JavaView`RunThrough`

Mathematica can launch external programs using the RunThrough[] command and feed them with data via the pipe mechanism. For example, this allows to launch the JavaView system and pass a Mathematica graphics object or animation to JavaView. JavaView then starts reading the data from stdin.

Invoking JavaView via RunThrough.

A drawback of using RunThrough is the missing feedback Mathematica is able to obtain from user interaction in JavaView. Further, on some operating systems the RunThrough[] command blocks the kernel until JavaView exists.
We provide the RunThrough mechanism because of its simplicity but encourage advanced users to use our J/Link-based package JavaView`JLink`. The commands in the package JavaView`RunThrough` are available in the package JavaView`JLink` too.

Load the package JavaView`RunThrough`.

<< JavaView`RunThrough`

Show a sample cube in a JavaView display.

cube  =  Graphics3D[Cuboid[{0, 0, 0}, {5, 2, 1}]];
RunJavaView[cube]

Some options.

Options[RunJavaView]

A list of geometries of the same type are displayed in JavaView either as a collection of individual geometries or as an animation of a single geometry.

Display a list of cuboids in an external JavaView display as a set of individual JavaView geometries.

randCube  :=  
        Cuboid[10 {Random[], Random[], 
              Random[]}];
cubes  =  
        Table[Graphics3D[randCube], {20}];
RunJavaView[cubes];

Display the same list of cuboids as an animation of a single cube.

RunJavaView[cubes,  Animatable -> True];

Here is the smooth animation of a catenoid deforming into a helicoid.

numFrames  =  2;
anim = 
      Table[ ParametricPlot3D[
{Cos[t] Cos[x] Cosh[y] + 
              Sin[t] Sin[x] Sinh[y], 
-Cos[t] Sin[
                  x] Cosh[y] + 
              Sin[t] Cos[x] Sinh[y], 
Cos[t] y + 
              Sin[t] x}, {x, -Pi, Pi}, {y, -Pi/2, 
            Pi/2}, 
AspectRatio -> Automatic, 
          Boxed -> False, Axes -> False, 
          PlotPoints  ->  {13, 
              7}, 
PlotRange -> {{-3, 3}, {-3, 
                3}, {-4, 4}}], {t, 0. , 
          Pi/2. , Pi/2. /(numFrames - 1)}]

Show a list of surfaces as smooth animation.

RunJavaView[anim,  Animatable -> True]

Command RunJavaView[g]

The command RunJavaView[g] launches JavaView to display a Mathematica graphics object. The graphics object may be of type Graphics, Graphics3D, SurfaceGraphics, and others. 
On some operating systems, this command blocks further execution of the Mathematica kernel until JavaView exits. In this case, during the life time of the JavaView process the kernel is waiting for JavaView to exit.

Create a sample Mathematica graphics and invoke JavaView for display.

geom  =  
        Plot3D[Sin[x* y],  {x, 0, Pi},  {y,  0, Pi}];

RunJavaView[geom]

RunJavaView invokes the Mathematica command RunThrough which launches "javaview" as an external process using a Java installation. Therefore, the path to the 'java' exectuable must be set such that Mathematica is able to find it. Further, the command RunJavaView converts a Mathematica graphics into InputForm and replaces the Mathematica specific floating point representation of numbers with conventional C form to simplify the parsing process in JavaView.

The JavaView archives ./Java/*.jar are searched relative to the JavaView installation directory:

GetInstallationPath[]

Experts Only: How to launch JavaView by hand?

Experts may directly use the command RunThrough but should ensure that the number representation in the graphics object are correctly formatted. JavaView requires data in InputForm. Note, that it is necessary to adjust the path to JavaView.
The handling of directory and filenames with blanks was changed in Mathematica 5.2 under MS-Windows. Therefore additional quotes have been added around codebase.

JavaView codebase from package installation.

jvCB = 
      StringReplace[
        GetInstallationPath[], $PathnameSeparator -> "/"]

Enclose in extra quotes since Mathematica 5.2 now handles blanks in filenames differently under MS-Windows.

jvCB = "\"" <> jvCB <> "\"";

JavaView archives (here only javaview.jar is specified).

jvJARS = jvCB <> "Java/javaview.jar"

Combine the Java runtime with JavaView archives and options.

jvCmd = "java -cp " <> 
        jvJARS <> " javaview file=stdin format=mgs codebase=" <> 
        jvCB

Convert Mathematica graphics to InputForm and launch JavaView.

fmtGeom = 
        InputForm[
          N[geom] /. x_Real :> CForm[Chop[x]]];

Launch JavaView to display Mathematica graphics.

RunThrough[jvCmd, fmtGeom]

Experts may insert changes to this setup in the package JavaView`RunThrough`.

Command WriteMgs[g, file]

WriteMgs[g,file] saves a Mathematica graphics in the given file, which may later be viewed with JavaView using the shell command 'javaview file'. The filename may specify a file relative to Mathematica or may be an absolute path. The command uses FormatGraphics[g] to convert the graphics object into a formatted string.
The saved file may later be viewed from command line using 'javaview myDode.mgs' or loaded into a running JavaView from the File-Open menu.

<< Graphics`Polyhedra`
dode =  Graphics3D[Dodecahedron[]];

GetWorkingPath[]

Saving a sample graphics as ASCII file relative to the working path.

fileName  =  "models\\mgs\\myDode.mgs";
WriteMgs[dode, fileName]

Re-import the previously saved geometry file as a regular Mathematica graphics. There is no difference between the original "cube" and "importCube".

importDode  =  
        Get[GetWorkingPath[] <> fileName];
Show[importDode];
RunJavaView[importDode]

Command WriteAnim[{g1, g2, ... },file]

WriteAnim[{g1, g2, ... },file] saves a list of Mathematica graphics as animation in the given file, which may later be viewed with JavaView using the shell command 'javaview file'. The filename may specify a file relative to Mathematica or may be an absolute path. The command uses FormatGraphics[g] to convert the graphics objects into a formatted string.

The saved file may later be viewed from the DOS command line using 'javaview c:\myAnim.mgs' or loaded into a running JavaView from the File-Open menu.

Create a list of cuboids in an external JavaView display as a set of individual JavaView geometries.

rcoord := {Random[], Random[], Random[]}
cubeAnim  =  
        Table[Graphics3D[Cuboid[10  rcoord]], {i, 1, 3}];

Save the cuboids as animation in a geometry file cuboidAnim.mgs relative to the working path.

fileName  =  "models/mgs/cubeAnim.mgs";
WriteAnim[cubeAnim, fileName]

As a test, load the previously saved animation back and playback in JavaView.

<< Graphics`Animation`
testAnim = Get[GetWorkingPath[] <> fileName];

The command WriteAnim saves an animation using the command ShowAnimation.

Command WriteHtml[g,file]

The following commands save a Mathematica graphics in a web page with a JavaView applet. This web page may be opened in a web browser, or published on a web site.

WriteHtml[g,file] creates a Html page showing the Mathematica graphics as interactive JavaView applet. The method uses FormatGraphics[g] to avoid very long lines which are anoying to web designers who postprocess the file. The filename may specify a file relative to Mathematica or may be an absolute path.
Note, the applet contains no codebase setting. Either the JavaView archives must be included in the classpath or manually added in a codebase directive of this applet.

Generate a cuboid as working example.

cube  =  
        Graphics3D[Cuboid[{5, 2, 1}], 
          PlotLabel -> "Cuboid"];

Create an Html page which displays the cuboid in a JavaView applet relative to the working path. The web page can be opened in any web browser.

WriteHtml[cube, "html\\myCube.html"]

Note, it is essential to have a JavaView installation in the target directory unless the path options of WriteHtml[] are adjusted as explained below.

The commands presented in this section are rather simple but very convenient in the daily use of Mathematica if J/Link is not available, or if no feedback from JavaView is needed. The following section gives a glimps of the tight integration J/Link offers for Mathematica and JavaView.

Adjusting the Codebase of Applet

The JavaView applet in the Html page needs the Java library 'javaview.jar' which contains the JavaView viewer. A web browser finds the location of the library by concatenating two string attributes of the applet: codebase and archive. The codebase attribute may either be an absolute or relative URL, and the archive attribute is a relative URL. If the codebase attribute is a relative URL then it is relative to the URL of the Html page.
The option "Codebase" specifies the codebase attribute of the JavaView applet. The codebase attribute is "./" on default, i.e. it refers to the directory of the Html page.

The option "PathToArchive" specifies the path of the JavaView archive relative to the codebase of the applet. A default installation of JavaView in a Mathematica installation puts the Java archive to <<mathematica root>>\AddOns\Applications\JavaView\Java\javaview.jar, and the default value of PathToArchive is "Java/".
The path name separators in the archive attributes must always be a slash "/".

Save the web page in a non-standard directory and adjust the codebase and archive attributes of the applet.

htmlFile  =  "html\\myCube.html";
codebase  =  "../";
archive =  "Java/";
WriteHtml[cube, htmlFile, Codebase -> codebase, 
      PathToArchive -> archive]

Note, if the web page is published on a web site, then the JavaView archives in .\Java must be published as well.

Using JavaView`JLink`

JavaView`JLink is a powerful add-on package to enable the tight integration between Mathematica and JavaView. The package JavaView`JLink` makes use of the Mathematica package J/Link. In this section we introduce two simple commands to easily setup an initialial connection, and then explore in more detail the interaction possibilities.

Start JavaView using J/Link and display Mathematica graphics.

J/Link is a Mathematica package which must be loaded before using JavaView. The package JavaView`JLink` loads J/Link automatically with a default configuration. A user may set different options to load and configure J/Link before loading JavaView. Loading of JavaView`JLink` does not modify the previous configuration of J/Link since the J/Link command InstallJava does nothing on its second and later invocations.

Optionally: configure J/Link before loading the JavaView package by using SetOptions[].

The package JavaView`JLink` automatically loads the package Mathematica package J/Link. By default, the command InstallJavaView uses the default settings of the J/Link initialization command InstallJava to load a Java runtime. This behaviour can be adjusted by using the command SetOptions BEFORE calling either InstallJava or InstallJavaView. The following options enable the use of the deprecated Microsoft Java runtime:

<<JLink`
SetOptions[InstallJava, ClassPath->None]
SetOptions[InstallJava, CommandLine->wjview]
SetOptions[InstallJava, MicrosoftJava->True]
SetOptions[InstallJava, Java1->True]

InstallJavaView[] creates a JavaView viewer manager and must be called prior to the first usage of JavaView[g]. The command also pre-loads some JavaView classes to simplify later access to static methods and constants. Its return value is the JavaView viewer manager which is an instance of the class jv.viewer.PvViewer, and which may be queried, for example, for the current display.
In contrast to the command RunJavaView[g] discussed in a previous section this J/Link connection to JavaView does not block the Mathematica kernel. Instead, it allows a realtime exchange of interactive data.

First JavaView display

Load the JavaView`JLink` package including the J/Link package of Mathematica.

<< JavaView`JLink`
viewer  =  InstallJavaView[];

The package Polyhedra is used in this notebook.

<< Graphics`Polyhedra`

Now we are ready to display the first geometry via the J/Link connection. The command JavaView[g] displays a Mathematica graphics in JavaView. The first invocation of the command JavaView will open a JavaView display.

Create a sample geometry and view it in a JavaView display.

dode =  Graphics3D[Dodecahedron[]];

JavaView[dode];

As a rule of thumb, the command JavaView[] can be used whenever the Mathematica command Show[] would apply.

Show[dode];

Simple graphics examples displayed by JavaView

JavaView understands most Mathematica graphics type such as Graphics, Graphics3D, SurfaceGraphics, and others. Subsequent invocations of the command JavaView[g] replace the previous geometry in the JavaView display. This is done intentionally to simplify the use of the command JavaView[g] although JavaView is able to visualize a whole scene of multiple geometries and animations. An option exists to keep the current scene shown in the JavaView display.

A detailed list of graphics examples is provided in the JavaView user's guide.

Visualizing a function curve as a set of points.

pts=Graphics[Table[Point[{x,2Sin[1/x]}],{x, -Pi, Pi,  .01}],Axes -> Automatic]
Show[pts];

JavaView[pts];

Visualized several cuboids, and an additional cuboid with different surface color.

cub = 
        Graphics3D[{Cuboid[{0, 0, 0}], Cuboid[{0, 0, 1}], Cuboid[{0, 1, 1}], 
            Cuboid[{1, 1, 1}], 
{SurfaceColor[
                RGBColor[0, 1, 0]], 
Cuboid[{1.25, 0.25, 
                  0.25}, {1.75, 0.75, 0.75}]}}];
Show[cub];

JavaView[cub];

Visualize a color image as rectangular grid of cells.

rsa = 
        Graphics[
          RasterArray[
            Table[Hue[ .1  Mod[i, j]], {i, 2, 10}, {j, 2, 
                10}]], 
AspectRatio -> 
            Automatic];
Show[rsa];

JavaView[rsa]

Simple examples of graphics options understood by JavaView

JavaView understands a large set of graphics options of Mathematica graphics. A detailed list of graphics options is provided in the JavaView user's guide.

The option PlotRange contrains the shown graphics to a box in x,y and z direction.

pr  =  
        Graphics3D[
          Stellate[
            Dodecahedron[]], 
PlotRange -> {All, {0. , 
                2. }, {-0.7, 0.5}}];
Show[pr]

JavaView[pr]

Adjust the focus and viewing direction of the camera.

gp = 
        Plot3D[Sin[x y], {x, 0, Pi}, {y, 0, 
            Pi}, 
ViewCenter -> {1, 1, 1}, 
          ViewVertical -> {1, 0, 0}];
JavaView[gp];

Position a few light sources for illumination.

ls  =  
        Graphics3D[
          Stellate[
            Dodecahedron[]], 
LightSources -> {{{1. , 
                  0. , 0. }, 
                RGBColor[1. , 0.4, 
                  0.4]}, 
{{- .15,  .85, 0. }, 
                RGBColor[0.4, 1. , 
                  0.4]}, 
{{- .15, - .85, 0. }, 
                RGBColor[0.4, 0.4, 1. ]}}];
Show[ls];
JavaView[ls];

Multiple geometries in a JavaView display

JavaView can display several graphics objects at once. The graphics objects may either be loaded at once, or one after another.

Load two geometries at once.

dode =  Graphics3D[Dodecahedron[]];
ico =  Graphics3D[Icosahedron[]];

JavaView[{dode, ico}];

Load two geometries one after another.

octa =  Graphics3D[Octahedron[]];
cube =  Graphics3D[Cube[]];

JavaView[octa];
JavaView[cube, Replace -> False];

When surfaces overlap or have intersections then switch on z-buffered rendering, for example, by pressing <shift-z> inside the JavaView display. The z-buffer can also be enabled from the Mathematica notebook by calling appropriate methods of the JavaView display objects. First, get the display object from the viewer manager, then enabled z-buffered rendering and finally initiate an update of the display to rerender the scene.

Get the JavaView viewer manager (in case we did not keep a reference at the beginning).

viewer  =  InstallJavaView[];

Enable z-buffered rendering.

disp = viewer@getDisplay[];
disp@setEnabledZBuffer[True];
disp@update[disp]

Having the display object at hand provide many more useful ways to interact with a JavaView scene. For example, it allows to change the currently active geometry. Normally, the first geometry added to a display is the active geometry. Inside the JavaView display the active geometry may be changed either inside the display inspector panel, or by a shortcut keeping ctrl-key pressed and left-clicking the geometry.
The active geometry may also be changed from within a notebook in different. For example, when adding a geometry to JavaView then keep a reference to the returned JavaView geometry object. (note, open the JavaView display inspector panel to see the change of the selection.)

Select a known other geometry as active geometry.

jvOcta=JavaView[octa];
jvCube=JavaView[cube, Replace -> False];

disp@selectGeometry[jvCube];
disp@update[disp]

Sometime the geometry are not known as JavaView objects. For example, when multiple geometries have been added to JavaView from a Mathematica graphics with many geometries. In this case the display can provide a list of all registered geometries.

Select an unknown other geometry.

geomArr = disp@getGeometries[]

disp@selectGeometry[geomArr[[1]]];
disp@update[disp]

Simple modifications of a geometry inside JavaView

The return value of JavaView[] is the geometry object used in JavaView. The type of the geometry class depends on the source material obtained from the Mathematica graphics. Typically the geometry is an instance of jv.geom.PgElementSet for Mathematica polygons and other surface primitives or it is an instance of jv.geom.PgPolygonSet for lines, circle, etc. The JavaView documentation contains information about the functionality of these geometry classes and the set of visualization tools operating on them. Using J/Link it is now possible to inspect the geometry classes, modify their material and appearence in the viewer, change the geometry, or return data to Mathematica.

The syntax of the invocation of Java methods is explained in detail in the J/Link manual. For convenience, a summary is included in these note.

View another geometry in JavaView which replaces the previous one. This time we catch the returned JavaView geometry.

geom=JavaView[Graphics3D[Icosahedron[]]]

Enable semi-transparent drawing in JavaView. The degree of transparency is in the interval [0,1].

geom@setTransparency[0.4];
geom@showTransparency[True];
geom@update[geom]

Query the geometry for its combinatorial structure, like number of vertices, edges, or elements. The name 'element' is used in JavaView for a face similar to the notation in finite element numerics.

geom@getNumElements[]

Query the geometry for geometric properties like surface area or enclosed oriented volume.

geom@getVolume[]

Modify the appearance and material properties. Here we switch off showing of faces but keep the display of edges. Note, whenever the geometry is changed in JavaView by a command from Mathematica then its update method be called to invoke a redraw of the JavaView display.

geom@showElements[False];
geom@update[geom]

Identification of Vertices

A Mathematica graphics has a separate list of points for each polygon. As a consequence, one cannot decide if two adjacent polygons join a common edge or if  the edge is common to both polygons just by chance. For example, surfaces which self-intersect might have edges common to four polygons but only pairs of two shall match there.
Since v3.0 JavaView automatically identifies equal vertices when parsing Mathematica graphics objects. In some rare cases the identification might produce a wrong neighbourhood relation of polygons and shall therefore be suppressed. Note, JavaView does not not identify vertices in animations since in animations a 1-1 correspondence between the vertices of all keyframes must be ensured during the animation.

Prevent the automatic identification of vertices using the option Identify->False.

<< Graphics`Polyhedra`
geom=JavaView[Graphics3D[Icosahedron[]],  
        Identify -> False]

The existence of duplicate vertices is easily detected by showing item labels, or by keeping the p-key pressed while dragging a vertex in the display.

geom@showVertices[True];
geom@showVertexLabels[True];
geom@update[geom]

We now show vertex normals. Each vertex shows as many vertex normals as there are adjacent polygons since without vertex identification JavaView is not able to produce an adjacency relation between polygons.

Change orientation and show vertex normals.

geom@flipOrientation[];
geom@makeVertexNormals[];
geom@showVertexNormals[True];
geom@update[geom]

On first sight, the vertex normals do not appear as expected but show up as a bunch of vectors at each vertex. The reason is that Mathematica lists the vertex coordinates for each polygon separately. Since this may be intentionally, JavaView keeps this duplicate vertices. In computational mathematics such a behaviour is usually avoided since duplicate vertices and edges lead to ambiguous neighboorhood relations between adjacent elements and to additional degrees of freedom in the numerical mesh.

If the vertices where not identified when passing to JavaView, then JavaView provide postprocessing tools to convert the geometry in a 'good' mesh by identifying vertices and building a neighbourhood between adjacent elements. Toolbox class jv.geom.PuCleanMesh is loaded during the initialization of JavaView.

Identify vertices whose vertex coordinates are equal (or within a small distance). The method returns the number of removed vertices.

PuCleanMesh`identifyVertices[geom]
geom@update[geom];

Refresh the vertex normals.

geom@makeVertexNormals[];
geom@update[geom];

Some of the commands issued above can also be invoked from the control window of JavaView. Click inside a display with the right mouse button and select the item 'Control Panel' from the popup menu.

Pre-Configuration of a JavaView Display

Normally, the JavaView display is initialized during each invocation such that all previous interactive configurations of a display are removed and reset to their default state. In some cases, a preconfiguration of the display is wanted were, for example, bounding box, axes frame and background image are enabled and visible when JavaView[] is launched.
The preconfiguration of the JavaView display is possible by configuration of the disp object. The disp object represents the JavaView display and can be obtained from the viewer manager. A large number of methods allow to configure even more feature than are available through the interactive display inspector.
A configuration of the disp object must be followed by an update of the display in order to take effect.
The disp object received from the viewer manager becomes void if a JavaView window is closed. When closing a JavaView window the disp object is removed from the viewer and destroyed, although the reference from inside Mathematica will still exist but no longer work. Therefore, after closing a JavaView window the disp object must be obtained again from the viewer manager.

Load the JavaView`JLink` package including the J/Link package of Mathematica.

<< JavaView`JLink`
viewer  =  InstallJavaView[];

Get the disp object from the viewer manager.

disp = viewer@getDisplay[];

Configure the JavaView display, and invoke update[] to enable the changes.

disp@showFrame[True];
disp@showAxes[True];
disp@showBndBox[True];
disp@showBackImage[True];
disp@update[disp]

The parameter KeepView->True prevents an initialization of the display

<< Graphics`Polyhedra`
dode =  
      Graphics3D[Dodecahedron[]]; 
JavaView[dode, KeepView -> True]

There exist many methods to configure a disp object which can be shown with the command Methods[]. The listing includes many more methods which are not useful in this context, but the relevant configuration methods have the form setEnableXxxx[] or showXxxx[]. The methods are not documented within the JavaView`JLink` package but at the JavaView website in the JavaView reference documentation at http://www.javaview.de/doc/reference/index.html. The configuration methods are described in the class jv.viewer.PvDisplay available at http://www.javaview.de/doc/reference/jv/viewer/PvDisplay.html.

Show all available methods of the JavaView display (much more than you can use).

Methods[disp]

Reminder on J/Link Basics

Launching J/Link

The first step is to load the J/Link package file. If you have installed J/Link as described in the installation chapter of the J/Link manual, you will be able to load the package:

Launching J/Link and Java.

Load J/Link.

<< JLink`

Launch the Java runtime.

InstallJava[]

A different invocation explicitly selects the Java runtime through options of InstallJava.

InstallJava[CommandLine -> "java", 
      MicrosoftJava -> False,  
      Java1 -> False]

The command InstallJava launches the Java runtime which may be selected by providing additional options. Remember, in J/Link version 1.01 the archive rmi.zip is required if the Microsoft virtual machine is used.
InstallJava can be called more than once in a session. On every call after the first, it does nothing. Thus, it is safe to call InstallJava in any program you write, without considering whether the user has already called it. Only one Java runtime will ever be in use.

Creating Java Objects

To instantiate Java objects, use the JavaNew[] function. The first argument to JavaNew is the object’s class, specified either as a JavaClass expression returned from LoadClass or as a string giving the fully-qualified class name (i.e., having the full package prefix with all the periods). If you wish to supply any arguments to the object’s constructor, they follow as a sequence after the class.

Creating Java classes in Mathematica.

Now we create a linear algebra vector in JavaView which mainly consists of an array of double values. The initial length of the array may be given as constructor argument. Double and integer vectors are the base classes used in all geometry classes of JavaView.

Create a new vector with different constructors.

vec0 = JavaNew["jv.vecmath.PdVector"]
vec3 = JavaNew["jv.vecmath.PdVector", 3]

We check the length of the return vectors.

vec0@getSize[]
vec3@getSize[]

vec3@setEntry[2,  17. ]

vec3@getEntries[]

The return value from JavaNew[] can be considered as a reference to the Java object, although it is a strange expression internally that will be referred to as JavaObject expression. JavaNew[] is not the only way to get a reference to a Java object in Mathematica. Many methods and fields return objects. Such objects can be used in the same way as ones you explicitly construct with JavaNew.

Naming Conventions

J/Link strictly follows the rules of the Mathematica programming language. This has certain implications how Java is accessed.

Access to public fields and methods follows the same rules as in Java with a slight difference in notation. Instead of '.' J/Link uses '@' for non-static respectively '`' for static fields and methods. Further, argument brackets [] are used instead of ().

Note, there is an issue with underscores used in method and variable names. They must be replaced by a capital 'U' unless the name appears inside of a string.

Naming conventions used by J/Link.

Before accessing a static variables the class must be loaded once. The command InstallJavaView of the JavaView pre-loads some basic JavaView classes but we repeat the loading here for completeness.

Load static classes prior to access of static variables. Notice the 'U'.

LoadClass["jv.object.PsObject"];
PsObject`ISUSELECTED

Arrays in Java and Lists in Mathematica

The level of exchange of larger data between Mathematica and Java is usually done on the basis of arrays in Java and lists in Mathematica as their counterparts.
The vector classes PdVector and PiVector used in JavaView have the functionality of double respectively integer arrays of arbitrary size. Basically, they contain a data fields 'double [] data' respectively 'int [] data'.

Here we call some basic linear algebra methods. Java objects in Mathematica behave like usual Java instances.

vec0@setSize[3];
vec0@setConstant[1. ];
vec3@add[vec0];
vec3@setEntry[0, 17];

Note, Java arrays start with index 0 while Mathematica lists start at index 1. This is essential when converting between Java arrays and Mathematica lists.

The content of the vector can be converted back and forth to a Mathematica list.

v  =  vec3@getEntries[]

v[[2]] = 19. ;
vec3@set[v];
vec3@getEntries[]

Create a new vector which is initialized with the data of the existing vector v.

kh = JavaNew["jv.vecmath.PdVector",  v]

kh@getEntries[]

Create a new empty surface.

torus  =  JavaNew["jv.geom.PgElementSet",  3]
torus@setName["fancy torus"];

Use a helper routine to create a torus over a 10*10 grid and radii 2 and 1.

torus@computeTorus[10,  10,  2. ,  1. ];

Here we are just accessing the 16th vertex of the torus. Note, array counting starts at 0 in Java.

torus@getVertex[16]@getEntries[]

Note, J/Link converts a Mathematica list to an array of doubles only if ALL entries are floating point numbers.

If the list v contains an integer then the setting fails since J/Link does not find the Java method.

v[[2]] = 19;
vec3@
      set[v];

vec3@set[17. , 19, 1. ]

When transferring large arrays of geometric data back and forth between Mathematica and JavaView it is time to read the section on performance issues in the J/Link manual.

Basics of the JavaView Display

The best introduction to the features of JavaView and the interaction with its display is to browse through the demonstrations given at the JavaView homepage http://www.javaview.de/. Here we provide a basic reference list.

The JavaView display always has a major interaction mode in which you can either rotate, scale, or translate a geometry. You press a shortcut key to switch to another mode temporarily. When releasing the key, the previous major mode is re-installed.
Note, selecting an interaction mode with the popup menu switches the major mode.

Each display opens a popup menu by clicking with the right mouse. This is a convenient shortcut for a few basic tasks avoiding to know keyboard shortcuts or to open the control window. For example, to switch the interaction mode (without using keyboard shortcut), access to help dialog (without using control window), open another display (without using control window), or open the control window.

Popup menu in any JavaView display using right-mouse click.

You can always get a listing of available keyboard shortcuts by opening the popup menu in any JavaView display and select the Help menu item. Here is a list of most commands. While focus over the display keep either of the following keys pressed while dragging with the mouse.

Keyboard shortcuts in JavaView display (an excerpt).

Different camera views, different display settings.

Each JavaView display maintains its own settings. If you like to have different views on the same scene then just open another display and select your preferred camera and display settings. Or go to the camera inspector and enable the synchronized display of four displays with different projection settings.

Different displays may also show a different set of geometries. But if a geometry is shared by displays, then it has the same shape and material in all displays. Therefore, if you have four displays with top, front, right, perspective view, then moving a vertex in either display will move the vertex in the other views too as you expect.

The control panel always views the camera and display panel of the currently active display. The current display is selected by moving the mouse over it. If there are many displays then this automatic selection might be annoying but it ensures that keyboard events are received by the display with mouse focus as expected (so we know about this problem).

Current geometry of a display.

Each JavaView display is able to display a scene with many geometries. One of these geometries is the active geometry. For example, you can pick vertices only of the active geometry.

Note, the control panel shows the info and material panel of the current geometry.

The current geometry may be selected in different ways:
1. Using keyboard shortcut Ctrl-tab or Ctrl-left mouse. This does not allow to select so-called special geometries like the coordinate frame, xy-grid or bounding box.
2. On the display panel select the active geometry. Here it is allowed to select special geometries too, and, for example, modify their appearance using their info/material/control panels.
3. Via method call disp@selectGeometry[geom].

Control Panel

The control window contains a set of panels to inspect the current geometry object, modify its material properties, select different camera type and to configure the active display.
The control panel may be opened in different ways:
1. Click inside a display with the right mouse button and select the item 'Control Panel' from the popup menu.
2. Ask the viewer manager to show the control panel, see below.
3. If JavaView is called from the command line as in the command RunJavaView then command line arguments may be specified like 'javaview panel=material control=show myDode.mgs' additional to a possible geometry file.
4. If JavaView runs inside an applet the applet parameters can be used to configure the initial setup like '<param name=config value=show>'.

If you did not keep your JavaView link from a session above then generate a new one.

<< JavaView`JLink`
viewer  =  InstallJavaView[]

Show the control window to inspect and configure the JavaView scene. Here we make use of the viewer obtained from command InstallJavaView and the automatic preloading of the interface class PsViewerIf.

viewer@showPanel[PsViewerIf`MATERIAL];
viewer@showDialog[PsViewerIf`CONTROL]

Java has some problems in bringing windows to the front, so the control panel might be hidden behind other windows. J/Link provides a special frame subclass to bring windows in front of Mathematica but the current version of the viewer manager creates an own specialized frame.

Acknowledgements

Although this text consists of informal notes, I would like use the opportunity to include thanks to Paul Wellin and Tom Wickham-Jones from Mathematica for pointing my attention to J/Link and providing a development edition of Mathematica, and to Todd Gayley who designed the marvellous J/Link package and answered my numerous questions. In many aspects, J/Link is this perfect interface to allow true interactive, high level integration of mathematical software which I was looking for a long time.

JavaView is software written by Konrad Polthier with Klaus Hildebrandt, Eike Preuß, and Ulrich Reitebuch. Other contributors are listed in the About menu of JavaView. The Mathematica graphics parser in JavaView is written by Ulrich Reitebuch, and the JavaView interface to Mathematica is designed and developed by Konrad Polthier.