void setupServerData(LocalDisplay[] dpys) throws RemoteException, VisADException { Unit super_degree = CommonUnit.degree.scale(2.5); RealType lon = RealType.getRealType("lon", super_degree); DataReference ref = loadFile(); if (ref == null) { System.err.println("must specify netCDF file name"); System.exit(1); return; } FieldImpl netcdf_data = (FieldImpl) ref.getData(); // compute ScalarMaps from type components FunctionType ftype = (FunctionType) netcdf_data.getType(); RealTupleType dtype = ftype.getDomain(); MathType rntype = ftype.getRange(); int n = dtype.getDimension(); dpys[0].addMap(new ScalarMap((RealType) dtype.getComponent(0), Display.XAxis)); if (n > 1) { dpys[0].addMap(new ScalarMap((RealType) dtype.getComponent(1), Display.YAxis)); } if (n > 2) { dpys[0].addMap(new ScalarMap((RealType) dtype.getComponent(2), Display.ZAxis)); } if (rntype instanceof RealType) { dpys[0].addMap(new ScalarMap((RealType) rntype, Display.Green)); if (n <= 2) { dpys[0].addMap(new ScalarMap((RealType) rntype, Display.ZAxis)); } } else if (rntype instanceof RealTupleType) { int m = ((RealTupleType) rntype).getDimension(); RealType rr = (RealType) ((RealTupleType) rntype).getComponent(0); dpys[0].addMap(new ScalarMap(rr, Display.Green)); if (n <= 2) { if (m > 1) { rr = (RealType) ((RealTupleType) rntype).getComponent(1); } dpys[0].addMap(new ScalarMap(rr, Display.ZAxis)); } } dpys[0].addMap(new ConstantMap(0.5, Display.Red)); dpys[0].addMap(new ConstantMap(0.0, Display.Blue)); dpys[0].addReference(ref, null); System.out.println("now saving data as 'save.nc' and re-reading"); Plain plain = new Plain(); try { plain.save("save.nc", netcdf_data, true); netcdf_data = (FieldImpl) plain.open("save.nc"); } catch (IOException e) { System.err.println("Couldn't open \"save.nc\": " + e.getMessage()); System.exit(1); return; } }
void setupServerData(LocalDisplay[] dpys) throws RemoteException, VisADException { RealType[] time = {RealType.Time}; RealType[] types = {RealType.Latitude, RealType.Longitude}; RealTupleType earth_location = new RealTupleType(types); RealType vis_radiance = RealType.getRealType("vis_radiance"); RealType ir_radiance = RealType.getRealType("ir_radiance"); RealType[] types2 = {vis_radiance, ir_radiance}; RealTupleType radiance = new RealTupleType(types2); FunctionType image_tuple = new FunctionType(earth_location, radiance); RealType[] types4 = {ir_radiance, vis_radiance}; RealTupleType ecnaidar = new RealTupleType(types4); FunctionType image_bumble = new FunctionType(earth_location, ecnaidar); RealTupleType time_type = new RealTupleType(time); FunctionType time_images = new FunctionType(time_type, image_tuple); int size = 64; FlatField imaget1 = FlatField.makeField(image_tuple, size, false); FlatField wasp = FlatField.makeField(image_bumble, size, false); int ntimes1 = 4; double start = new DateTime(1999, 122, 57060).getValue(); Set time_set = new Linear1DSet(time_type, start, start + 3600.0 * (ntimes1 - 1.0), ntimes1); FieldImpl image_sequence = new FieldImpl(time_images, time_set); FlatField temp = imaget1; Real[] reals30 = { new Real(vis_radiance, (float) size / 4.0f), new Real(ir_radiance, (float) size / 8.0f) }; RealTuple val = new RealTuple(reals30); for (int i = 0; i < ntimes1; i++) { image_sequence.setSample(i, temp); temp = (FlatField) temp.add(val); } dpys[0].addMap(new ScalarMap(RealType.Latitude, Display.YAxis)); dpys[0].addMap(new ScalarMap(RealType.Longitude, Display.XAxis)); dpys[0].addMap(new ScalarMap(vis_radiance, Display.Red)); dpys[0].addMap(new ScalarMap(ir_radiance, Display.Green)); dpys[0].addMap(new ConstantMap(0.5, Display.Blue)); dpys[0].addMap(new ScalarMap(RealType.Time, Display.ZAxis)); GraphicsModeControl mode = dpys[0].getGraphicsModeControl(); mode.setScaleEnable(true); DataReference ref_image_sequence = new DataReferenceImpl("ref_big_tuple"); ref_image_sequence.setData(image_sequence); dpys[0].addReference(ref_image_sequence, null); }
/** * Create e field description from the field * * @param fi field to use */ protected void makeFieldDescription(FieldImpl fi) { if (fi == null) { fieldsDescription = "Bad data: null"; return; } try { if (ucar.unidata.data.grid.GridUtil.isTimeSequence(fi)) { fi = (FieldImpl) fi.getSample(0); } PointOb ob = (PointOb) fi.getSample(0); Tuple tuple = (Tuple) ob.getData(); MathType[] comps = ((TupleType) tuple.getType()).getComponents(); Trace.msg("PointDataSource #vars=" + comps.length); StringBuffer params = new StringBuffer(comps.length + " Fields:<ul>"); String dataSourceName = getName(); DataChoice.addCurrentName(new TwoFacedObject("Point Data>Time", "Time")); DataChoice.addCurrentName(new TwoFacedObject("Point Data>Latitude", "Latitude")); DataChoice.addCurrentName(new TwoFacedObject("Point Data>Altitude", "Altitude")); for (int i = 0; i < comps.length; i++) { params.append("<li>"); String paramName = ucar.visad.Util.cleanTypeName(comps[i].toString()); DataAlias alias = DataAlias.findAlias(paramName); params.append(paramName); if (alias != null) { params.append(" -- " + alias.getLabel()); DataChoice.addCurrentName( new TwoFacedObject( dataSourceName + ">" + alias.getLabel() + " -- " + paramName, paramName)); } else { DataChoice.addCurrentName( new TwoFacedObject(dataSourceName + ">" + paramName, paramName)); } Data data = tuple.getComponent(i); if (data instanceof Real) { Unit unit = ((Real) data).getUnit(); if (unit != null) { params.append(" [" + unit.toString() + "]"); } } } fieldsDescription = params.toString(); } catch (Exception exc) { logException("getting description", exc); } }
/** evaluate the domainFactor function */ public static visad.Field factor(FieldImpl f, VRealType rt) { visad.Field val = null; try { val = f.domainFactor(rt.getRealType()); } catch (VisADException exc) { if (FormulaVar.DEBUG) exc.printStackTrace(); } catch (RemoteException exc) { if (FormulaVar.DEBUG) exc.printStackTrace(); } return val; }
/** create parallel coordinates display for data */ public static void parallel(DisplayImpl display, FlatField data) throws VisADException, RemoteException { FunctionType ftype = (FunctionType) data.getType(); RealType index = (RealType) ftype.getDomain().getComponent(0); RealTupleType range = (RealTupleType) ftype.getRange(); int ncoords = range.getDimension(); int nrows = data.getLength(); Set index_set = data.getDomainSet(); float[][] samples = data.getFloats(false); RealType x = RealType.getRealType("coordinate"); RealType y = RealType.getRealType("value"); SetType xy = new SetType(new RealTupleType(x, y)); FunctionType ptype = new FunctionType(index, xy); FieldImpl pfield = new FieldImpl(ptype, index_set); for (int j = 0; j < nrows; j++) { float[][] locs = new float[2][ncoords]; for (int i = 0; i < ncoords; i++) { locs[0][i] = i; locs[1][i] = samples[i][j]; } Gridded2DSet set = new Gridded2DSet(xy, locs, ncoords); pfield.setSample(j, set, false); } // create a DataReference for river system DataReference parallel_ref = new DataReferenceImpl("parallel"); parallel_ref.setData(pfield); display.addMap(new ScalarMap(x, Display.XAxis)); display.addMap(new ScalarMap(y, Display.YAxis)); // enable axis scales display.getGraphicsModeControl().setScaleEnable(true); // link display to parallel display display.addReference(parallel_ref); }
/** * Load the volume data to the display * * @throws RemoteException problem loading remote data * @throws VisADException problem loading the data */ private void loadVolumeData() throws VisADException, RemoteException { Trace.call1("VRC.loadVolumeData"); FieldImpl grid = getGridDataInstance().getGrid(); FieldImpl newGrid = grid; if (getSkipValue() > 0) { grid = GridUtil.subset(grid, getSkipValue() + 1); newGrid = grid; } if (!usePoints) { // make sure the projection is correct before we start // transforming the data setProjectionInView(true, true); CoordinateSystem cs = getNavigatedDisplay().getDisplayCoordinateSystem(); if ((cs != null) && (getNavigatedDisplay() instanceof MapProjectionDisplay)) { try { if (GridUtil.isConstantSpatialDomain(grid)) { newGrid = makeLinearGrid(grid, cs); } else { Set timeSet = GridUtil.getTimeSet(grid); for (int i = 0; i < timeSet.getLength(); i++) { FieldImpl timeField = makeLinearGrid((FieldImpl) grid.getSample(i, false), cs); if (i == 0) { FunctionType ft = new FunctionType( ((SetType) timeSet.getType()).getDomain(), timeField.getType()); newGrid = new FieldImpl(ft, timeSet); } newGrid.setSample(i, timeField, false); } } } catch (VisADException ve) { ve.printStackTrace(); userErrorMessage( "Can't render volume for " + paramName + " in this projection. Try using the data projection"); newGrid = grid; } } } Trace.call1("VRC.loadVolumeData.loadData"); myDisplay.loadData(newGrid); Trace.call2("VRC.loadVolumeData.loadData"); Trace.call2("loadVolumeData"); }
/** * Get the data for the given DataChoice and selection criteria. * * @param dataChoice DataChoice for selection * @param category DataCategory for the DataChoice (not used) * @param subset subsetting criteria * @param requestProperties extra request properties * @return the Data object for the request * @throws RemoteException couldn't create a remote data object * @throws VisADException couldn't create the data */ protected Data getDataInner( final DataChoice dataChoice, DataCategory category, final DataSelection subset, final Hashtable requestProperties) throws VisADException, RemoteException { try { List times = null; if (subset != null) { times = getTimesFromDataSelection(subset, dataChoice); } if (times == null) { times = dataChoice.getSelectedDateTimes(); } List dtimes = subset.getTimeDriverTimes(); if (dtimes != null && useDriverTime == false) { useDriverTime = true; } List<RadarAdapter> adapters = getAdapters(); DateTime[] realDateTimes = new DateTime[adapters.size()]; for (int i = 0; i < adapters.size(); i++) { realDateTimes[i] = ((RadarAdapter) adapters.get(i)).getBaseTime(); } Arrays.sort(realDateTimes); // Flip it to get youngest date first boolean isRealTime = isRealTime(); if (isRealTime) { realDateTimes = (DateTime[]) Misc.reverseArray(realDateTimes, new DateTime[realDateTimes.length]); } // if use time driver if (useDriverTime) { List tests = resetTimesList(realDateTimes, times); if (!compareTimeLists(times, tests)) { reloadData(); adapters = getAdapters(); realDateTimes = new DateTime[adapters.size()]; for (int i = 0; i < adapters.size(); i++) { realDateTimes[i] = ((RadarAdapter) adapters.get(i)).getBaseTime(); } Arrays.sort(realDateTimes); // Flip it to get youngest date first isRealTime = isRealTime(); if (isRealTime) { realDateTimes = (DateTime[]) Misc.reverseArray(realDateTimes, new DateTime[realDateTimes.length]); } tests = resetTimesList(realDateTimes, times); } times = tests; } // if times are null, then that means all times DateTime[] dateTimes = null; if ((times == null) || (times.size() == 0)) { dateTimes = realDateTimes; } else { dateTimes = new DateTime[times.size()]; for (int i = 0; i < times.size(); i++) { Object time = times.get(i); if (time instanceof TwoFacedObject) { int index = ((Integer) ((TwoFacedObject) time).getId()).intValue(); dateTimes[i] = realDateTimes[index]; } else if (time instanceof DateTime) { dateTimes[i] = (DateTime) time; } } } Arrays.sort(dateTimes); final Data[] datas = new Data[dateTimes.length]; int timeIndex = 0; final MathType[] mt = {null}; // create a new field of (Time -> (radar data)). // fill in the times array and data array with dates/data // only from those adapters which match the selected times. // if a data object is null, stick it in the list. // if all are null, then the MathType (mt) will never get set, // so return null. // System.err.println ("Reading " + adapters.size() + " radar files"); int cnt = 0; ThreadManager threadManager = new visad.util.ThreadManager("radar data reading"); for (Iterator iter = adapters.iterator(); iter.hasNext(); ) { final RadarAdapter adapter = (RadarAdapter) iter.next(); timeIndex = Arrays.binarySearch(dateTimes, adapter.getBaseTime()); // System.err.println ("timeIndex:" + timeIndex); if (timeIndex < 0) { continue; } cnt++; LogUtil.message("Time: " + (cnt) + "/" + dateTimes.length + " From:" + toString()); final int theTimeIndex = timeIndex; threadManager.addRunnable( new visad.util.ThreadManager.MyRunnable() { public void run() throws Exception { Trace.call1("RDS.getData"); Data d = adapter.getData(dataChoice, subset, requestProperties); Trace.call2("RDS.getData"); datas[theTimeIndex] = d; if (d != null) { mt[0] = d.getType(); } else { } } }); } try { // threadManager.debug = true; threadManager.runInParallel(getDataContext().getIdv().getMaxDataThreadCount()); } catch (VisADException ve) { LogUtil.printMessage(ve.toString()); } if (mt[0] == null) { return null; } FunctionType ft = new FunctionType(RealType.Time, mt[0]); SampledSet domainSet = (dateTimes.length == 1) ? (SampledSet) new SingletonSet(new RealTuple(dateTimes)) : (SampledSet) DateTime.makeTimeSet(dateTimes); FieldImpl fi = new FieldImpl(ft, domainSet); fi.setSamples(datas, false); return fi; } catch (Exception exc) { logException("Creating obs", exc); } return null; }
/** * Create a front from the curve * * @param curve the curve coordinates * @param flip true to flip the pips * @return The front as a FieldImpl * @throws RemoteException On badness * @throws VisADException On badness */ private FieldImpl curveToFront(float[][] curve, boolean flip) throws VisADException, RemoteException { if (flipTheFlip) { flip = !flip; } // compute various scaling factors int len = curve[0].length; if (len < 2) { return null; } float[] seg_length = new float[len - 1]; float curve_length = curveLength(curve, seg_length); float delta = curve_length / (len - 1); // curve[findex] where // float findex = ibase + mul * repeat_shapes[shape][0][j] float mul = rprofile_length * zoom / rsegment_length; // curve_perp[][findex] * ratio * repeat_shapes[shape][1][j] float ratio = delta * mul; // compute unit perpendiculars to curve float[][] curve_perp = new float[2][len]; for (int i = 0; i < len; i++) { int im = i - 1; int ip = i + 1; if (im < 0) { im = 0; } if (ip > len - 1) { ip = len - 1; } float yp = curve[0][ip] - curve[0][im]; float xp = curve[1][ip] - curve[1][im]; xp = -xp; float d = (float) Math.sqrt(xp * xp + yp * yp); if (flip) { d = -d; } xp = xp / d; yp = yp / d; curve_perp[0][i] = xp; curve_perp[1][i] = yp; } // build Vector of FlatFields for each shape of each segment Vector inner_field_vector = new Vector(); for (int segment = 0; true; segment++) { // curve[findex] where // float findex = ibase + mul * repeat_shapes[shape][0][j] float segment_length = (segment == 0) ? fsegment_length : rsegment_length; int profile_length = (segment == 0) ? fprofile_length : rprofile_length; mul = profile_length * zoom / segment_length; // curve_perp[][findex] * ratio * repeat_shapes[shape][1][j] // float ratio = delta * mul; // figure out if clipping is needed for this segment // only happens for last segment boolean clip = false; float xclip = 0.0f; // int ibase = segment * profile_length; int ibase = (segment == 0) ? 0 : fprofile_length + (segment - 1) * rprofile_length; int iend = ibase + profile_length; if (ibase > len - 1) { break; } if (iend > len - 1) { clip = true; iend = len - 1; xclip = (iend - ibase) / mul; } // set up shapes for first or repeating segment int nshapes = nrshapes; float[][][] shapes = repeat_shapes; int[][][] tris = repeat_tris; float[] red = repeat_red; float[] green = repeat_green; float[] blue = repeat_blue; if (segment == 0) { nshapes = nfshapes; shapes = first_shapes; tris = first_tris; red = first_red; green = first_green; blue = first_blue; } // iterate over shapes for segment for (int shape = 0; shape < nshapes; shape++) { float[][] samples = shapes[shape]; int[][] ts = tris[shape]; /* // if needed, clip shape if (clip) { float[][][] outs = new float[1][][]; int[][][] outt = new int[1][][]; DelaunayCustom.clip(samples, ts, 1.0f, 0.0f, xclip, outs, outt); samples = outs[0]; ts = outt[0]; } */ if ((samples == null) || (samples[0].length < 1)) { break; } float[][] ss = mapShape(samples, len, ibase, mul, ratio, curve, curve_perp); // **** get rid of previous calls to fill() **** ts = DelaunayCustom.fill(ss); // jeffmc: For now don't clip. This seems to fix the problem of too short a front boolean DOCLIP = false; if (clip && DOCLIP) { float[][] clip_samples = { {xclip, xclip, xclip - CLIP_DELTA}, {CLIP_DELTA, -CLIP_DELTA, 0.0f} }; float[][] clip_ss = mapShape(clip_samples, len, ibase, mul, ratio, curve, curve_perp); // now solve for: // xc * clip_samples[0][0] + yc * clip_samples[1][0] = 1 // xc * clip_samples[0][1] + yc * clip_samples[1][1] = 1 // xc * clip_samples[0][2] + yc * clip_samples[1][2] < 1 float det = (clip_samples[0][1] * clip_samples[1][0] - clip_samples[0][0] * clip_samples[1][1]); float xc = (clip_samples[1][0] - clip_samples[1][1]) / det; float yc = (clip_samples[0][1] - clip_samples[0][0]) / det; float v = 1.0f; if (xc * clip_samples[0][2] + yc * clip_samples[1][2] > v) { xc = -xc; yc = -yc; v = -v; } float[][][] outs = new float[1][][]; int[][][] outt = new int[1][][]; DelaunayCustom.clip(ss, ts, xc, yc, v, outs, outt); ss = outs[0]; ts = outt[0]; } if (ss == null) { break; } int n = ss[0].length; // create color values for field float[][] values = new float[3][n]; float r = red[shape]; float g = green[shape]; float b = blue[shape]; for (int i = 0; i < n; i++) { values[0][i] = r; values[1][i] = g; values[2][i] = b; } // construct set and field DelaunayCustom delaunay = new DelaunayCustom(ss, ts); Irregular2DSet set = new Irregular2DSet(curve_type, ss, null, null, null, delaunay); FlatField field = new FlatField(front_inner, set); field.setSamples(values, false); inner_field_vector.addElement(field); // some crazy bug - see Gridded3DSet.makeNormals() } // end for (int shape=0; shape<nshapes; shape++) } // end for (int segment=0; true; segment++) int nfields = inner_field_vector.size(); Integer1DSet iset = new Integer1DSet(front_index, nfields); FieldImpl front = new FieldImpl(front_type, iset); FlatField[] fields = new FlatField[nfields]; for (int i = 0; i < nfields; i++) { fields[i] = (FlatField) inner_field_vector.elementAt(i); } front.setSamples(fields, false); return front; }
/** Make the <code>DataChoices</code> for this <code>DataSource</code>. */ public void doMakeDataChoices() { if (sources == null) { return; } String stationModelName = (String) getProperty(PROP_STATIONMODELNAME); Hashtable properties = Misc.newHashtable(DataChoice.PROP_ICON, "/auxdata/ui/icons/Placemark16.gif"); if (stationModelName != null) { properties.put(PROP_STATIONMODELNAME, stationModelName); } if (!getDefaultLevels().isEmpty()) { properties.put(DataSelection.PROP_DEFAULT_LEVELS, getDefaultLevels()); } DataChoice uberChoice = null; /* Might want to do this someday uberChoice = new DirectDataChoice(this, sources, getName(), getDataName(), getPointCategories(), properties); */ if (sources.size() > 1) { uberChoice = new CompositeDataChoice( this, sources, getName(), getDataName(), getPointCategories(), properties); addDataChoice(uberChoice); } for (int i = 0; i < sources.size(); i++) { String dataChoiceDesc = getDescription(); String dataChoiceName = getDataName(); if (uberChoice != null) { dataChoiceDesc = IOUtil.getFileTail(sources.get(i).toString()); dataChoiceName = IOUtil.getFileTail(sources.get(i).toString()); } DataChoice choice = new DirectDataChoice( this, new Integer(i), dataChoiceDesc, dataChoiceName, getPointCategories(), properties); /* We'd like to create sub choices for each parameter but we don't really know the parameters until we read the data and that can be expensive DirectDataChoice subChoice = new DirectDataChoice(this, (String) sources.get(i), getDescription(), getDataName(), getPointCategories(), properties); choice.addDataChoice(subChoice);*/ if (uberChoice != null) { ((CompositeDataChoice) uberChoice).addDataChoice(choice); } else { addDataChoice(choice); } // Only add the grid data choices for the first source if (i > 0) { continue; } try { FieldImpl sample = (makeGridFields ? getSample(choice) : null); if (sample != null) { for (int dataChoiceType = 0; dataChoiceType < 2; dataChoiceType++) { Hashtable seenFields = new Hashtable(); if (ucar.unidata.data.grid.GridUtil.isTimeSequence(sample)) { sample = (FieldImpl) sample.getSample(0); } PointOb ob = (PointOb) sample.getSample(0); Tuple tuple = (Tuple) ob.getData(); TupleType tupleType = (TupleType) tuple.getType(); MathType[] types = tupleType.getComponents(); CompositeDataChoice compositeDataChoice = null; for (int typeIdx = 0; typeIdx < types.length; typeIdx++) { if (!(types[typeIdx] instanceof RealType)) { continue; } RealType type = (RealType) types[typeIdx]; if (!canCreateGrid(type)) { continue; } // List gridCategories = // DataCategory.parseCategories("OA Fields;GRID-2D-TIME;"); List gridCategories = DataCategory.parseCategories("GRID-2D-TIME;", false); if (compositeDataChoice == null) { compositeDataChoice = new CompositeDataChoice( this, "", "Grid Fields from Objective Analysis", "Gridded Fields " + ((dataChoiceType == 0) ? "" : "(with first guess)"), Misc.newList(DataCategory.NONE_CATEGORY), null); addDataChoice(compositeDataChoice); } String name = ucar.visad.Util.cleanTypeName(type.toString()); if (seenFields.get(name) != null) { continue; } seenFields.put(name, name); List idList = Misc.newList(new Integer(i), type); if (dataChoiceType == 1) { idList.add(new Boolean(true)); } DataChoice gridChoice = new DirectDataChoice(this, idList, name, name, gridCategories, (Hashtable) null); compositeDataChoice.addDataChoice(gridChoice); } } } } catch (Exception exc) { throw new WrapperException("Making grid parameters", exc); } // if(true) break; } }
/** * Actually get the data identified by the given DataChoce. The default is to call the * getDataInner that does not take the requestProperties. This allows other, non unidata.data * DataSource-s (that follow the old API) to work. * * @param dataChoice The data choice that identifies the requested data. * @param category The data category of the request. * @param dataSelection Identifies any subsetting of the data. * @param requestProperties Hashtable that holds any detailed request properties. * @return The visad.Data object * @throws RemoteException Java RMI problem * @throws VisADException VisAD problem */ protected Data getDataInner( DataChoice dataChoice, DataCategory category, DataSelection dataSelection, Hashtable requestProperties) throws VisADException, RemoteException { loadId = JobManager.getManager().stopAndRestart(loadId, "WMSControl"); Object myLoadId = loadId; if (requestProperties == null) { requestProperties = new Hashtable(); } WmsSelection wmsInfo = (WmsSelection) dataChoice.getId(); // Look if there was a layer that overrides the one in the data choice Object tfoLayer = requestProperties.get(PROP_LAYER); if ((tfoLayer != null) && (tfoLayer instanceof TwoFacedObject)) { String layer = ((TwoFacedObject) tfoLayer).getId().toString(); for (int i = 0; i < wmsSelections.size(); i++) { WmsSelection tmpSelection = (WmsSelection) wmsSelections.get(i); if (Misc.equals(tmpSelection.getLayer(), layer)) { wmsInfo = tmpSelection; break; } } } GeoLocationInfo boundsToUse = (GeoLocationInfo) requestProperties.get(PROP_BOUNDS); Image image = null; FieldImpl xyData = null; byte[] imageContent = null; // System.err.println(wmsInfo.getImageFile()); if (wmsInfo.getImageFile() != null) { try { boundsToUse = new GeoLocationInfo(90, -180, -90, 180); InputStream is = IOUtil.getInputStream(wmsInfo.getImageFile()); imageContent = IOUtil.readBytes(is, myLoadId); image = Toolkit.getDefaultToolkit().createImage(imageContent); // javax.swing.JLabel l = new javax.swing.JLabel(new // javax.swing.ImageIcon(image)); // l.setBackground(Color.red); // ucar.unidata.util.GuiUtils.showOkCancelDialog(null,null, l,null); xyData = ucar.visad.Util.makeField(image, 0, false, true); } catch (Exception iexc) { logException("There was an error accessing the image:\n" + wmsInfo.getImageFile(), iexc); return null; } } else { String writeFile = (String) requestProperties.get(PROP_WRITEFILE); int imageWidth = Misc.getProperty(requestProperties, PROP_IMAGEWIDTH, 800); int imageHeight = Misc.getProperty(requestProperties, PROP_IMAGEHEIGHT, -1); double resolution = Misc.getProperty(requestProperties, PROP_RESOLUTION, (float) 1.0); if (wmsInfo.getLegendIcon() != null) { requestProperties.put(PROP_ICONPATH, wmsInfo.getLegendIcon()); } if (!wmsInfo.getAllowSubsets() || (boundsToUse == null)) { boundsToUse = wmsInfo.getBounds(); } else { boundsToUse.rectify(wmsInfo.getBounds(), 0.0); boundsToUse.snapToGrid(); boundsToUse.rectify(wmsInfo.getBounds(), 0.0); } double widthDegrees = boundsToUse.getMaxLon() - boundsToUse.getMinLon(); double heightDegrees = boundsToUse.getMaxLat() - boundsToUse.getMinLat(); if ((widthDegrees == 0) || (heightDegrees == 0)) { return null; } if (wmsInfo.getFixedWidth() > -1) { imageWidth = wmsInfo.getFixedWidth(); } if (wmsInfo.getFixedHeight() > -1) { imageHeight = wmsInfo.getFixedHeight(); } else { if (imageHeight < 0) { imageHeight = Math.abs((int) (imageWidth * boundsToUse.getDegreesY() / boundsToUse.getDegreesX())); } } imageWidth = Math.min(Math.max(imageWidth, 50), 2056); imageHeight = Math.min(Math.max(imageHeight, 50), 2056); if (maintainRatio) { imageHeight = (int) (imageWidth * (heightDegrees / widthDegrees)); } double diff = Math.abs(boundsToUse.getMinLon() - boundsToUse.getMaxLon()); String url = wmsInfo.assembleRequest( boundsToUse, (int) (imageWidth / resolution), (int) (imageHeight / resolution)); String cacheGroup = "WMS"; synchronized (cachedUrls) { if (writeFile == null) { for (int i = 0; i < cachedUrls.size(); i++) { if (url.equals(cachedUrls.get(i))) { image = (Image) cachedData.get(i); break; } } } } try { if (image == null) { if (Misc.equals(url, lastUrl) && (lastImageContent != null)) { imageContent = lastImageContent; } else { } if (imageContent == null) { long t1 = System.currentTimeMillis(); // System.err.println("getting image:" + url); LogUtil.message("Reading WMS image: " + wmsInfo); // System.err.println ("url:" + url); InputStream is = IOUtil.getInputStream(url); long t2 = System.currentTimeMillis(); imageContent = IOUtil.readBytes(is, myLoadId); long t3 = System.currentTimeMillis(); LogUtil.message(""); // System.err.println("Done"); } // If it is null then there is another thread that is doing // a subsequent read lastImageContent = null; if (imageContent == null) { return null; } Trace.call2("Getting image"); Trace.call1("Making image"); image = Toolkit.getDefaultToolkit().createImage(imageContent); // Wait on the image image = ucar.unidata.ui.ImageUtils.waitOnImage(image); if (image == null) { throw new IllegalStateException(); } Trace.call2("Making image"); lastImageContent = imageContent; lastUrl = url; updateDetailsText(); if (!JobManager.getManager().canContinue(myLoadId)) { Trace.call2("WMSControl.loadImage"); return null; } synchronized (cachedUrls) { if (cachedUrls.size() > 5) { cachedUrls.remove(cachedUrls.size() - 1); cachedData.remove(cachedData.size() - 1); } // For now don't cache // cachedUrls.add(0, url); // cachedData.add(0, image); } } ImageHelper ih = new ImageHelper(); int width = image.getWidth(ih); if (ih.badImage) { throw new IllegalStateException(); } long tt1 = System.currentTimeMillis(); xyData = ucar.visad.Util.makeField(image, 0, false, true); long tt2 = System.currentTimeMillis(); // System.err.println("time to make field:" + (tt2-tt1)); } catch (Exception iexc) { if (imageContent != null) { String msg = new String(imageContent); // System.err.println ("msg:" + msg); /* Check to see if this is of the form: <?xml version='1.0' encoding="UTF-8" standalone="no" ?> <!DOCTYPE ServiceExceptionReport SYSTEM "http://www.digitalearth.gov/wmt/xml/exception_1_1_0.dtd "> <ServiceExceptionReport version="1.1.0"> <ServiceException> Service denied due to system overload. Please try again later. </ServiceException> </ServiceExceptionReport> */ if (msg.indexOf("<ServiceExceptionReport") >= 0) { try { StringBuffer errors = new StringBuffer(); errors.append("\n"); Element root = XmlUtil.getRoot(msg); List children = XmlUtil.findChildren(root, "ServiceException"); for (int i = 0; i < children.size(); i++) { Element node = (Element) children.get(i); String code = XmlUtil.getAttribute(node, "code", (String) null); String body = XmlUtil.getChildText(node); if (code != null) { errors.append(code + "\n"); } errors.append(body.trim() + "\n"); } LogUtil.userErrorMessage( "Error accessing image with the url:\n" + url + "\nError:\n" + errors); } catch (Exception exc) { LogUtil.userErrorMessage( "Error accessing image with the url:\n" + url + "\nError:\n" + StringUtil.stripTags(msg)); } return null; } msg = StringUtil.replace(msg, "\n", " ").toLowerCase(); if (StringUtil.stringMatch(msg, "service\\s*exception")) { if (StringUtil.stringMatch(msg, "cannot\\s*be\\s*less\\s*than")) { return null; } } if (msg.indexOf("error") >= 0) { LogUtil.userErrorMessage( "There was an error accessing the image with the url:\n" + url + "\nError:\n" + new String(imageContent)); return null; } } logException("There was an error accessing the image with the url:\n" + url, iexc); return null; } if (writeFile != null) { try { ImageXmlDataSource.writeToFile(writeFile, boundsToUse, imageContent, wmsInfo.getFormat()); } catch (Exception exc) { throw new IllegalArgumentException( "Error writing image xml file:" + writeFile + " " + exc); } } } Linear2DSet domain = (Linear2DSet) xyData.getDomainSet(); Linear2DSet imageDomain = new Linear2DSet( RealTupleType.SpatialEarth2DTuple, boundsToUse.getMinLon(), boundsToUse.getMaxLon(), domain.getX().getLength(), boundsToUse.getMaxLat(), boundsToUse.getMinLat(), domain.getY().getLength()); // System.err.println("image domain:" + imageDomain); /* new Linear2DSet(RealTupleType.SpatialEarth2DTuple, boundsToUse.getMinLon(), boundsToUse.getMaxLon(), domain.getX().getLength(), boundsToUse.getMinLat() +diff, boundsToUse.getMinLat(), domain.getY().getLength());*/ FieldImpl field = GridUtil.setSpatialDomain(xyData, imageDomain, true); return field; }
/** * run 'java visad.bom.ImageRendererJ3D len step' to test animation behavior of ImageRendererJ3D * renders a loop of len at step ms per frame then updates loop by deleting first time and adding * a new last time */ public static void main(String args[]) throws VisADException, RemoteException, IOException { int step = 1000; int len = 3; if (args.length > 0) { try { len = Integer.parseInt(args[0]); } catch (NumberFormatException e) { len = 3; } } if (len < 1) len = 1; if (args.length > 1) { try { step = Integer.parseInt(args[1]); } catch (NumberFormatException e) { step = 1000; } } if (step < 1) step = 1; // create a netCDF reader Plain plain = new Plain(); // open a netCDF file containing an image sequence and adapt // it to a Field Data object Field raw_image_sequence = null; try { // raw_image_sequence = (Field) plain.open("images256x256.nc"); raw_image_sequence = (Field) plain.open("images.nc"); } catch (IOException exc) { String s = "To run this example, the images.nc file must be " + "present in\nthe current directory." + "You can obtain this file from:\n" + " ftp://www.ssec.wisc.edu/pub/visad-2.0/images.nc.Z"; System.out.println(s); System.exit(0); } // just take first half of raw_image_sequence FunctionType image_sequence_type = (FunctionType) raw_image_sequence.getType(); Set raw_set = raw_image_sequence.getDomainSet(); float[][] raw_times = raw_set.getSamples(); int raw_len = raw_times[0].length; if (raw_len != 4) { throw new VisADException("wrong number of images in sequence"); } float raw_span = (4.0f / 3.0f) * (raw_times[0][3] - raw_times[0][0]); double[][] times = new double[1][len]; for (int i = 0; i < len; i++) { times[0][i] = raw_times[0][i % raw_len] + raw_span * (i / raw_len); } Gridded1DDoubleSet set = new Gridded1DDoubleSet(raw_set.getType(), times, len); Field image_sequence = new FieldImpl(image_sequence_type, set); for (int i = 0; i < len; i++) { image_sequence.setSample(i, raw_image_sequence.getSample(i % raw_len)); } // create a DataReference for image sequence final DataReference image_ref = new DataReferenceImpl("image"); image_ref.setData(image_sequence); // create a Display using Java3D DisplayImpl display = new DisplayImplJ3D("image display"); // extract the type of image and use // it to determine how images are displayed FunctionType image_type = (FunctionType) image_sequence_type.getRange(); RealTupleType domain_type = image_type.getDomain(); // map image coordinates to display coordinates display.addMap(new ScalarMap((RealType) domain_type.getComponent(0), Display.XAxis)); display.addMap(new ScalarMap((RealType) domain_type.getComponent(1), Display.YAxis)); // map image brightness values to RGB (default is grey scale) display.addMap(new ScalarMap((RealType) image_type.getRange(), Display.RGB)); RealType hour_type = (RealType) image_sequence_type.getDomain().getComponent(0); ScalarMap animation_map = new ScalarMap(hour_type, Display.Animation); display.addMap(animation_map); AnimationControl animation_control = (AnimationControl) animation_map.getControl(); animation_control.setStep(step); animation_control.setOn(true); /* // link the Display to image_ref ImageRendererJ3D renderer = new ImageRendererJ3D(); display.addReferences(renderer, image_ref); // display.addReference(image_ref); */ // create JFrame (i.e., a window) for display and slider JFrame frame = new JFrame("ImageRendererJ3D test"); frame.addWindowListener( new WindowAdapter() { public void windowClosing(WindowEvent e) { System.exit(0); } }); // create JPanel in JFrame JPanel panel = new JPanel(); panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS)); panel.setAlignmentY(JPanel.TOP_ALIGNMENT); panel.setAlignmentX(JPanel.LEFT_ALIGNMENT); frame.getContentPane().add(panel); // add display to JPanel panel.add(display.getComponent()); // set size of JFrame and make it visible frame.setSize(500, 500); frame.setVisible(true); System.out.println("first animation sequence"); // link the Display to image_ref ImageRendererJ3D renderer = new ImageRendererJ3D(); display.addReferences(renderer, image_ref); // display.addReference(image_ref); // wait 4 * len seconds new Delay(len * 4000); // substitute a new image sequence for the old one for (int i = 0; i < len; i++) { times[0][i] = raw_times[0][(i + 1) % raw_len] + raw_span * ((i + 1) / raw_len); } set = new Gridded1DDoubleSet(raw_set.getType(), times, len); FieldImpl new_image_sequence = new FieldImpl(image_sequence_type, set); for (int i = 0; i < len; i++) { new_image_sequence.setSample(i, raw_image_sequence.getSample((i + 1) % raw_len)); } System.out.println("second animation sequence"); // tell renderer to resue frames in its scene graph renderer.setReUseFrames(true); image_ref.setData(new_image_sequence); }
public static boolean isByRefUsable(DataDisplayLink link, ShadowType shadow) throws VisADException, RemoteException { ShadowFunctionOrSetType shadowType = (ShadowFunctionOrSetType) shadow.getAdaptedShadowType(); CoordinateSystem dataCoordinateSystem = null; FlatField fltField = null; int num_images = 1; FieldImpl field = (FieldImpl) link.getData(); if (!(field instanceof FlatField)) { num_images = field.getDomainSet().getLength(); if (1 == num_images) { // If there is a single image in the animation dont do anything, simply // return true return true; } shadowType = (ShadowFunctionOrSetType) shadowType.getRange(); fltField = (FlatField) field.getSample(0); dataCoordinateSystem = fltField.getDomainCoordinateSystem(); } else { dataCoordinateSystem = ((FlatField) field).getDomainCoordinateSystem(); return true; } // cs might be cached if (dataCoordinateSystem instanceof CachingCoordinateSystem) { dataCoordinateSystem = ((CachingCoordinateSystem) dataCoordinateSystem).getCachedCoordinateSystem(); } ShadowRealType[] DomainComponents = shadowType.getDomainComponents(); ShadowRealTupleType Domain = shadowType.getDomain(); ShadowRealTupleType domain_reference = Domain.getReference(); ShadowRealType[] DC = DomainComponents; if (domain_reference != null && domain_reference.getMappedDisplayScalar()) { DC = shadowType.getDomainReferenceComponents(); } DisplayTupleType spatial_tuple = null; for (int i = 0; i < DC.length; i++) { java.util.Enumeration maps = DC[i].getSelectedMapVector().elements(); ScalarMap map = (ScalarMap) maps.nextElement(); DisplayRealType real = map.getDisplayScalar(); spatial_tuple = real.getTuple(); } CoordinateSystem coord = spatial_tuple.getCoordinateSystem(); if (coord instanceof CachingCoordinateSystem) { coord = ((CachingCoordinateSystem) coord).getCachedCoordinateSystem(); } boolean useLinearTexture = false; if (coord instanceof InverseLinearScaledCS) { InverseLinearScaledCS invCS = (InverseLinearScaledCS) coord; useLinearTexture = (invCS.getInvertedCoordinateSystem()).equals(dataCoordinateSystem); } /** * if useLinearTexture is true at this point, it's true for the first image of a sequence with * numimages > 1. We'll have to assume that byRef will apply until below is resolved. */ /** * more consideration/work needed here. CoordinateSystems might be equal even if they aren't the * same transform (i,j) -> (lon,lat) if (!useLinearTexture) { //If DisplayCoordinateSystem != * DataCoordinateSystem if (num_images > 1) { //Its an animation int lengths[] = * ((visad.GriddedSet) fltField.getDomainSet()).getLengths(); int data_width = lengths[0]; int * data_height = lengths[1]; for (int i = 1; i < num_images; i++) {//Playing safe: go down the * full sequence to find if the full set is Geostaionary or NOT FlatField ff = (FlatField) * field.getSample(i); //Quicker Approach would be to just compare only the first two images in * the sequence. But that may not be safe. CoordinateSystem dcs = * ff.getDomainCoordinateSystem(); // dcs might be cached if (dcs instanceof * CachingCoordinateSystem) { dcs = ((CachingCoordinateSystem) dcs).getCachedCoordinateSystem(); * } int[] lens = ((visad.GriddedSet) ff.getDomainSet()).getLengths(); if (lens[0] != data_width * || lens[1] != data_height || ( (dcs != null) && (dataCoordinateSystem != null) && * !dcs.equals(dataCoordinateSystem))) { useLinearTexture = false; break; } } } } */ return useLinearTexture; }