file_name
stringlengths 6
86
| file_path
stringlengths 45
249
| content
stringlengths 47
6.26M
| file_size
int64 47
6.26M
| language
stringclasses 1
value | extension
stringclasses 1
value | repo_name
stringclasses 767
values | repo_stars
int64 8
14.4k
| repo_forks
int64 0
1.17k
| repo_open_issues
int64 0
788
| repo_created_at
stringclasses 767
values | repo_pushed_at
stringclasses 767
values |
---|---|---|---|---|---|---|---|---|---|---|---|
HeatChartStackWindow.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual2D/HeatChartStackWindow.java | package ezcol.visual.visual2D;
import java.awt.Button;
import java.awt.Color;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Label;
import java.awt.LayoutManager;
import java.awt.Panel;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;
import ij.IJ;
import ij.ImagePlus;
import ij.Prefs;
import ij.WindowManager;
import ij.gui.GenericDialog;
import ij.gui.ImageLayout;
import ij.gui.Overlay;
import ij.gui.Plot;
import ij.gui.PolygonRoi;
import ij.gui.Roi;
import ij.gui.StackWindow;
import ij.io.SaveDialog;
import ij.macro.Interpreter;
import ij.measure.Measurements;
import ij.measure.ResultsTable;
import ij.plugin.filter.Analyzer;
import ij.process.ByteProcessor;
import ij.process.ColorProcessor;
import ij.process.ImageProcessor;
import ij.util.Tools;
import ezcol.main.PluginConstants;
import ezcol.main.PluginStatic;
import ezcol.metric.BasicCalculator;
import ezcol.metric.MatrixCalculator;
@SuppressWarnings("serial")
public class HeatChartStackWindow extends StackWindow
implements ActionListener, ClipboardOwner, Runnable, ItemListener {
private Button list, save, copy, type, plot;
private Label coordinates;
// denotes the current plot
private HeatChart heatChart;
// private static Plots staticPlot;
// private Plots plot;
boolean layoutDone; // becomes true after the layout has been done, used by
// PlotCanvas
private String blankLabel = " ";
/**
* Save x-values only. To set, use Edit/Options/ Profile Plot Options.
*/
public static boolean saveXValues;
/**
* Automatically close window after saving values. To set, use
* Edit/Options/Profile Plot Options.
*/
public static boolean autoClose;
/**
* Display the XY coordinates in a separate window. To set, use
* Edit/Options/Profile Plot Options.
*/
public static boolean listValues;
private Roi[] rangeArrowRois; // these constitute the arrow overlays for
// changing the range
private boolean rangeArrowsVisible;
private int activeRangeArrow = -1;
// new fields
private static boolean saveRaw;
private HeatChart[] heatCharts;
// default fields from Plot
@SuppressWarnings("deprecation")
int leftMargin = Plot.LEFT_MARGIN, rightMargin = Plot.RIGHT_MARGIN, topMargin = Plot.TOP_MARGIN,
bottomMargin = Plot.BOTTOM_MARGIN;
int frameWidth; // width corresponding to plot range; frame.width is larger
// by 1
int frameHeight; // height corresponding to plot range; frame.height is
// larger by 1
Rectangle stackFrame = null;
String orgtitle = "";
public void setOrgTitle(String title) {
orgtitle = title;
}
public String getOrgTitle() {
return this.orgtitle;
}
/** Creates a PlotWindow from a Plot object. */
public HeatChartStackWindow(HeatChart heatChart) {
super(heatChart.getImagePlus());
// ((PlotCanvas)getCanvas()).setPlot(plot);
this.heatChart = heatChart;
draw();
}
/** Creates a PlotWindow from a Plot object. */
public HeatChartStackWindow(HeatChart[] heatCharts, ImagePlus imp) {
super(imp);
// ((PlotCanvas)getCanvas()).setPlot(plot);
if (heatCharts != null && heatCharts.length > 0) {
this.heatCharts = heatCharts;
this.heatChart = heatCharts[0];
draw();
}
}
/** Displays the plot. */
protected void draw() {
Panel bottomPanel = new Panel();
int hgap = IJ.isMacOSX() ? 1 : 5;
list = new Button(" List ");
list.addActionListener(this);
bottomPanel.add(list);
bottomPanel.setLayout(new FlowLayout(FlowLayout.RIGHT, hgap, 0));
save = new Button("Save...");
save.addActionListener(this);
bottomPanel.add(save);
copy = new Button(" Copy ");
copy.addActionListener(this);
bottomPanel.add(copy);
type = new Button(" Proc ");
type.addActionListener(this);
bottomPanel.add(type);
plot = new Button("Options...");
plot.addActionListener(this);
bottomPanel.add(plot);
coordinates = new Label(blankLabel);
coordinates.setFont(new Font("Monospaced", Font.PLAIN, 12));
coordinates.setBackground(new Color(220, 220, 220));
bottomPanel.add(coordinates);
add(bottomPanel);
// plot.draw();
LayoutManager lm = getLayout();
if (lm instanceof ImageLayout)
((ImageLayout) lm).ignoreNonImageWidths(true); // don't expand size
// to make the panel
// fit
pack();
ImageProcessor ip = heatChart.getProcessor();
if ((ip instanceof ColorProcessor) && (imp.getProcessor() instanceof ByteProcessor))
imp.setProcessor(null, ip);
else
imp.updateAndDraw();
layoutDone = true;
if (listValues)
showList();
else
ic.requestFocus(); // have focus on the canvas, not the button, so
// that pressing the space bar allows panning
// get the frame from plot because frame is private in plot
stackFrame = heatChart.getDrawingFrame();
frameWidth = stackFrame.width;
frameHeight = stackFrame.height;
}
@Deprecated
public void showStack() {
if ((IJ.macroRunning() && IJ.getInstance() == null) || Interpreter.isBatchMode()) {
imp = heatChart.getImagePlus();
WindowManager.setTempCurrentImage(imp);
/*
* if (getMainCurveObject() != null) { imp.setProperty("XValues",
* getXValues()); // Allows values to be retrieved by
* imp.setProperty("YValues", getYValues()); // by Plot.getValues()
* macro function } Interpreter.addBatchModeImage(imp); return null;
*/
}
if (imp != null) {
Window win = imp.getWindow();
if (win instanceof HeatChartStackWindow && win.isVisible()) {
heatChart.updateImage(); // show in existing window
}
}
if (imp == null)
imp.setProperty(Plot.PROPERTY_KEY, null);
imp = getImagePlus();
imp.setProperty(Plot.PROPERTY_KEY, this);
if (IJ.isMacro() && imp != null) // wait for plot to be displayed
IJ.selectWindow(imp.getID());
}
/** Shows the data of the backing plot in a Textwindow with columns */
void showList() {
ResultsTable rt = heatChart.getResultsTable(saveRaw);
rt.show(heatChart.getInfo(saveRaw) + " of " + orgtitle);
if (autoClose) {
imp.changes = false;
close();
}
}
/** Copy the first dataset or all values to the clipboard */
void copyToClipboard(boolean writeAllColumns) {
float[] xValues = PluginStatic.obj2floatArray(heatChart.getXValues());
float[] yValues = PluginStatic.obj2floatArray(heatChart.getYValues());
if (xValues == null)
return;
Clipboard systemClipboard = null;
try {
systemClipboard = getToolkit().getSystemClipboard();
} catch (Exception e) {
systemClipboard = null;
}
if (systemClipboard == null) {
IJ.error("Unable to copy to Clipboard.");
return;
}
IJ.showStatus("Copying plot values...");
CharArrayWriter aw = new CharArrayWriter(10 * xValues.length);
PrintWriter pw = new PrintWriter(aw); // uses platform's line
// termination characters
if (writeAllColumns) {
ResultsTable rt = heatChart.getResultsTable(saveRaw);
if (!Prefs.dontSaveHeaders) {
String headings = rt.getColumnHeadings();
pw.println(headings);
}
for (int i = 0; i < rt.size(); i++)
pw.println(rt.getRowAsString(i));
}
//legacy
/*else {
int xdigits = 0;
// if (saveXValues)
xdigits = getPrecision(xValues);
int ydigits = getPrecision(yValues);
for (int i = 0; i < Math.min(xValues.length, yValues.length); i++) {
// if (saveXValues)
// pw.println(IJ.d2s(xValues[i],xdigits)+"\t"+IJ.d2s(yValues[i],ydigits));
// else
pw.println(IJ.d2s(yValues[i], ydigits));
}
}*/
String text = aw.toString();
pw.close();
StringSelection contents = new StringSelection(text);
systemClipboard.setContents(contents, this);
IJ.showStatus(text.length() + " characters copied to Clipboard");
if (autoClose) {
imp.changes = false;
close();
}
}
/** Returns the plot values as a ResultsTable. */
public ResultsTable getResultsTable() {
return heatChart.getResultsTable(saveRaw);
}
/** Saves the data of the plot in a text file */
void saveAsText() {
if (heatChart.getZValues() == null) {
IJ.error("Plot has no data");
return;
}
SaveDialog sd = new SaveDialog("Save as Text", "Values", Prefs.defaultResultsExtension());
String name = sd.getFileName();
if (name == null)
return;
String directory = sd.getDirectory();
IJ.wait(250); // give system time to redraw ImageJ window
IJ.showStatus("Saving plot values...");
ResultsTable rt = getResultsTable();
try {
rt.saveAs(directory + name);
} catch (IOException e) {
IJ.error("" + e);
return;
}
if (autoClose) {
imp.changes = false;
close();
}
}
/**
* Creates an overlay with triangular buttons for changing the axis range
* limits and shows it
*/
void showRangeArrows() {
if (imp == null)
return;
hideRangeArrows(); // in case we have old arrows from a different plot
// size or so
rangeArrowRois = new Roi[4 * 2]; // 4 arrows per axis
int i = 0;
int height = imp.getHeight();
int arrowH = topMargin < 14 ? 6 : 8; // height of arrows and distance
// between them; base is twice
// that value
float[] yP = new float[] { height - arrowH / 2, height - 3 * arrowH / 2, height - 5 * arrowH / 2 - 0.1f };
for (float x : new float[] { leftMargin, leftMargin + frameWidth }) { // create
// arrows
// for
// x
// axis
float[] x0 = new float[] { x - arrowH / 2, x - 3 * arrowH / 2 - 0.1f, x - arrowH / 2 };
rangeArrowRois[i++] = new PolygonRoi(x0, yP, 3, Roi.POLYGON);
float[] x1 = new float[] { x + arrowH / 2, x + 3 * arrowH / 2 + 0.1f, x + arrowH / 2 };
rangeArrowRois[i++] = new PolygonRoi(x1, yP, 3, Roi.POLYGON);
}
float[] xP = new float[] { arrowH / 2 - 0.1f, 3 * arrowH / 2, 5 * arrowH / 2 + 0.1f };
for (float y : new float[] { topMargin + frameHeight, topMargin }) { // create
// arrows
// for
// y
// axis
float[] y0 = new float[] { y + arrowH / 2, y + 3 * arrowH / 2 + 0.1f, y + arrowH / 2 };
rangeArrowRois[i++] = new PolygonRoi(xP, y0, 3, Roi.POLYGON);
float[] y1 = new float[] { y - arrowH / 2, y - 3 * arrowH / 2 - 0.1f, y - arrowH / 2 };
rangeArrowRois[i++] = new PolygonRoi(xP, y1, 3, Roi.POLYGON);
}
Overlay ovly = imp.getOverlay();
if (ovly == null)
ovly = new Overlay();
for (Roi roi : rangeArrowRois) {
roi.setFillColor(Color.GRAY);
ovly.add(roi);
}
imp.setOverlay(ovly);
ic.repaint();
rangeArrowsVisible = true;
}
void hideRangeArrows() {
if (imp == null || rangeArrowRois == null)
return;
Overlay ovly = imp.getOverlay();
if (ovly == null)
return;
for (Roi roi : rangeArrowRois)
ovly.remove(roi);
ic.repaint();
rangeArrowsVisible = false;
activeRangeArrow = -1;
}
/**
* Returns the index of the range arrow at cursor position x,y, or -1 of
* none. Index numbers start with 0 at the 'down' arrow of the lower side of
* the x axis and end with the up arrow at the upper side of the y axis.
*/
int getRangeArrowIndex(int x, int y) {
if (!rangeArrowsVisible)
return -1;
for (int i = 0; i < rangeArrowRois.length; i++)
if (rangeArrowRois[i].getBounds().contains(x, y))
return i;
return -1;
}
private String d2s(double n) {
int digits = Tools.getDecimalPlaces(n);
if (digits > 2)
digits = 2;
return IJ.d2s(n, digits);
}
private void toggleDataType() {
saveRaw = !saveRaw;
if (saveRaw) {
type.setForeground(Color.red);
type.setLabel(" Raw ");
} else {
type.setForeground(Color.black);
type.setLabel(" Proc ");
}
}
private void setLogScale(boolean doLog, boolean doStack) {
if (doStack && heatCharts != null) {
for (int i = 0; i < heatCharts.length; i++) {
if (heatCharts[i] == null)
continue;
heatCharts[i].setLogScale(doLog);
}
}
if (heatChart != null)
heatChart.setLogScale(doLog);
}
private void setNumOfFTs(int[] numOfFTs, boolean doStack) {
if (doStack && heatCharts != null) {
for (int i = 0; i < heatCharts.length; i++) {
if (heatCharts[i] == null)
continue;
heatCharts[i].setNumOfFTs(numOfFTs);
}
}
if (heatChart != null)
heatChart.setNumOfFTs(numOfFTs);
}
private void setStatsMethod(int statsMethod, boolean doStack) {
if (doStack && heatCharts != null) {
for (int i = 0; i < heatCharts.length; i++) {
if (heatCharts[i] == null)
continue;
switch (statsMethod) {
case MEDIAN:
heatCharts[i].setStatsMethod(HeatChart.MEDIAN);
break;
case MEAN:
heatCharts[i].setStatsMethod(HeatChart.MEAN);
break;
case MODE:
heatCharts[i].setStatsMethod(HeatChart.MODE);
break;
default:
break;
}
}
}
if (heatChart != null) {
switch (statsMethod) {
case MEDIAN:
heatChart.setStatsMethod(HeatChart.MEDIAN);
break;
case MEAN:
heatChart.setStatsMethod(HeatChart.MEAN);
break;
case MODE:
heatChart.setStatsMethod(HeatChart.MODE);
break;
default:
break;
}
}
}
private void setCalculator(int choiceIdx) {
if (doStack && heatCharts != null) {
for (int i = 0; i < heatCharts.length; i++) {
if (heatCharts[i] == null)
continue;
heatCharts[i].setCalculator(choiceIdx);
}
}
if (heatChart != null) {
heatChart.setCalculator(choiceIdx);
}
}
public void updateImage() {
updateImage(this.doStack);
}
private void updateImage(boolean doStack) {
if (doStack && heatCharts != null) {
for (int i = 0; i < heatCharts.length; i++) {
if (heatCharts[i] == null)
continue;
heatCharts[i].updateImage();
}
}
if (heatChart != null) {
heatChart.updateImage();
stackFrame = heatChart.getDrawingFrame();
}
ic.repaint();
}
@Override
public synchronized void adjustmentValueChanged(AdjustmentEvent e) {
super.adjustmentValueChanged(e);
if (heatCharts != null && imp.getCurrentSlice() <= heatCharts.length)
heatChart = heatCharts[imp.getCurrentSlice() - 1];
}
/**
* Updates the X and Y values when the mouse is moved and, if appropriate,
* shows/hides the overlay with the triangular buttons for changing the axis
* range limits Overrides mouseMoved() in ImageWindow.
*
* @see ij.gui.ImageWindow#mouseMoved
*/
@Override
public void mouseMoved(int x, int y) {
super.mouseMoved(x, y);
if (heatChart == null)
return;
if (stackFrame == null || coordinates == null)
return;
if (stackFrame.contains(x, y))
coordinates.setText("X=" + d2s(heatChart.getX(x)) + ", Y=" + d2s(heatChart.getY(y)) + ", Z="
+ d2s(heatChart.getZ(x, y)));
else
coordinates.setText(blankLabel);
// arrows for modifying the plot range
if (x < leftMargin || y > topMargin + frameHeight) {
if (!rangeArrowsVisible)// && !plot.isFrozen())
showRangeArrows();
if (activeRangeArrow >= 0 && !rangeArrowRois[activeRangeArrow].contains(x, y)) {
rangeArrowRois[activeRangeArrow].setFillColor(Color.GRAY);
ic.repaint(); // de-highlight arrow where cursor has moved out
activeRangeArrow = -1;
}
if (activeRangeArrow < 0) { // highlight arrow below cursor (if any)
int i = getRangeArrowIndex(x, y);
if (i >= 0) { // we have an arrow at cursor position
rangeArrowRois[i].setFillColor(Color.RED);
activeRangeArrow = i;
ic.repaint();
}
}
} else if (rangeArrowsVisible)
hideRangeArrows();
}
@Override
/**
* Update the slice display by the scrollbar
*/
public void run() {
while (!done) {
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
}
}
if (done)
return;
if (slice > 0) {
int s = slice;
slice = 0;
if (s != imp.getCurrentSlice()) {
imp.setSlice(s);
heatChart = heatCharts[s - 1];
}
}
}
}
/** Called if user has activated a button or popup menu item */
@Override
public void actionPerformed(ActionEvent e) {
Object b = e.getSource();
if (b == list)
showList();
else if (b == save)
saveAsText();
else if (b == copy)
copyToClipboard(true);
else if (b == type)
toggleDataType();
else if (b == plot)
plotDialog();
if(b!=list)
ic.requestFocus(); // have focus on the canvas, not the button, so that
// pressing the space bar allows panning
}
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
// TODO Auto-generated method stub
}
// when writing data in scientific mode, use at least 4 decimals behind the
// decimal point
static final int MIN_SCIENTIFIC_DIGITS = 4;
// when writing float data, precision should be at least 1e-5*data range
static final double MIN_FLOAT_PRECISION = 1e-5;
/**
* get the number of digits for writing a column to the results table or the
* clipboard
*/
static int getPrecision(float[] values) {
int setDigits = Analyzer.getPrecision();
int measurements = Analyzer.getMeasurements();
boolean scientificNotation = (measurements & Measurements.SCIENTIFIC_NOTATION) != 0;
if (scientificNotation) {
if (setDigits < MIN_SCIENTIFIC_DIGITS)
setDigits = MIN_SCIENTIFIC_DIGITS;
return -setDigits;
}
boolean allInteger = true;
float min = Float.MAX_VALUE, max = -Float.MAX_VALUE;
for (int i = 0; i < values.length; i++) {
if ((int) values[i] != values[i] && !Float.isNaN(values[i])) {
allInteger = false;
if (values[i] < min)
min = values[i];
if (values[i] > max)
max = values[i];
}
}
if (allInteger)
return 0;
int digits = (max - min) > 0 ? getDigits(min, max, MIN_FLOAT_PRECISION * (max - min), 15)
: getDigits(max, MIN_FLOAT_PRECISION * Math.abs(max), 15);
if (setDigits > Math.abs(digits))
digits = setDigits * (digits < 0 ? -1 : 1); // use scientific
// notation if needed
return digits;
}
// Number of digits to display the number n with resolution 'resolution';
// (if n is integer and small enough to display without scientific notation,
// no decimals are needed, irrespective of 'resolution')
// Scientific notation is used for more than 'maxDigits' (must be >=3), and
// indicated
// by a negative return value
static int getDigits(double n, double resolution, int maxDigits) {
if (n == Math.round(n) && Math.abs(n) < Math.pow(10, maxDigits - 1) - 1) // integers
// and
// not
// too
// big
return 0;
else
return getDigits2(n, resolution, maxDigits);
}
// Number of digits to display the range between n1 and n2 with resolution
// 'resolution';
// Scientific notation is used for more than 'maxDigits' (must be >=3), and
// indicated
// by a negative return value
static int getDigits(double n1, double n2, double resolution, int maxDigits) {
if (n1 == 0 && n2 == 0)
return 0;
return getDigits2(Math.max(Math.abs(n1), Math.abs(n2)), resolution, maxDigits);
}
static int getDigits2(double n, double resolution, int maxDigits) {
int log10ofN = (int) Math.floor(Math.log10(Math.abs(n)) + 1e-7);
int digits = resolution != 0 ? -(int) Math.floor(Math.log10(Math.abs(resolution)) + 1e-7)
: Math.max(0, -log10ofN + maxDigits - 2);
int sciDigits = -Math.max((log10ofN + digits), 1);
// IJ.log("n="+(float)n+"digitsRaw="+digits+" log10ofN="+log10ofN+"
// sciDigits="+sciDigits);
if (digits < -2 && log10ofN >= maxDigits)
digits = sciDigits; // scientific notation for large numbers
else if (digits < 0)
digits = 0;
else if (digits > maxDigits - 1 && log10ofN < -2)
digits = sciDigits; // scientific notation for small numbers
return digits;
}
// names for popupMenu items
/*
* private static final int COPY_TYPE = 0, AXIS_OPTIONS = 2, LAST_ITEM = 3;
*
* PopupMenu getPopupMenu() { popupMenu = new PopupMenu(); menuItems = new
* MenuItem[LAST_ITEM]; menuItems[COPY_TYPE] = addPopupItem(popupMenu,
* "Raw Data", true); popupMenu.addSeparator(); menuItems[AXIS_OPTIONS] =
* addPopupItem(popupMenu, "Plot Options...");
*
* return popupMenu; }
*
* MenuItem addPopupItem(PopupMenu popupMenu, String s) { return
* addPopupItem(popupMenu, s, false); }
*
* MenuItem addPopupItem(PopupMenu popupMenu, String s, boolean
* isCheckboxItem) { MenuItem mi = null; if (isCheckboxItem) { mi = new
* CheckboxMenuItem(s); ((CheckboxMenuItem)mi).addItemListener(this); } else
* { mi = new MenuItem(s); mi.addActionListener(this); } popupMenu.add(mi);
* return mi; }
*/
@Override
public void itemStateChanged(ItemEvent e) {
// TODO Auto-generated method stub
}
private GenericDialog gd;
private static final String[] STATS_METHODS = { "Median", "Mean", "Mode" };
public static final int MEDIAN = 0, MEAN = 1, MODE = 2;
private boolean logScale, doStack;
private int[] numOfFTs = { PluginConstants.DEFAULT_FT, PluginConstants.DEFAULT_FT };
private int statsMethod = MEDIAN, choiceIdx = 0;
public static String getStatsName(int idx) {
if (idx >= 0 && idx < STATS_METHODS.length)
return STATS_METHODS[idx];
else
return null;
}
public static String[] getAllStatsMethods() {
return STATS_METHODS.clone();
}
private void plotDialog() {
boolean doStack = heatCharts != null && heatCharts.length > 1 && slice > 1;
gd = new GenericDialog("Plot Options");
String[] metricNames = BasicCalculator.getAllMetrics();
if (metricNames != null && metricNames.length > 0)
gd.addChoice("Metric", metricNames, metricNames[choiceIdx]);
// gd.addMessage("If "+metricNames[0]+" is chosen, you can also choose
// the scale:");
// TOS now is divided into TOS(linear) and TOS(log)
// gd.addCheckbox(metricNames[0]+" Log Scale", logScale);
if (doStack)
gd.addCheckbox("Apply to Stack", this.doStack);
gd.addChoice("Central Tendency", STATS_METHODS, STATS_METHODS[statsMethod]);
gd.addNumericField("Percentage (C1)", numOfFTs[0], 0);
gd.addNumericField("Percentage (C2)", numOfFTs[1], 0);
gd.showDialog();
if (gd.wasCanceled())
return;
// logScale = gd.getNextBoolean();
if (doStack)
this.doStack = gd.getNextBoolean();
else
this.doStack = false;
choiceIdx = gd.getNextChoiceIndex();
statsMethod = gd.getNextChoiceIndex();
for (int i = 0; i < numOfFTs.length; i++) {
numOfFTs[i] = (int) gd.getNextNumber();
}
logScale = metricNames[choiceIdx].equals(MatrixCalculator.SHOW_TOS_LOG2);
setLogScale(logScale, this.doStack);
setNumOfFTs(numOfFTs, this.doStack);
setStatsMethod(statsMethod, this.doStack);
setCalculator(choiceIdx);
updateImage(this.doStack);
}
// For whatever reason, I overrode
/*
* public void windowClosing(WindowEvent e) { //IJ.log("windowClosing: "
* +imp.getTitle()+" "+closed); if (closed) return; //For whatever reason,
* IJ.doCommand doesn't work here //Probably because this window cannot been
* found in WindowManager. if (ij!=null) {
* WindowManager.setCurrentWindow(this); IJ.doCommand("Close"); } else {
* setVisible(false); dispose(); WindowManager.removeWindow(this); } }
*/
}
| 23,375 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
HeatChart.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual2D/HeatChart.java | package ezcol.visual.visual2D;
/*
* Copyright 2010 Tom Castle (www.tc33.org)
* Licensed under GNU Lesser General Public License
*
* This file is part of JHeatChart - the heat maps charting api for Java.
*
* JHeatChart is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* JHeatChart is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with JHeatChart. If not, see <http://www.gnu.org/licenses/>.
*/
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;
import javax.imageio.*;
import javax.imageio.stream.FileImageOutputStream;
import ij.IJ;
import ij.ImagePlus;
import ij.measure.ResultsTable;
import ij.process.ImageProcessor;
import ezcol.cell.CellData;
import ezcol.main.PluginConstants;
import ezcol.main.PluginStatic;
import ezcol.metric.BasicCalculator;
import ezcol.metric.MatrixCalculator;
/**
* The <code>HeatChart</code> class describes a chart which can display
* 3-dimensions of values - x,y and z, where x and y are the usual 2-dimensional
* axis and z is portrayed by colour intensity. Heat charts are sometimes known
* as heat maps.
*
* <p>
* Use of this chart would typically involve 3 steps:
* <ol>
* <li>Construction of a new instance, providing the necessary z-values.</li>
* <li>Configure the visual settings.</li>
* <li>A call to either <code>getChartImage()</code> or <code>saveToFile(String)</code>.</li>
* </ol>
*
* <h3>Instantiation</h3>
* <p>
* Construction of a new <code>HeatChart</code> instance is through its one
* constructor which takes a 2-dimensional array of <tt>doubles</tt> which
* should contain the z-values for the chart. Consider this array to be
* the grid of values which will instead be represented as colours in the chart.
*
* <p>
* Setting of the x-values and y-values which are displayed along the
* appropriate axis is optional, and by default will simply display the values
* 0 to n-1, where n is the number of rows or columns. Otherwise, the x/y axis
* values can be set with the <code>setXValues</code> and <code>setYValues
* </code> methods. Both methods are overridden with two forms:
*
* <h4>Object axis values</h4>
*
* <p>
* The simplist way to set the axis values is to use the methods which take an
* array of Object[]. This array must have the same length as the number of
* columns for setXValues and same as the number of rows for setYValues. The
* string representation of the objects will then be used as the axis values.
*
* <h4>Offset and Interval</h4>
*
* <p>
* This is convenient way of defining numerical values along the axis. One of
* the two methods takes an interval and an offset for either the
* x or y axis. These parameters supply the necessary information to describe
* the values based upon the z-value indexes. The quantity of x-values and
* y-values is already known from the lengths of the z-values array dimensions.
* Then the offset parameters indicate what the first value will be, with the
* intervals providing the increment from one column or row to the next.
*
* <p>
* <strong>Consider an example:</strong>
* <blockquote><pre>
* double[][] zValues = new double[][]{
* {1.2, 1.3, 1.5},
* {1.0, 1.1, 1.6},
* {0.7, 0.9, 1.3}
* };
*
* double xOffset = 1.0;
* double yOffset = 0.0;
* double xInterval = 1.0;
* double yInterval = 2.0;
*
* chart.setXValues(xOffset, xInterval);
* chart.setYValues(yOffset, yInterval);
* </pre></blockquote>
*
* <p>In this example, the z-values range from 0.7 to 1.6. The x-values range
* from the xOffset value 1.0 to 4.0, which is calculated as the number of x-values
* multiplied by the xInterval, shifted by the xOffset of 1.0. The y-values are
* calculated in the same way to give a range of values from 0.0 to 6.0.
*
* <h3>Configuration</h3>
* <p>
* This step is optional. By default the heat chart will be generated without a
* title or labels on the axis, and the colouring of the heat map will be in
* grayscale. A large range of configuration options are available to customise
* the chart. All customisations are available through simple accessor methods.
* See the javadoc of each of the methods for more information.
*
* <h3>Output</h3>
* <p>
* The generated heat chart can be obtained in two forms, using the following
* methods:
* <ul>
* <li><strong>getChartImage()</strong> - The chart will be returned as a
* <code>BufferedImage</code> object that can be used in any number of ways,
* most notably it can be inserted into a Swing component, for use in a GUI
* application.</li>
* <li><strong>saveToFile(File)</strong> - The chart will be saved to the file
* system at the file location specified as a parameter. The image format that
* the image will be saved in is derived from the extension of the file name.</li>
* </ul>
*
* <strong>Note:</strong> The chart image will not actually be created until
* either saveToFile(File) or getChartImage() are called, and will be
* regenerated on each successive call.
*/
public class HeatChart {
/**
* A basic logarithmic scale value of 0.3.
*/
public static final double SCALE_LOGARITHMIC = 0.3;
/**
* The linear scale value of 1.0.
*/
public static final double SCALE_LINEAR = 1.0;
/**
* A basic exponential scale value of 3.0.
*/
public static final double SCALE_EXPONENTIAL = 3;
// x, y, z data values.
private double[][] zValues;
private Object[] xValues;
private Object[] yValues;
private boolean xValuesHorizontal;
private boolean yValuesHorizontal;
// General chart settings.
private Dimension cellSize;
private Dimension chartSize;
private int margin;
private Color backgroundColour;
// Title settings.
private String title;
private Font titleFont;
private Color titleColour;
private Dimension titleSize;
private int titleAscent;
// Axis settings.
private int axisThickness;
private Color axisColour;
private Font axisLabelsFont;
private Color axisLabelColour;
private String xAxisLabel;
private String yAxisLabel;
private Color axisValuesColour;
private Font axisValuesFont; // The font size will be considered the maximum font size - it may be smaller if needed to fit in.
private int xAxisValuesFrequency;
private int yAxisValuesFrequency;
private boolean showXAxisValues;
private boolean showYAxisValues;
// Generated axis properties.
private int xAxisValuesHeight;
private int xAxisValuesWidthMax;
private int yAxisValuesHeight;
private int yAxisValuesAscent;
private int yAxisValuesWidthMax;
private Dimension xAxisLabelSize;
private int xAxisLabelDescent;
private Dimension yAxisLabelSize;
private int yAxisLabelAscent;
// Heat map colour settings.
private Color highValueColour;
private Color lowValueColour;
// How many RGB steps there are between the high and low colours.
private int colourValueDistance;
private double lowValue;
private double highValue;
// Key co-ordinate positions.
private Point heatMapTL;
private Point heatMapBR;
private Point heatMapC;
// Heat map dimensions.
private Dimension heatMapSize;
// Control variable for mapping z-values to colours.
private double colourScale;
/**
* Constructs a heatmap for the given z-values against x/y-values that by
* default will be the values 0 to n-1, where n is the number of columns or
* rows.
*
* @param zValues the z-values, where each element is a row of z-values
* in the resultant heat chart.
*/
public HeatChart(double[][] zValues) {
this(zValues, min(zValues), max(zValues));
}
/**
* Constructs a heatmap for the given z-values against x/y-values that by
* default will be the values 0 to n-1, where n is the number of columns or
* rows.
*
* @param zValues the z-values, where each element is a row of z-values
* in the resultant heat chart.
* @param low the minimum possible value, which may or may not appear in the
* z-values.
* @param high the maximum possible value, which may or may not appear in
* the z-values.
*/
public HeatChart(double[][] zValues, double low, double high) {
this.zValues = zValues;
this.lowValue = low;
this.highValue = high;
// Default x/y-value settings.
setXValues(0, 1);
setYValues(0, 1);
// Default chart settings.
this.cellSize = new Dimension(20, 20);
this.margin = 20;
this.backgroundColour = Color.WHITE;
// Default title settings.
this.title = null;
this.titleFont = new Font("Sans-Serif", Font.BOLD, 16);
this.titleColour = Color.BLACK;
// Default axis settings.
this.xAxisLabel = null;
this.yAxisLabel = null;
this.axisThickness = 2;
this.axisColour = Color.BLACK;
this.axisLabelsFont = new Font("Sans-Serif", Font.PLAIN, 12);
this.axisLabelColour = Color.BLACK;
this.axisValuesColour = Color.BLACK;
this.axisValuesFont = new Font("Sans-Serif", Font.PLAIN, 10);
this.xAxisValuesFrequency = 1;
this.xAxisValuesHeight = 0;
this.xValuesHorizontal = false;
this.showXAxisValues = true;
this.showYAxisValues = true;
this.yAxisValuesFrequency = 1;
this.yAxisValuesHeight = 0;
this.yValuesHorizontal = true;
// Default heatmap settings.
this.highValueColour = Color.BLACK;
this.lowValueColour = Color.WHITE;
this.colourScale = SCALE_LINEAR;
updateColourDistance();
}
/**
* Returns the low value. This is the value at which the low value colour
* will be applied.
*
* @return the low value.
*/
public double getLowValue() {
return lowValue;
}
/**
* Returns the high value. This is the value at which the high value colour
* will be applied.
*
* @return the high value.
*/
public double getHighValue() {
return highValue;
}
/**
* Returns the 2-dimensional array of z-values currently in use. Each
* element is a double array which represents one row of the heat map, or
* all the z-values for one y-value.
*
* @return an array of the z-values in current use, that is, those values
* which will define the colour of each cell in the resultant heat map.
*/
public double[][] getZValues() {
return zValues;
}
/**
* Replaces the z-values array. See the
* {@link #setZValues(double[][], double, double)} method for an example of
* z-values. The smallest and largest values in the array are used as the
* minimum and maximum values respectively.
* @param zValues the array to replace the current array with. The number
* of elements in each inner array must be identical.
*/
public void setZValues(double[][] zValues) {
setZValues(zValues, min(zValues), max(zValues));
}
/**
* Replaces the z-values array. The number of elements should match the
* number of y-values, with each element containing a double array with
* an equal number of elements that matches the number of x-values. Use this
* method where the minimum and maximum values possible are not contained
* within the dataset.
*
* <h2>Example</h2>
*
* <blockcode><pre>
* new double[][]{
* {1.0,1.2,1.4},
* {1.2,1.3,1.5},
* {0.9,1.3,1.2},
* {0.8,1.6,1.1}
* };
* </pre></blockcode>
*
* The above zValues array is equivalent to:
*
* <table border="1">
* <tr>
* <td rowspan="4" width="20"><center><strong>y</strong></center></td>
* <td>1.0</td>
* <td>1.2</td>
* <td>1.4</td>
* </tr>
* <tr>
* <td>1.2</td>
* <td>1.3</td>
* <td>1.5</td>
* </tr>
* <tr>
* <td>0.9</td>
* <td>1.3</td>
* <td>1.2</td>
* </tr>
* <tr>
* <td>0.8</td>
* <td>1.6</td>
* <td>1.1</td>
* </tr>
* <tr>
* <td></td>
* <td colspan="3"><center><strong>x</strong></center></td>
* </tr>
* </table>
*
* @param zValues the array to replace the current array with. The number
* of elements in each inner array must be identical.
* @param low the minimum possible value, which may or may not appear in the
* z-values.
* @param high the maximum possible value, which may or may not appear in
* the z-values.
*/
public void setZValues(double[][] zValues, double low, double high) {
this.zValues = zValues;
this.lowValue = low;
this.highValue = high;
}
/**
* Sets the x-values which are plotted along the x-axis. The x-values are
* calculated based upon the indexes of the z-values array:
*
* <blockcode><pre>
* x-value = x-offset + (column-index * x-interval)
* </pre></blockcode>
*
* <p>The x-interval defines the gap between each x-value and the x-offset
* is applied to each value to offset them all from zero.
*
* <p>Alternatively the x-values can be set more directly with the
* <code>setXValues(Object[])</code> method.
*
* @param xOffset an offset value to be applied to the index of each z-value
* element.
* @param xInterval an interval that will separate each x-value item.
*/
public void setXValues(double xOffset, double xInterval) {
// Update the x-values according to the offset and interval.
xValues = new Object[zValues[0].length];
for (int i=0; i<zValues[0].length; i++) {
xValues[i] = xOffset + (i * xInterval);
}
}
/**
* Sets the x-values which are plotted along the x-axis. The given x-values
* array must be the same length as the z-values array has columns. Each
* of the x-values elements will be displayed according to their toString
* representation.
*
* @param xValues an array of elements to be displayed as values along the
* x-axis.
*/
public void setXValues(Object[] xValues) {
this.xValues = xValues;
}
/**
* Sets the y-values which are plotted along the y-axis. The y-values are
* calculated based upon the indexes of the z-values array:
*
* <blockcode><pre>
* y-value = y-offset + (column-index * y-interval)
* </pre></blockcode>
*
* <p>The y-interval defines the gap between each y-value and the y-offset
* is applied to each value to offset them all from zero.
*
* <p>Alternatively the y-values can be set more directly with the
* <code>setYValues(Object[])</code> method.
*
* @param yOffset an offset value to be applied to the index of each z-value
* element.
* @param yInterval an interval that will separate each y-value item.
*/
public void setYValues(double yOffset, double yInterval) {
// Update the y-values according to the offset and interval.
yValues = new Object[zValues.length];
for (int i=0; i<zValues.length; i++) {
yValues[i] = yOffset + (i * yInterval);
}
}
/**
* Sets the y-values which are plotted along the y-axis. The given y-values
* array must be the same length as the z-values array has columns. Each
* of the y-values elements will be displayed according to their toString
* representation.
*
* @param yValues an array of elements to be displayed as values along the
* y-axis.
*/
public void setYValues(Object[] yValues) {
this.yValues = yValues;
}
/**
* Returns the x-values which are currently set to display along the x-axis.
* The array that is returned is either that which was explicitly set with
* <code>setXValues(Object[])</code> or that was generated from the offset
* and interval that were given to <code>setXValues(double, double)</code>,
* in which case the object type of each element will be <code>Double</code>.
*
* @return an array of the values that are to be displayed along the x-axis.
*/
public Object[] getXValues() {
return xValues;
}
/**
* Returns the y-values which are currently set to display along the y-axis.
* The array that is returned is either that which was explicitly set with
* <code>setYValues(Object[])</code> or that was generated from the offset
* and interval that were given to <code>setYValues(double, double)</code>,
* in which case the object type of each element will be <code>Double</code>.
*
* @return an array of the values that are to be displayed along the y-axis.
*/
public Object[] getYValues() {
return yValues;
}
/**
* Sets whether the text of the values along the x-axis should be drawn
* horizontally left-to-right, or vertically top-to-bottom.
*
* @param xValuesHorizontal true if x-values should be drawn horizontally,
* false if they should be drawn vertically.
*/
public void setXValuesHorizontal(boolean xValuesHorizontal) {
this.xValuesHorizontal = xValuesHorizontal;
}
/**
* Returns whether the text of the values along the x-axis are to be drawn
* horizontally left-to-right, or vertically top-to-bottom.
*
* @return true if the x-values will be drawn horizontally, false if they
* will be drawn vertically.
*/
public boolean isXValuesHorizontal() {
return xValuesHorizontal;
}
/**
* Sets whether the text of the values along the y-axis should be drawn
* horizontally left-to-right, or vertically top-to-bottom.
*
* @param yValuesHorizontal true if y-values should be drawn horizontally,
* false if they should be drawn vertically.
*/
public void setYValuesHorizontal(boolean yValuesHorizontal) {
this.yValuesHorizontal = yValuesHorizontal;
}
/**
* Returns whether the text of the values along the y-axis are to be drawn
* horizontally left-to-right, or vertically top-to-bottom.
*
* @return true if the y-values will be drawn horizontally, false if they
* will be drawn vertically.
*/
public boolean isYValuesHorizontal() {
return yValuesHorizontal;
}
/**
* Sets the width of each individual cell that constitutes a value in x,y,z
* data space. By setting the cell width, any previously set chart width
* will be overwritten with a value calculated based upon this value and the
* number of cells in there are along the x-axis.
*
* @param cellWidth the new width to use for each individual data cell.
* @deprecated As of release 0.6, replaced by {@link #setCellSize(Dimension)}
*/
@Deprecated
public void setCellWidth(int cellWidth) {
setCellSize(new Dimension(cellWidth, cellSize.height));
}
/**
* Returns the width of each individual data cell that constitutes a value
* in the x,y,z space.
*
* @return the width of each cell.
* @deprecated As of release 0.6, replaced by {@link #getCellSize}
*/
@Deprecated
public int getCellWidth() {
return cellSize.width;
}
/**
* Sets the height of each individual cell that constitutes a value in x,y,z
* data space. By setting the cell height, any previously set chart height
* will be overwritten with a value calculated based upon this value and the
* number of cells in there are along the y-axis.
*
* @param cellHeight the new height to use for each individual data cell.
* @deprecated As of release 0.6, replaced by {@link #setCellSize(Dimension)}
*/
@Deprecated
public void setCellHeight(int cellHeight) {
setCellSize(new Dimension(cellSize.width, cellHeight));
}
/**
* Returns the height of each individual data cell that constitutes a value
* in the x,y,z space.
*
* @return the height of each cell.
* @deprecated As of release 0.6, replaced by {@link #getCellSize()}
*/
@Deprecated
public int getCellHeight() {
return cellSize.height;
}
/**
* Sets the size of each individual cell that constitutes a value in x,y,z
* data space. By setting the cell size, any previously set chart size will
* be overwritten with a value calculated based upon this value and the
* number of cells along each axis.
*
* @param cellSize the new size to use for each individual data cell.
* @since 0.6
*/
public void setCellSize(Dimension cellSize) {
this.cellSize = cellSize;
}
/**
* Returns the size of each individual data cell that constitutes a value in
* the x,y,z space.
*
* @return the size of each individual data cell.
* @since 0.6
*/
public Dimension getCellSize() {
return cellSize;
}
/**
* Returns the width of the chart in pixels as calculated according to the
* cell dimensions, chart margin and other size settings.
*
* @return the width in pixels of the chart image to be generated.
* @deprecated As of release 0.6, replaced by {@link #getChartSize()}
*/
@Deprecated
public int getChartWidth() {
return chartSize.width;
}
/**
* Returns the height of the chart in pixels as calculated according to the
* cell dimensions, chart margin and other size settings.
*
* @return the height in pixels of the chart image to be generated.
* @deprecated As of release 0.6, replaced by {@link #getChartSize()}
*/
@Deprecated
public int getChartHeight() {
return chartSize.height;
}
/**
* Returns the size of the chart in pixels as calculated according to the
* cell dimensions, chart margin and other size settings.
*
* @return the size in pixels of the chart image to be generated.
* @since 0.6
*/
public Dimension getChartSize() {
return chartSize;
}
/**
* Returns the String that will be used as the title of any successive
* calls to generate a chart.
*
* @return the title of the chart.
*/
public String getTitle() {
return title;
}
/**
* Sets the String that will be used as the title of any successive
* calls to generate a chart. The title will be displayed centralised
* horizontally at the top of any generated charts.
*
* <p>
* If the title is set to <tt>null</tt> then no title will be displayed.
*
* <p>
* Defaults to null.
*
* @param title the chart title to set.
*/
public void setTitle(String title) {
this.title = title;
}
/**
* Returns the String that will be displayed as a description of the
* x-axis in any generated charts.
*
* @return the display label describing the x-axis.
*/
public String getXAxisLabel() {
return xAxisLabel;
}
/**
* Sets the String that will be displayed as a description of the
* x-axis in any generated charts. The label will be displayed
* horizontally central of the x-axis bar.
*
* <p>
* If the xAxisLabel is set to <tt>null</tt> then no label will be
* displayed.
*
* <p>
* Defaults to null.
*
* @param xAxisLabel the label to be displayed describing the x-axis.
*/
public void setXAxisLabel(String xAxisLabel) {
this.xAxisLabel = xAxisLabel;
}
/**
* Returns the String that will be displayed as a description of the
* y-axis in any generated charts.
*
* @return the display label describing the y-axis.
*/
public String getYAxisLabel() {
return yAxisLabel;
}
/**
* Sets the String that will be displayed as a description of the
* y-axis in any generated charts. The label will be displayed
* horizontally central of the y-axis bar.
*
* <p>
* If the yAxisLabel is set to <tt>null</tt> then no label will be
* displayed.
*
* <p>
* Defaults to null.
*
* @param yAxisLabel the label to be displayed describing the y-axis.
*/
public void setYAxisLabel(String yAxisLabel) {
this.yAxisLabel = yAxisLabel;
}
/**
* Returns the width of the margin in pixels to be left as empty space
* around the heat map element.
*
* @return the size of the margin to be left blank around the edge of the
* chart.
*/
public int getChartMargin() {
return margin;
}
/**
* Sets the width of the margin in pixels to be left as empty space around
* the heat map element. If a title is set then half the margin will be
* directly above the title and half directly below it. Where axis labels
* are set then the axis labels may sit partially in the margin.
*
* <p>
* Defaults to 20 pixels.
*
* @param margin the new margin to be left as blank space around the heat
* map.
*/
public void setChartMargin(int margin) {
this.margin = margin;
}
/**
* Returns an object that represents the colour to be used as the
* background for the whole chart.
*
* @return the colour to be used to fill the chart background.
*/
public Color getBackgroundColour() {
return backgroundColour;
}
/**
* Sets the colour to be used on the background of the chart. A transparent
* background can be set by setting a background colour with an alpha value.
* The transparency will only be effective when the image is saved as a png
* or gif.
*
* <p>
* Defaults to <code>Color.WHITE</code>.
*
* @param backgroundColour the new colour to be set as the background fill.
*/
public void setBackgroundColour(Color backgroundColour) {
if (backgroundColour == null) {
backgroundColour = Color.WHITE;
}
this.backgroundColour = backgroundColour;
}
/**
* Returns the <code>Font</code> that describes the visual style of the
* title.
*
* @return the Font that will be used to render the title.
*/
public Font getTitleFont() {
return titleFont;
}
/**
* Sets a new <code>Font</code> to be used in rendering the chart's title
* String.
*
* <p>
* Defaults to Sans-Serif, BOLD, 16 pixels.
*
* @param titleFont the Font that should be used when rendering the chart
* title.
*/
public void setTitleFont(Font titleFont) {
this.titleFont = titleFont;
}
/**
* Returns the <code>Color</code> that represents the colour the title text
* should be painted in.
*
* @return the currently set colour to be used in painting the chart title.
*/
public Color getTitleColour() {
return titleColour;
}
/**
* Sets the <code>Color</code> that describes the colour to be used for the
* chart title String.
*
* <p>
* Defaults to <code>Color.BLACK</code>.
*
* @param titleColour the colour to paint the chart's title String.
*/
public void setTitleColour(Color titleColour) {
this.titleColour = titleColour;
}
/**
* Returns the width of the axis bars in pixels. Both axis bars have the
* same thickness.
*
* @return the thickness of the axis bars in pixels.
*/
public int getAxisThickness() {
return axisThickness;
}
/**
* Sets the width of the axis bars in pixels. Both axis bars use the same
* thickness.
*
* <p>
* Defaults to 2 pixels.
*
* @param axisThickness the thickness to use for the axis bars in any newly
* generated charts.
*/
public void setAxisThickness(int axisThickness) {
this.axisThickness = axisThickness;
}
/**
* Returns the colour that is set to be used for the axis bars. Both axis
* bars use the same colour.
*
* @return the colour in use for the axis bars.
*/
public Color getAxisColour() {
return axisColour;
}
/**
* Sets the colour to be used on the axis bars. Both axis bars use the same
* colour.
*
* <p>
* Defaults to <code>Color.BLACK</code>.
*
* @param axisColour the colour to be set for use on the axis bars.
*/
public void setAxisColour(Color axisColour) {
this.axisColour = axisColour;
}
/**
* Returns the font that describes the visual style of the labels of the
* axis. Both axis' labels use the same font.
*
* @return the font used to define the visual style of the axis labels.
*/
public Font getAxisLabelsFont() {
return axisLabelsFont;
}
/**
* Sets the font that describes the visual style of the axis labels. Both
* axis' labels use the same font.
*
* <p>
* Defaults to Sans-Serif, PLAIN, 12 pixels.
*
* @param axisLabelsFont the font to be used to define the visual style of
* the axis labels.
*/
public void setAxisLabelsFont(Font axisLabelsFont) {
this.axisLabelsFont = axisLabelsFont;
}
/**
* Returns the current colour of the axis labels. Both labels use the same
* colour.
*
* @return the colour of the axis label text.
*/
public Color getAxisLabelColour() {
return axisLabelColour;
}
/**
* Sets the colour of the text displayed as axis labels. Both labels use
* the same colour.
*
* <p>
* Defaults to Color.BLACK.
*
* @param axisLabelColour the colour to use for the axis label text.
*/
public void setAxisLabelColour(Color axisLabelColour) {
this.axisLabelColour = axisLabelColour;
}
/**
* Returns the font which describes the visual style of the axis values.
* The axis values are those values displayed alongside the axis bars at
* regular intervals. Both axis use the same font.
*
* @return the font in use for the axis values.
*/
public Font getAxisValuesFont() {
return axisValuesFont;
}
/**
* Sets the font which describes the visual style of the axis values. The
* axis values are those values displayed alongside the axis bars at
* regular intervals. Both axis use the same font.
*
* <p>
* Defaults to Sans-Serif, PLAIN, 10 pixels.
*
* @param axisValuesFont the font that should be used for the axis values.
*/
public void setAxisValuesFont(Font axisValuesFont) {
this.axisValuesFont = axisValuesFont;
}
/**
* Returns the colour of the axis values as they will be painted along the
* axis bars. Both axis use the same colour.
*
* @return the colour of the values displayed along the axis bars.
*/
public Color getAxisValuesColour() {
return axisValuesColour;
}
/**
* Sets the colour to be used for the axis values as they will be painted
* along the axis bars. Both axis use the same colour.
*
* <p>
* Defaults to Color.BLACK.
*
* @param axisValuesColour the new colour to be used for the axis bar values.
*/
public void setAxisValuesColour(Color axisValuesColour) {
this.axisValuesColour = axisValuesColour;
}
/**
* Returns the frequency of the values displayed along the x-axis. The
* frequency is how many columns in the x-dimension have their value
* displayed. A frequency of 2 would mean every other column has a value
* shown and a frequency of 3 would mean every third column would be given a
* value.
*
* @return the frequency of the values displayed against columns.
*/
public int getXAxisValuesFrequency() {
return xAxisValuesFrequency;
}
/**
* Sets the frequency of the values displayed along the x-axis. The
* frequency is how many columns in the x-dimension have their value
* displayed. A frequency of 2 would mean every other column has a value and
* a frequency of 3 would mean every third column would be given a value.
*
* <p>
* Defaults to 1. Every column is given a value.
*
* @param axisValuesFrequency the frequency of the values displayed against
* columns, where 1 is every column and 2 is every other column.
*/
public void setXAxisValuesFrequency(int axisValuesFrequency) {
this.xAxisValuesFrequency = axisValuesFrequency;
}
/**
* Returns the frequency of the values displayed along the y-axis. The
* frequency is how many rows in the y-dimension have their value displayed.
* A frequency of 2 would mean every other row has a value and a frequency
* of 3 would mean every third row would be given a value.
*
* @return the frequency of the values displayed against rows.
*/
public int getYAxisValuesFrequency() {
return yAxisValuesFrequency;
}
/**
* Sets the frequency of the values displayed along the y-axis. The
* frequency is how many rows in the y-dimension have their value displayed.
* A frequency of 2 would mean every other row has a value and a frequency
* of 3 would mean every third row would be given a value.
*
* <p>
* Defaults to 1. Every row is given a value.
*
* @param axisValuesFrequency the frequency of the values displayed against
* rows, where 1 is every row and 2 is every other row.
*/
public void setYAxisValuesFrequency(int axisValuesFrequency) {
yAxisValuesFrequency = axisValuesFrequency;
}
/**
* Returns whether axis values are to be shown at all for the x-axis.
*
* <p>
* If axis values are not shown then more space is allocated to the heat
* map.
*
* @return true if the x-axis values will be displayed, false otherwise.
*/
public boolean isShowXAxisValues() {
//TODO Could get rid of these flags and use a frequency of -1 to signal no values.
return showXAxisValues;
}
/**
* Sets whether axis values are to be shown at all for the x-axis.
*
* <p>
* If axis values are not shown then more space is allocated to the heat
* map.
*
* <p>
* Defaults to true.
*
* @param showXAxisValues true if x-axis values should be displayed, false
* if they should be hidden.
*/
public void setShowXAxisValues(boolean showXAxisValues) {
this.showXAxisValues = showXAxisValues;
}
/**
* Returns whether axis values are to be shown at all for the y-axis.
*
* <p>
* If axis values are not shown then more space is allocated to the heat
* map.
*
* @return true if the y-axis values will be displayed, false otherwise.
*/
public boolean isShowYAxisValues() {
return showYAxisValues;
}
/**
* Sets whether axis values are to be shown at all for the y-axis.
*
* <p>
* If axis values are not shown then more space is allocated to the heat
* map.
*
* <p>
* Defaults to true.
*
* @param showYAxisValues true if y-axis values should be displayed, false
* if they should be hidden.
*/
public void setShowYAxisValues(boolean showYAxisValues) {
this.showYAxisValues = showYAxisValues;
}
/**
* Returns the colour that is currently to be displayed for the heat map
* cells with the highest z-value in the dataset.
*
* <p>
* The full colour range will go through each RGB step between the high
* value colour and the low value colour.
*
* @return the colour in use for cells of the highest z-value.
*/
public Color getHighValueColour() {
return highValueColour;
}
/**
* Sets the colour to be used to fill cells of the heat map with the
* highest z-values in the dataset.
*
* <p>
* The full colour range will go through each RGB step between the high
* value colour and the low value colour.
*
* <p>
* Defaults to Color.BLACK.
*
* @param highValueColour the colour to use for cells of the highest
* z-value.
*/
public void setHighValueColour(Color highValueColour) {
this.highValueColour = highValueColour;
updateColourDistance();
}
/**
* Returns the colour that is currently to be displayed for the heat map
* cells with the lowest z-value in the dataset.
*
* <p>
* The full colour range will go through each RGB step between the high
* value colour and the low value colour.
*
* @return the colour in use for cells of the lowest z-value.
*/
public Color getLowValueColour() {
return lowValueColour;
}
/**
* Sets the colour to be used to fill cells of the heat map with the
* lowest z-values in the dataset.
*
* <p>
* The full colour range will go through each RGB step between the high
* value colour and the low value colour.
*
* <p>
* Defaults to Color.WHITE.
*
* @param lowValueColour the colour to use for cells of the lowest
* z-value.
*/
public void setLowValueColour(Color lowValueColour) {
this.lowValueColour = lowValueColour;
updateColourDistance();
}
/**
* Returns the scale that is currently in use to map z-value to colour. A
* value of 1.0 will give a <strong>linear</strong> scale, which will
* spread the distribution of colours evenly amoungst the full range of
* represented z-values. A value of greater than 1.0 will give an
* <strong>exponential</strong> scale that will produce greater emphasis
* for the separation between higher values and a value between 0.0 and 1.0
* will provide a <strong>logarithmic</strong> scale, with greater
* separation of low values.
*
* @return the scale factor that is being used to map from z-value to colour.
*/
public double getColourScale() {
return colourScale;
}
/**
* Sets the scale that is currently in use to map z-value to colour. A
* value of 1.0 will give a <strong>linear</strong> scale, which will
* spread the distribution of colours evenly amoungst the full range of
* represented z-values. A value of greater than 1.0 will give an
* <strong>exponential</strong> scale that will produce greater emphasis
* for the separation between higher values and a value between 0.0 and 1.0
* will provide a <strong>logarithmic</strong> scale, with greater
* separation of low values. Values of 0.0 or less are illegal.
*
* <p>
* Defaults to a linear scale value of 1.0.
*
* @param colourScale the scale that should be used to map from z-value to
* colour.
*/
public void setColourScale(double colourScale) {
this.colourScale = colourScale;
}
/*
* Calculate and update the field for the distance between the low colour
* and high colour. The distance is the number of steps between one colour
* and the other using an RGB coding with 0-255 values for each of red,
* green and blue. So the maximum colour distance is 255 + 255 + 255.
*/
private void updateColourDistance() {
int r1 = lowValueColour.getRed();
int g1 = lowValueColour.getGreen();
int b1 = lowValueColour.getBlue();
int r2 = highValueColour.getRed();
int g2 = highValueColour.getGreen();
int b2 = highValueColour.getBlue();
colourValueDistance = Math.abs(r1 - r2);
colourValueDistance += Math.abs(g1 - g2);
colourValueDistance += Math.abs(b1 - b2);
}
/**
* Generates a new chart <code>Image</code> based upon the currently held
* settings and then attempts to save that image to disk, to the location
* provided as a File parameter. The image type of the saved file will
* equal the extension of the filename provided, so it is essential that a
* suitable extension be included on the file name.
*
* <p>
* All supported <code>ImageIO</code> file types are supported, including
* PNG, JPG and GIF.
*
* <p>
* No chart will be generated until this or the related
* <code>getChartImage()</code> method are called. All successive calls
* will result in the generation of a new chart image, no caching is used.
*
* @param outputFile the file location that the generated image file should
* be written to. The File must have a suitable filename, with an extension
* of a valid image format (as supported by <code>ImageIO</code>).
* @throws IOException if the output file's filename has no extension or
* if there the file is unable to written to. Reasons for this include a
* non-existant file location (check with the File exists() method on the
* parent directory), or the permissions of the write location may be
* incorrect.
*/
public void saveToFile(File outputFile) throws IOException {
String filename = outputFile.getName();
int extPoint = filename.lastIndexOf('.');
if (extPoint < 0) {
throw new IOException("Illegal filename, no extension used.");
}
// Determine the extension of the filename.
String ext = filename.substring(extPoint + 1);
// Handle jpg without transparency.
if (ext.toLowerCase().equals("jpg") || ext.toLowerCase().equals("jpeg")) {
BufferedImage chart = (BufferedImage) getChartImage(false);
// Save our graphic.
saveGraphicJpeg(chart, outputFile, 1.0f);
} else {
BufferedImage chart = (BufferedImage) getChartImage(true);
ImageIO.write(chart, ext, outputFile);
}
}
private void saveGraphicJpeg(BufferedImage chart, File outputFile, float quality) throws IOException {
// Setup correct compression for jpeg.
Iterator<ImageWriter> iter = ImageIO.getImageWritersByFormatName("jpeg");
ImageWriter writer = (ImageWriter) iter.next();
ImageWriteParam iwp = writer.getDefaultWriteParam();
iwp.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
iwp.setCompressionQuality(quality);
// Output the image.
FileImageOutputStream output = new FileImageOutputStream(outputFile);
writer.setOutput(output);
IIOImage image = new IIOImage(chart, null, null);
writer.write(null, image, iwp);
writer.dispose();
}
/**
* Generates and returns a new chart <code>Image</code> configured
* according to this object's currently held settings. The given parameter
* determines whether transparency should be enabled for the generated
* image.
*
* <p>
* No chart will be generated until this or the related
* <code>saveToFile(File)</code> method are called. All successive calls
* will result in the generation of a new chart image, no caching is used.
*
* @param alpha whether to enable transparency.
* @return A newly generated chart <code>Image</code>. The returned image
* is a <code>BufferedImage</code>.
*/
public Image getChartImage(boolean alpha) {
// Calculate all unknown dimensions.
//Customize here to allow chartSize to be kept
measureComponents(fixChart);
//This is now incorporated into measureComponents;
//updateCoordinates();
// Determine image type based upon whether require alpha or not.
// Using BufferedImage.TYPE_INT_ARGB seems to break on jpg.
int imageType = (alpha ? BufferedImage.TYPE_4BYTE_ABGR : BufferedImage.TYPE_3BYTE_BGR);
// Create our chart image which we will eventually draw everything on.
BufferedImage chartImage = new BufferedImage(chartSize.width, chartSize.height, imageType);
Graphics2D chartGraphics = chartImage.createGraphics();
// Use anti-aliasing where ever possible.
chartGraphics.setRenderingHint(RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON);
// Set the background.
chartGraphics.setColor(backgroundColour);
chartGraphics.fillRect(0, 0, chartSize.width, chartSize.height);
// Draw the title.
drawTitle(chartGraphics);
// Draw the heatmap image.
drawHeatMap(chartGraphics, zValues);
// Draw the axis labels.
drawXLabel(chartGraphics);
drawYLabel(chartGraphics);
// Draw the axis bars.
drawAxisBars(chartGraphics);
// Draw axis values.
drawXValues(chartGraphics);
drawYValues(chartGraphics);
/**customized code draw colorbar and labels**/
drawColorBar(chartGraphics);
drawColorBarValues(chartGraphics);
return chartImage;
}
/**
* Generates and returns a new chart <code>Image</code> configured
* according to this object's currently held settings. By default the image
* is generated with no transparency.
*
* <p>
* No chart will be generated until this or the related
* <code>saveToFile(File)</code> method are called. All successive calls
* will result in the generation of a new chart image, no caching is used.
*
* @return A newly generated chart <code>Image</code>. The returned image
* is a <code>BufferedImage</code>.
*/
public Image getChartImage() {
return getChartImage(false);
}
/*
* Calculates all unknown component dimensions.
*/
private void measureComponents() {
//TODO This would be a good place to check that all settings have sensible values or throw illegal state exception.
//TODO Put this somewhere so it only gets created once.
BufferedImage chartImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D tempGraphics = chartImage.createGraphics();
// Calculate title dimensions.
if (title != null) {
tempGraphics.setFont(titleFont);
FontMetrics metrics = tempGraphics.getFontMetrics();
titleSize = new Dimension(metrics.stringWidth(title), metrics.getHeight());
titleAscent = metrics.getAscent();
} else {
titleSize = new Dimension(0, 0);
}
// Calculate x-axis label dimensions.
if (xAxisLabel != null) {
tempGraphics.setFont(axisLabelsFont);
FontMetrics metrics = tempGraphics.getFontMetrics();
xAxisLabelSize = new Dimension(metrics.stringWidth(xAxisLabel), metrics.getHeight());
xAxisLabelDescent = metrics.getDescent();
} else {
xAxisLabelSize = new Dimension(0, 0);
}
// Calculate y-axis label dimensions.
if (yAxisLabel != null) {
tempGraphics.setFont(axisLabelsFont);
FontMetrics metrics = tempGraphics.getFontMetrics();
yAxisLabelSize = new Dimension(metrics.stringWidth(yAxisLabel), metrics.getHeight());
yAxisLabelAscent = metrics.getAscent();
} else {
yAxisLabelSize = new Dimension(0, 0);
}
// Calculate x-axis value dimensions.
if (showXAxisValues) {
tempGraphics.setFont(axisValuesFont);
FontMetrics metrics = tempGraphics.getFontMetrics();
xAxisValuesHeight = metrics.getHeight();
xAxisValuesWidthMax = 0;
for (Object o: xValues) {
//Customsize here to make sure there are at least LABEL_LENGTH digit space reserved
int w = metrics.stringWidth(formatStr(o.toString()));
if (w > xAxisValuesWidthMax) {
xAxisValuesWidthMax = w;
}
}
} else {
xAxisValuesHeight = 0;
}
// Calculate y-axis value dimensions.
if (showYAxisValues) {
tempGraphics.setFont(axisValuesFont);
FontMetrics metrics = tempGraphics.getFontMetrics();
yAxisValuesHeight = metrics.getHeight();
yAxisValuesAscent = metrics.getAscent();
yAxisValuesWidthMax = 0;
for (Object o: yValues) {
//Customsize here to make sure there are at least LABEL_LENGTH digit space reserved
int w = metrics.stringWidth(formatStr(o.toString()));
if (w > yAxisValuesWidthMax) {
yAxisValuesWidthMax = w;
}
}
} else {
yAxisValuesHeight = 0;
}
// Calculate heatmap dimensions.
/**
* Custom comment here
* I have no idea why the author flip x and y axis
* Normally, the first dimension is x and the second is y
* Therefore, heatMapWidth should be the length of the first dimension
* and heatMapHeight is that of the second.
*/
int heatMapWidth = (zValues.length * cellSize.width);
int heatMapHeight = (zValues[0].length * cellSize.height);
heatMapSize = new Dimension(heatMapWidth, heatMapHeight);
int yValuesHorizontalSize = 0;
if (yValuesHorizontal) {
yValuesHorizontalSize = yAxisValuesWidthMax;
} else {
yValuesHorizontalSize = yAxisValuesHeight;
}
int xValuesVerticalSize = 0;
if (xValuesHorizontal) {
xValuesVerticalSize = xAxisValuesHeight;
} else {
xValuesVerticalSize = xAxisValuesWidthMax;
}
// Calculate colorbar value dimensions.
if (showColorBarValues) {
tempGraphics.setFont(colorValuesFont);
FontMetrics metrics = tempGraphics.getFontMetrics();
colorBarValuesHeight = metrics.getHeight();
colorBarValuesAscent = metrics.getAscent();
colorBarValuesWidthMax = 0;
for (Object o: colorBarValues) {
//Customsize here to make sure there are at least LABEL_LENGTH digit space reserved
int w = metrics.stringWidth(formatStr(o.toString()));
if (w > colorBarValuesWidthMax) {
colorBarValuesWidthMax = w;
}
}
} else {
colorBarValuesHeight = 0;
}
int colorValuesHorizontalSize = 0;
if (colorBarValuesHorizontal) {
colorValuesHorizontalSize = colorBarValuesWidthMax;
} else {
colorValuesHorizontalSize = colorBarValuesHeight;
}
// Calculate chart dimensions.
/**int chartWidth = heatMapWidth + (2 * margin) + yAxisLabelSize.height + yValuesHorizontalSize + axisThickness;
int chartHeight = heatMapHeight + (2 * margin) + xAxisLabelSize.height + xValuesVerticalSize + titleSize.height + axisThickness;
chartSize = new Dimension(chartWidth, chartHeight);**/
//Customized size so that colorbar could fit in and labels have more room
int chartWidth = heatMapWidth + (5 * margin) + yAxisLabelSize.height + colorBarWidth + colorValuesHorizontalSize + yValuesHorizontalSize + axisThickness*2;
int chartHeight = heatMapHeight + (3 * margin) + xAxisLabelSize.height + xValuesVerticalSize + titleSize.height + axisThickness;
chartSize = new Dimension(chartWidth, chartHeight);
}
/*
* Calculates the co-ordinates of some key positions.
*/
private void updateCoordinates() {
// Top-left of heat map.
// customized code give more space to the left
int x = margin * 2 + axisThickness + yAxisLabelSize.height;
x += (yValuesHorizontal ? yAxisValuesWidthMax : yAxisValuesHeight);
int y = titleSize.height + margin;
heatMapTL = new Point(x, y);
// Top-right of heat map.
x = heatMapTL.x + heatMapSize.width;
y = heatMapTL.y + heatMapSize.height;
heatMapBR = new Point(x, y);
// Centre of heat map.
x = heatMapTL.x + (heatMapSize.width / 2);
y = heatMapTL.y + (heatMapSize.height / 2);
heatMapC = new Point(x, y);
}
/*
* Draws the title String on the chart if title is not null.
*/
private void drawTitle(Graphics2D chartGraphics) {
if (title != null) {
// Strings are drawn from the baseline position of the leftmost char.
int yTitle = (margin/2) + titleAscent;
int xTitle = (heatMapTL.x+heatMapSize.width/2)-(titleSize.width/2);
chartGraphics.setFont(titleFont);
chartGraphics.setColor(titleColour);
chartGraphics.drawString(title, xTitle, yTitle);
}
}
/*
* Creates the actual heatmap element as an image, that can then be drawn
* onto a chart.
*/
private void drawHeatMap(Graphics2D chartGraphics, double[][] data) {
// Calculate the available size for the heatmap.
int noXCells = data.length;
int noYCells = data[0].length;
//double dataMin = min(data);
//double dataMax = max(data);
BufferedImage heatMapImage = new BufferedImage(heatMapSize.width, heatMapSize.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D heatMapGraphics = heatMapImage.createGraphics();
for (int x=0; x<noXCells; x++) {
for (int y=0; y<noYCells; y++) {
// Set colour depending on zValues.
/*** change it to accept three colours gradient***/
if(Double.isNaN(data[x][y]))
heatMapGraphics.setColor(nanValueColour);
else if(withMiddle)
heatMapGraphics.setColor(getCellColour(data[x][y], lowValue, middleValue, highValue));
else
heatMapGraphics.setColor(getCellColour(data[x][y], lowValue, highValue));
int cellX = x * cellSize.width;
int cellY = y * cellSize.height;
heatMapGraphics.fillRect(cellX, cellY, cellSize.width, cellSize.height);
}
}
// Draw the heat map onto the chart.
chartGraphics.drawImage(heatMapImage, heatMapTL.x, heatMapTL.y, heatMapSize.width, heatMapSize.height, null);
}
/*
* Draws the x-axis label string if it is not null.
*/
private void drawXLabel(Graphics2D chartGraphics) {
if (xAxisLabel != null) {
// Strings are drawn from the baseline position of the leftmost char.
//move the label more away from the axis
int yPosXAxisLabel = chartSize.height - margin/2 - xAxisLabelDescent;
//TODO This will need to be updated if the y-axis values/label can be moved to the right.
int xPosXAxisLabel = heatMapC.x - (xAxisLabelSize.width / 2);
chartGraphics.setFont(axisLabelsFont);
chartGraphics.setColor(axisLabelColour);
chartGraphics.drawString(xAxisLabel, xPosXAxisLabel, yPosXAxisLabel);
}
}
/*
* Draws the y-axis label string if it is not null.
*/
private void drawYLabel(Graphics2D chartGraphics) {
if (yAxisLabel != null) {
// Strings are drawn from the baseline position of the leftmost char.
int yPosYAxisLabel = heatMapC.y + (yAxisLabelSize.width / 2);
int xPosYAxisLabel = (margin / 2) + yAxisLabelAscent;
chartGraphics.setFont(axisLabelsFont);
chartGraphics.setColor(axisLabelColour);
// Create 270 degree rotated transform.
AffineTransform transform = chartGraphics.getTransform();
AffineTransform originalTransform = (AffineTransform) transform.clone();
transform.rotate(Math.toRadians(270), xPosYAxisLabel, yPosYAxisLabel);
chartGraphics.setTransform(transform);
// Draw string.
chartGraphics.drawString(yAxisLabel, xPosYAxisLabel, yPosYAxisLabel);
// Revert to original transform before rotation.
chartGraphics.setTransform(originalTransform);
}
}
/*
* Draws the bars of the x-axis and y-axis.
*/
private void drawAxisBars(Graphics2D chartGraphics) {
if (axisThickness > 0) {
chartGraphics.setColor(axisColour);
// Draw x-axis.
int x = heatMapTL.x - axisThickness;
int y = heatMapBR.y;
int width = heatMapSize.width + axisThickness;
int height = axisThickness;
chartGraphics.fillRect(x, y, width, height);
// Draw y-axis.
x = heatMapTL.x - axisThickness;
y = heatMapTL.y;
width = axisThickness;
height = heatMapSize.height;
chartGraphics.fillRect(x, y, width, height);
}
}
/*
* Draws the x-values onto the x-axis if showXAxisValues is set to true.
*/
private void drawXValues(Graphics2D chartGraphics) {
if (!showXAxisValues) {
return;
}
chartGraphics.setColor(axisValuesColour);
for (int i=0; i<xValues.length; i++) {
if (i % xAxisValuesFrequency != 0) {
continue;
}
String xValueStr = xValues[i].toString();
chartGraphics.setFont(axisValuesFont);
FontMetrics metrics = chartGraphics.getFontMetrics();
int valueWidth = metrics.stringWidth(xValueStr);
if (xValuesHorizontal) {
// Draw the value with whatever font is now set.
int valueXPos = (i * cellSize.width) + ((cellSize.width / 2) - (valueWidth / 2));
valueXPos += heatMapTL.x;
int valueYPos = heatMapBR.y + metrics.getAscent() + 1 + margin / 2;
chartGraphics.drawString(xValueStr, valueXPos, valueYPos);
} else {
int valueXPos = heatMapTL.x + (i * cellSize.width) + ((cellSize.width / 2) + (xAxisValuesHeight / 2));
int valueYPos = heatMapBR.y + axisThickness + valueWidth + margin / 2;
// Create 270 degree rotated transform.
AffineTransform transform = chartGraphics.getTransform();
AffineTransform originalTransform = (AffineTransform) transform.clone();
transform.rotate(Math.toRadians(270), valueXPos, valueYPos);
chartGraphics.setTransform(transform);
// Draw the string.
chartGraphics.drawString(xValueStr, valueXPos, valueYPos);
// Revert to original transform before rotation.
chartGraphics.setTransform(originalTransform);
}
}
}
/*
* Draws the y-values onto the y-axis if showYAxisValues is set to true.
*/
private void drawYValues(Graphics2D chartGraphics) {
if (!showYAxisValues) {
return;
}
chartGraphics.setColor(axisValuesColour);
for (int i=0; i<yValues.length; i++) {
if (i % yAxisValuesFrequency != 0) {
continue;
}
String yValueStr = yValues[i].toString();
chartGraphics.setFont(axisValuesFont);
FontMetrics metrics = chartGraphics.getFontMetrics();
int valueWidth = metrics.stringWidth(yValueStr);
if (yValuesHorizontal) {
// Draw the value with whatever font is now set.
//customized code give more room to ylabel
int valueXPos = (int) (margin * 1.5) + yAxisLabelSize.height + (yAxisValuesWidthMax - valueWidth);
int valueYPos = heatMapTL.y + (i * cellSize.height) + (cellSize.height/2) + (yAxisValuesAscent/2);
chartGraphics.drawString(yValueStr, valueXPos, valueYPos);
} else {
//customized code give more room to ylabel
int valueXPos = (int) (margin * 1.5) + yAxisLabelSize.height + yAxisValuesAscent;
int valueYPos = heatMapTL.y + (i * cellSize.height) + (cellSize.height/2) + (valueWidth/2);
// Create 270 degree rotated transform.
AffineTransform transform = chartGraphics.getTransform();
AffineTransform originalTransform = (AffineTransform) transform.clone();
transform.rotate(Math.toRadians(270), valueXPos, valueYPos);
chartGraphics.setTransform(transform);
// Draw the string.
chartGraphics.drawString(yValueStr, valueXPos, valueYPos);
// Revert to original transform before rotation.
chartGraphics.setTransform(originalTransform);
}
}
}
/*
* Determines what colour a heat map cell should be based upon the cell
* values.
*/
private Color getCellColour(double data, double min, double max) {
double range = max - min;
double position = data - min;
// What proportion of the way through the possible values is that.
double percentPosition = position / range;
// Which colour group does that put us in.
int colourPosition = getColourPosition(percentPosition);
int r = lowValueColour.getRed();
int g = lowValueColour.getGreen();
int b = lowValueColour.getBlue();
// Make n shifts of the colour, where n is the colourPosition.
for (int i=0; i<colourPosition; i++) {
int rDistance = r - highValueColour.getRed();
int gDistance = g - highValueColour.getGreen();
int bDistance = b - highValueColour.getBlue();
if ((Math.abs(rDistance) >= Math.abs(gDistance))
&& (Math.abs(rDistance) >= Math.abs(bDistance))) {
// Red must be the largest.
r = changeColourValue(r, rDistance);
} else if (Math.abs(gDistance) >= Math.abs(bDistance)) {
// Green must be the largest.
g = changeColourValue(g, gDistance);
} else {
// Blue must be the largest.
b = changeColourValue(b, bDistance);
}
}
return new Color(r, g, b);
}
/*
* Returns how many colour shifts are required from the lowValueColour to
* get to the correct colour position. The result will be different
* depending on the colour scale used: LINEAR, LOGARITHMIC, EXPONENTIAL.
*/
private int getColourPosition(double percentPosition) {
return (int) Math.round(colourValueDistance * Math.pow(percentPosition, colourScale));
}
private int changeColourValue(int colourValue, int colourDistance) {
if (colourDistance < 0) {
return colourValue+1;
} else if (colourDistance > 0) {
return colourValue-1;
} else {
// This shouldn't actually happen here.
return colourValue;
}
}
/**
* Finds and returns the maximum value in a 2-dimensional array of doubles.
*
* @return the largest value in the array.
*/
public static double max(double[][] values) {
double max = 0;
for (int i=0; i<values.length; i++) {
for (int j=0; j<values[i].length; j++) {
max = (values[i][j] > max) ? values[i][j] : max;
}
}
return max;
}
/**
* Finds and returns the minimum value in a 2-dimensional array of doubles.
*
* @return the smallest value in the array.
*/
public static double min(double[][] values) {
double min = Double.MAX_VALUE;
for (int i=0; i<values.length; i++) {
for (int j=0; j<values[i].length; j++) {
min = (values[i][j] < min) ? values[i][j] : min;
}
}
return min;
}
/*
* customized new variables
*/
private Color nanValueColour = Color.BLACK;
private Color middleValueColour;
private double middleValue;
private double colourValueDistance1,colourValueDistance2;
private boolean withMiddle;
private boolean showColorBarValues = true;
private Object[] colorBarValues;
private int colorBarWidth;
private int colorBarValuesHeight,colorBarValuesAscent, colorBarValuesWidthMax;
private boolean colorBarValuesHorizontal = true;
// the middle value will be used only when withMiddle is set to true
/*
* Customized new functions
*/
// customized construction function
public HeatChart(double[][] zValues, double low, double middle, double high)
{
this(zValues,low,high);
this.middleValue=middle;
this.middleValueColour = Color.GRAY;
updateColourDistance(false);
this.withMiddle=true;
}
private Color getCellColour(double data, double min, double middle, double max) {
double range = max - min;
double position = data - min;
// What proportion of the way through the possible values is that.
double percentPosition = position / range;
boolean leftOrRight=percentPosition<0.5;
// Which colour group does that put us in.
int colourPosition = getColourPosition(percentPosition,leftOrRight);
int r,g,b;
if(leftOrRight)
{
r = lowValueColour.getRed();
g = lowValueColour.getGreen();
b = lowValueColour.getBlue();
}
else
{
r = middleValueColour.getRed();
g = middleValueColour.getGreen();
b = middleValueColour.getBlue();
}
// Make n shifts of the colour, where n is the colourPosition.
for (int i=0; i<colourPosition; i++)
{
int rDistance,gDistance,bDistance;
if(leftOrRight)
{
rDistance = r - middleValueColour.getRed();
gDistance = g - middleValueColour.getGreen();
bDistance = b - middleValueColour.getBlue();
}
else
{
rDistance = r - highValueColour.getRed();
gDistance = g - highValueColour.getGreen();
bDistance = b - highValueColour.getBlue();
}
if ((Math.abs(rDistance) >= Math.abs(gDistance))
&& (Math.abs(rDistance) >= Math.abs(bDistance)))
{
// Red must be the largest.
r = changeColourValue(r, rDistance);
} else if (Math.abs(gDistance) >= Math.abs(bDistance))
{
// Green must be the largest.
g = changeColourValue(g, gDistance);
} else
{
// Blue must be the largest.
b = changeColourValue(b, bDistance);
}
}
return new Color(r, g, b);
}
public boolean isColorBarValuesDisplay()
{return colorBarValuesHorizontal;}
public void setColorBarValuesDisplay(boolean colorBarValuesHorizontal)
{this.colorBarValuesHorizontal = colorBarValuesHorizontal;}
public void displayMiddleValue(boolean middle)
{withMiddle=middle;}
public void setColorValuesFont(Font colorValuesFont) {
this.colorValuesFont = colorValuesFont;
}
public void setColorBarWidth(int colorBarWidth)
{this.colorBarWidth = colorBarWidth;}
public void setMiddleValueColour(Color middleValueColour) {
this.middleValueColour = middleValueColour;
updateColourDistance(false);
withMiddle=true;
}
public Color setNaNValueColour(Color nanValueColour)
{return this.nanValueColour = nanValueColour;}
public Color getMiddleValueColour()
{return this.middleValueColour;}
public double getMiddleValue()
{return middleValue;}
public void setZValues(double[][] zValues, double low, double middle, double high)
{
this.middleValue=middle;
setZValues(zValues,low,high);
}
public void setShowColorBarValues(boolean showColorBarValues)
{
this.showColorBarValues=showColorBarValues;
}
public void setColorBarValues(double colorbarOffset, double colorbarInterval) {
// Update the colorbar-values according to the offset and interval.
colorBarValues = new Object[zValues[0].length];
for (int i=0; i<zValues[0].length; i++) {
colorBarValues[i] = (float)colorbarOffset + (i * (float)colorbarInterval);
}
}
public void setColorBarValues(Object[] colorbarValues) {
// Update the colorbar-values according to the input array.
this.colorBarValues=colorbarValues;
}
private int getColourPosition(double percentPosition,boolean leftOrRight)
{
if(leftOrRight)
return (int) Math.round(colourValueDistance1 * Math.pow(percentPosition*2, colourScale));
else
return (int) Math.round(colourValueDistance2* Math.pow(percentPosition*2-1, colourScale));
}
private void updateColourDistance(boolean flag)
{
int r1 = lowValueColour.getRed();
int g1 = lowValueColour.getGreen();
int b1 = lowValueColour.getBlue();
int r2 = highValueColour.getRed();
int g2 = highValueColour.getGreen();
int b2 = highValueColour.getBlue();
//**update middleValueColour as well**//
int r3 = middleValueColour.getRed();
int g3 = middleValueColour.getGreen();
int b3 = middleValueColour.getBlue();
colourValueDistance1 = Math.abs(r1 - r3);
colourValueDistance1 += Math.abs(g1 - g3);
colourValueDistance1 += Math.abs(b1 - b3);
colourValueDistance2 = Math.abs(r3 - r2);
colourValueDistance2 += Math.abs(g3 - g2);
colourValueDistance2 += Math.abs(b3 - b2);
}
private void drawColorBar(Graphics2D chartGraphics)
{
if(highValue<lowValue)
return;
int noYCells = heatMapSize.height;
double increment = (highValue-lowValue)/noYCells;
double[] data=new double[noYCells];
for(int i=0;i<noYCells;i++)
data[i]=lowValue+increment*i;
// Calculate the available size for the heatmap.
//double dataMin = min(data);
//double dataMax = max(data);
BufferedImage heatMapImage = new BufferedImage(colorBarWidth, heatMapSize.height, BufferedImage.TYPE_INT_ARGB);
Graphics2D heatMapGraphics = heatMapImage.createGraphics();
for (int y=0; y<noYCells; y++)
{
// Set colour depending on zValues.
/*** change it to accept three colours gradient***/
if(withMiddle)
heatMapGraphics.setColor(getCellColour(data[y], lowValue, middleValue, highValue));
else
heatMapGraphics.setColor(getCellColour(data[y], lowValue, highValue));
heatMapGraphics.fillRect(0, noYCells-1-y, colorBarWidth, 1);
}
// Draw the heat map onto the chart.
chartGraphics.drawImage(heatMapImage, heatMapTL.x + heatMapSize.width + margin, heatMapTL.y, colorBarWidth, heatMapSize.height, null);
}
private void drawColorBarValues(Graphics2D chartGraphics) {
if (!showColorBarValues||colorBarValues==null)
return;
chartGraphics.setColor(axisValuesColour);
int colorStepHeight=heatMapSize.height/(colorBarValues.length-1);
colorStepHeight=colorStepHeight>1?colorStepHeight:1;
for (int i=0; i<colorBarValues.length; i++) {
/*if (i % yAxisValuesFrequency != 0) {
continue;
}*/
String colorbarValueStr = colorBarValues[colorBarValues.length-1-i].toString();
chartGraphics.setFont(colorValuesFont);
FontMetrics metrics = chartGraphics.getFontMetrics();
int valueWidth = metrics.stringWidth(colorbarValueStr);
if (colorBarValuesHorizontal) {
// Draw the value with whatever font is now set.
//int valueXPos = chartSize.width - margin - yAxisLabelSize.height - axisThickness;
int valueXPos = (int) (margin * 1.5)+ heatMapTL.x + heatMapSize.width + colorBarWidth + (colorBarValuesWidthMax - valueWidth);
int valueYPos = heatMapTL.y + (i * colorStepHeight) + (colorBarValuesAscent/2);
chartGraphics.drawString(colorbarValueStr, valueXPos, valueYPos);
} else {
int valueXPos = (int) (margin * 1.5)+ heatMapTL.x + heatMapSize.width + colorBarWidth + colorBarValuesAscent;
int valueYPos = heatMapTL.y + (i * colorStepHeight) + (valueWidth/2);
// Create 270 degree rotated transform.
AffineTransform transform = chartGraphics.getTransform();
AffineTransform originalTransform = (AffineTransform) transform.clone();
transform.rotate(Math.toRadians(270), valueXPos, valueYPos);
chartGraphics.setTransform(transform);
// Draw the string.
chartGraphics.drawString(colorbarValueStr, valueXPos, valueYPos);
// Revert to original transform before rotation.
chartGraphics.setTransform(originalTransform);
}
}
}
/**
* Modified code below for TOS matrix only
*/
public static final int MEDIAN = HeatChartStackWindow.MEDIAN, MEAN = HeatChartStackWindow.MEAN, MODE = HeatChartStackWindow.MODE;
public static final int LABEL_LENGTH = 5;
private ImagePlus imp = null;
private ImageProcessor ip = null;
private CellData[] cellDataC1, cellDataC2;
private int[] numOfFTs;
private boolean metricChanged,statsChanged;
private int statsMethod;
private ResultsTable rawValuesRT, plotValuesRT;
//private int numOfCell;
private int options = PluginStatic.getOptions();
private boolean fixChart;
private Dimension heatMapFixedSize;
private Point heatMapFixedTL;
private Font colorValuesFont = new Font("Sans-Serif", Font.PLAIN, 10);
private MatrixCalculator callBase = null;
private int metricIdx = -1;
//CALL_BASES must be declared and initialized first
//Otherwise, it will return ExceptionInInitializerError
private static final String[] METRIC_NAMES = BasicCalculator.getAllMetrics();
public ImagePlus getImagePlus() {
return getImagePlus("");
}
public ImagePlus getImagePlus(String title) {
if(imp==null){
imp = new ImagePlus(title,getChartImage(false));
ip = imp.getProcessor();
}
return imp;
}
public ImageProcessor getProcessor() {
if(ip==null){
imp = new ImagePlus(title,getChartImage(false));
ip = imp.getProcessor();
}
return ip;
}
public Rectangle getDrawingFrame(){
return new Rectangle(heatMapTL.x, heatMapTL.y, heatMapSize.width, heatMapSize.height);
}
/** Converts pixels to calibrated coordinates. In contrast to the image calibration, also
* works with log axes and inverted x axes */
public double getX(int x) {
int xv = (x-heatMapTL.x)/cellSize.width;
if(xValues!=null && xv>=0 && xv<xValues.length)
return Double.valueOf(xValues[xv].toString().replaceAll("[^\\.0123456789]",""));
else
return Double.NaN;
}
/** Converts pixels to calibrated coordinates. In contrast to the image calibration, also
* works with log axes */
public double getY(int y) {
int yv = (y-heatMapTL.y)/cellSize.height;
if(yValues!=null && yv>=0 && yv<yValues.length)
return Double.valueOf(yValues[yv].toString().replaceAll("[^\\.0123456789]",""));
else
return Double.NaN;
}
public double getZ(int x, int y){
int xv = (x-heatMapTL.x)/cellSize.width;
int yv = (y-heatMapTL.y)/cellSize.height;
if(zValues!=null && xv>=0 && xv<zValues.length && yv>=0 && yv<zValues[xv].length)
return zValues[xv][yv];
else
return Double.NaN;
}
public void resetChange(){
metricChanged = false;
statsChanged = false;
}
//public static String[] getMetricNames(){return METRIC_NAMES.clone();}
/**
* set index and calculator
* @param index cooresponding to METRIC_NAMES
*/
public void setCalculator(int index){
if(index<0||index>=METRIC_NAMES.length)
return;
int num = 0;
MatrixCalculator callBase = new MatrixCalculator();
num += MatrixCalculator.getNum();
if(index < num){
this.callBase = callBase;
this.metricIdx = index;
this.metricChanged = true;
return;
}
this.callBase = null;
this.metricIdx = -1;
}
public void updateImage(boolean forced){
if(forced){
metricChanged = true;
statsChanged = true;
}
updateImage();
}
public void updateImage(){
if(!metricChanged && !statsChanged)
return;
if(metricChanged){
if(cellDataC1==null || cellDataC2==null){
IJ.error(getClass().getSimpleName(),"Mssing cell data");
return;
}
callBase.setOptions(options);
callBase.setCutoff(numOfFTs);
int[] xLabels = callBase.numFT2SF(numOfFTs[0]);
int[] yLabels = callBase.numFT2SF(numOfFTs[1]);
String[] xStrings = new String[xLabels.length];
String[] yStrings = new String[yLabels.length];
for(int i=0;i<xStrings.length;i++){
xStrings[i] = xLabels[i] + " %";
}
for(int i=0;i<yStrings.length;i++){
yStrings[i] = yLabels[i] + " %";
}
rawValuesRT = callBase.getMatrix(cellDataC1,cellDataC2,metricIdx);
if(rawValuesRT == null){
IJ.error(getClass().getSimpleName(),"Error in calculating new ResultsTable for the matrix");
return;
}
setColorBarValues(callBase.getColorValues(metricIdx, MatrixCalculator.numColorBar));
setTitle(getInfo(false));
double[] colorValues = callBase.getMetricRange(metricIdx);
lowValue = colorValues[0];
middleValue = colorValues[1];
highValue = colorValues[2];
setZValues(getStatsMatrix(rawValuesRT,callBase),getLowValue(),getMiddleValue(),getHighValue());
setXValues(PluginStatic.flipArray(PluginStatic.other2objArray(xStrings)));
setYValues(PluginStatic.other2objArray(yStrings));
}else if(statsChanged){
setZValues(getStatsMatrix(rawValuesRT,new MatrixCalculator()));
}
plotValuesRT = getResultsTable();
//adaptCellSize(chartSize);
//imp.setImage(getChartImage(false));
//.getScaledInstance(imp.getWidth(), imp.getHeight(), Image.SCALE_DEFAULT)
if(imp==null)
getImagePlus();
else
imp.setImage(getChartImage(false));
imp.updateAndDraw();
metricChanged = false;
statsChanged = false;
}
public void setNumOfFTs(int[] numOfFTs){
if(numOfFTs==null || numOfFTs.length<2){
return;
}
if(this.numOfFTs==null || this.numOfFTs.length<2){
metricChanged = true;
this.numOfFTs = new int[2];
}
for(int i=0;i<2;i++){
if(this.numOfFTs[i]!=numOfFTs[i]){
metricChanged = true;
this.numOfFTs[i]=numOfFTs[i];
}
}
}
/**
* It should be noted that MDEIAN, MEAN, MODE are assumed to be from 0 to 2
* @param statsMethod
*/
public void setStatsMethod(int statsMethod){
switch(statsMethod){
case MEDIAN:
if(this.statsMethod != MEDIAN){
this.statsMethod = MEDIAN;
statsChanged = true;
}
break;
case MEAN:
if(this.statsMethod != MEAN){
this.statsMethod = MEAN;
statsChanged = true;
}
break;
case MODE:
if(this.statsMethod != MODE){
this.statsMethod = MODE;
statsChanged = true;
}
break;
}
}
public void setOptions(int options){
if((this.options &(PluginConstants.RUN_METRICS|PluginConstants.OPTS_TOS))!=
(options &(PluginConstants.RUN_METRICS|PluginConstants.OPTS_TOS)))
metricChanged = true;
this.options = options;
}
public void setLogScale(boolean doLog){
if(doLog)
setOptions(PluginConstants.DO_MATRIX | PluginConstants.DO_LOG2_TOS);
else
setOptions(PluginConstants.DO_MATRIX | PluginConstants.DO_LINEAR_TOS);
}
public void setRawData(CellData[] cellDataC1, CellData[] cellDataC2){
this.cellDataC1 = cellDataC1;
this.cellDataC2 = cellDataC2;
/*if(cellDataC1==null || cellDataC2==null)
numOfCell = 0;
else
numOfCell = cellDataC1.length<cellDataC2.length ? cellDataC1.length : cellDataC2.length;*/
metricChanged = true;
}
public void setRawResultsTable(ResultsTable rt){
rawValuesRT = rt;
}
public void setFixChart(boolean fixChart){
this.fixChart = fixChart;
}
public ResultsTable getResultsTable(boolean raw){
if(raw){
if(rawValuesRT==null)
//rawValuesRT cannot be found, plotValuesRT will be automatically returned
rawValuesRT = getResultsTable();
return rawValuesRT;
}
else{
if(plotValuesRT==null)
plotValuesRT = getResultsTable();
return plotValuesRT;
}
}
private ResultsTable getResultsTable(){
if(zValues!=null && zValues.length>0 && zValues[0]!=null){
double[] x = getAxisValues(xValues, zValues.length);
double[] y = getAxisValues(yValues, zValues[0].length);
return PluginStatic.matrix2ResultsTable(zValues,x,y,false,false);
}else
return new ResultsTable();
}
private double[] getAxisValues(Object[] values, int length){
double[] label;
if(values == null){
label = new double[length];
for(int i=0;i<label.length;i++)
label[i] = i+1;
}
else{
label = new double[values.length];
for(int i=0;i<label.length;i++){
if(values[i] instanceof Float )
label[i] = (float) values[i];
else if(values[i] instanceof Double )
label[i] = (double) values[i];
else if(values[i] instanceof Integer )
label[i] = (int) values[i];
else if (values[i] instanceof String)
label[i] = Double.parseDouble(((String)values[i]).replaceAll("[^\\.0123456789]",""));
label[i] = PluginStatic.round(label[i], 3);
}
}
return label;
}
private double[][] getStatsMatrix(ResultsTable rt, BasicCalculator callBase){
if(rt==null||numOfFTs==null||numOfFTs.length<2)
return null;
int Nrow = BasicCalculator.ft2length(numOfFTs[0]), Ncolumn = BasicCalculator.ft2length(numOfFTs[1]);
double[][] matrix = new double[Nrow][Ncolumn];
switch(statsMethod){
case MEDIAN:
for (int iColumn=0;iColumn<=rt.getLastColumn();iColumn++){
double[] tempmTOS = rt.getColumnAsDoubles(iColumn);
matrix[Nrow-1-iColumn/Ncolumn][iColumn%Ncolumn] = callBase.getMedian(tempmTOS);
}
break;
case MEAN:
for (int iColumn=0;iColumn<=rt.getLastColumn();iColumn++){
double[] tempmTOS = rt.getColumnAsDoubles(iColumn);
matrix[Nrow-1-iColumn/Ncolumn][iColumn%Ncolumn] = callBase.getMean(tempmTOS);
}
break;
case MODE:
for (int iColumn=0;iColumn<=rt.getLastColumn();iColumn++){
double[] tempmTOS = rt.getColumnAsDoubles(iColumn);
matrix[Nrow-1-iColumn/Ncolumn][iColumn%Ncolumn] = callBase.getMode(tempmTOS);
}
break;
default:
return null;
}
return matrix;
}
/*
* Calculates the co-ordinates of some key positions.
*/
private void updateCoordinates(boolean fixChart) {
// Top-left of heat map.
// customized code give more space to the left
int x,y;
// Top-right of heat map.
x = heatMapTL.x + heatMapSize.width;
y = heatMapTL.y + heatMapSize.height;
heatMapBR = new Point(x, y);
// Centre of heat map.
x = heatMapTL.x + (heatMapSize.width / 2);
y = heatMapTL.y + (heatMapSize.height / 2);
heatMapC = new Point(x, y);
}
private void measureComponents(boolean fixChart){
if(!fixChart || chartSize == null){
measureComponents();
updateCoordinates();
heatMapFixedSize = new Dimension(heatMapSize);
heatMapFixedTL = new Point(heatMapTL);
return;
}
//Only updates title width
if (title != null) {
BufferedImage chartImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D tempGraphics = chartImage.createGraphics();
tempGraphics.setFont(titleFont);
FontMetrics metrics = tempGraphics.getFontMetrics();
titleSize = new Dimension(metrics.stringWidth(title), metrics.getHeight());
titleAscent = metrics.getAscent();
} else {
titleSize = new Dimension(0, 0);
}
//Assuming measureComponents has been called at least onces
//TODO This would be a good place to check that all settings have sensible values or throw illegal state exception.
//TODO Put this somewhere so it only gets created once.
BufferedImage chartImage = new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB);
Graphics2D tempGraphics = chartImage.createGraphics();
// Calculate heatmap dimensions.
/**
* Custom comment here
* I have no idea why the author flip x and y axis
* Normally, the first dimension is x and the second is y
* Therefore, heatMapWidth should be the length of the first dimension
* and heatMapHeight is that of the second.
*/
cellSize.width = heatMapFixedSize.width / zValues.length;
cellSize.height = heatMapFixedSize.height / zValues[0].length;
int heatMapWidth = heatMapFixedSize.width;
int heatMapHeight = heatMapFixedSize.height;
heatMapSize.width = cellSize.width * zValues.length;
heatMapSize.height = cellSize.height * zValues[0].length;
heatMapTL.x = heatMapFixedTL.x + (heatMapWidth - heatMapSize.width)/2;
heatMapTL.y = heatMapFixedTL.y + (heatMapHeight - heatMapSize.height)/2;
int axisValuesFontSize = 288;
// Calculate x-axis value dimensions.
if (showXAxisValues) {
int xAxisValuesHeight,xAxisValuesWidth;
if(xValuesHorizontal){
xAxisValuesWidth = this.xAxisValuesWidthMax > cellSize.width ? cellSize.width : this.xAxisValuesWidthMax;
xAxisValuesHeight = this.xAxisValuesHeight;
}else{
xAxisValuesWidth = this.xAxisValuesWidthMax;
xAxisValuesHeight = this.xAxisValuesHeight > cellSize.width ? cellSize.width : this.xAxisValuesHeight;
}
for (Object o: xValues) {
int fontSize = getMaxFittingFontSize(tempGraphics, axisValuesFont, o.toString(),
new Dimension(xAxisValuesWidth, xAxisValuesHeight));
if(axisValuesFontSize > fontSize)
axisValuesFontSize = fontSize;
}
}
// Calculate y-axis value dimensions.
if (showYAxisValues) {
int yAxisValuesHeight,yAxisValuesWidth;
if(xValuesHorizontal){
yAxisValuesWidth = this.yAxisValuesWidthMax > cellSize.height ? cellSize.height : this.yAxisValuesWidthMax;
yAxisValuesHeight = this.yAxisValuesHeight;
}else{
yAxisValuesWidth = this.yAxisValuesWidthMax;
yAxisValuesHeight = this.yAxisValuesHeight > cellSize.height ? cellSize.height : this.yAxisValuesHeight;
}
for (Object o: yValues) {
int fontSize = getMaxFittingFontSize(tempGraphics, axisValuesFont, o.toString(),
new Dimension(yAxisValuesWidth, yAxisValuesHeight));
if(axisValuesFontSize > fontSize)
axisValuesFontSize = fontSize;
}
}
axisValuesFont = axisValuesFont.deriveFont((float)axisValuesFontSize);
// Calculate colorbar value dimensions.
if (showColorBarValues) {
for (Object o: colorBarValues) {
int fontSize = getMaxFittingFontSize(tempGraphics, colorValuesFont, o.toString(),
yValuesHorizontal ? new Dimension(colorBarValuesWidthMax, colorBarValuesHeight) : new Dimension(colorBarValuesHeight, colorBarValuesWidthMax));
colorValuesFont = colorValuesFont.deriveFont((float)fontSize);
}
}
updateCoordinates(fixChart);
}
/**
* Retrieved from http://www.java2s.com/Code/Java/Swing-JFC/GetMaxFittingFontSize.htm
* The utillib library.
* More information is available at http://www.jinchess.com/.
* Copyright (C) 2002 Alexander Maryanovsky.
* All rights reserved.
*
* The utillib library is free software; you can redistribute
* it and/or modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2 of the
* License, or (at your option) any later version.
*
* The utillib library is distributed in the hope that it will
* be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser
* General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with utillib library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
private int getMaxFittingFontSize(Graphics2D g, Font font, String string, Dimension size){
int minSize = 0;
int maxSize = 288;
int curSize = font.getSize();
while (maxSize - minSize > 2){
FontMetrics fm = g.getFontMetrics(new Font(font.getName(), font.getStyle(), curSize));
int fontWidth = fm.stringWidth(string);
int fontHeight = fm.getLeading() + fm.getMaxAscent() + fm.getMaxDescent();
if ((fontWidth > size.width) || (fontHeight > size.height)){
maxSize = curSize;
curSize = (maxSize + minSize) / 2;
}
else{
minSize = curSize;
curSize = (minSize + maxSize) / 2;
}
}
return curSize;
}
private String formatStr(String str){
return formatStr(str, LABEL_LENGTH);
}
private String formatStr(String str, int length){
return String.format("%-"+length+"s", str).replace(' ', '0');
}
public String getInfo(boolean raw){
String metric = ""+ MatrixCalculator.getNames(metricIdx);
String stats;
if(raw)
stats = "Raw Values";
else
stats = HeatChartStackWindow.getStatsName(statsMethod) + " values";
return metric+" "+stats;
}
}
| 85,279 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
PlotStackWindow.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual2D/PlotStackWindow.java | package ezcol.visual.visual2D;
import java.awt.Button;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Event;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Insets;
import java.awt.Label;
import java.awt.LayoutManager;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Window;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.StringSelection;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.MouseWheelEvent;
import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Vector;
import ij.IJ;
import ij.ImagePlus;
import ij.Prefs;
import ij.WindowManager;
import ij.gui.ImageLayout;
import ij.gui.Overlay;
import ij.gui.Plot;
import ij.gui.PlotCanvas;
import ij.gui.PolygonRoi;
import ij.gui.Roi;
import ij.gui.StackWindow;
import ij.io.SaveDialog;
import ij.macro.Interpreter;
import ij.measure.Measurements;
import ij.measure.ResultsTable;
import ij.plugin.filter.Analyzer;
import ij.process.ByteProcessor;
import ij.process.ColorProcessor;
import ij.process.ImageProcessor;
import ij.util.Tools;
/** This class is a slightly modified version of PlotWindow from ij.gui. **/
@SuppressWarnings("serial")
public class PlotStackWindow extends StackWindow implements ActionListener, ClipboardOwner, Runnable {
/** Display points using a circle 5 pixels in diameter. */
public static final int CIRCLE = Plot.CIRCLE;
/** Display points using an X-shaped mark. */
public static final int X = Plot.X;
/** Display points using an box-shaped mark. */
public static final int BOX = Plot.BOX;
/** Display points using an tiangular mark. */
public static final int TRIANGLE = Plot.TRIANGLE;
/** Display points using an cross-shaped mark. */
public static final int CROSS = Plot.CROSS;
/** Connect points with solid lines. */
public static final int LINE = Plot.LINE;
/**
* Save x-values only. To set, use Edit/Options/ Profile Plot Options.
*/
public static boolean saveXValues = true;
/**
* Automatically close window after saving values. To set, use
* Edit/Options/Profile Plot Options.
*/
public static boolean autoClose;
/**
* Display the XY coordinates in a separate window. To set, use
* Edit/Options/Profile Plot Options.
*/
public static boolean listValues;
/**
* Interpolate line profiles. To set, use Edit/Options/Profile Plot Options.
*/
public static boolean interpolate;
// default values for new installations; values will be then saved in prefs
private static final int WIDTH = 450;
private static final int HEIGHT = 200;
private static final int FONT_SIZE = 12;
/** The width of the plot (without frame) in pixels. */
public static int plotWidth = WIDTH;
/** The height of the plot in pixels. */
public static int plotHeight = HEIGHT;
/**
* The plot text size, can be overridden by Plot.setFont, Plot.setFontSize,
* Plot.setXLabelFont etc.
*/
public static int fontSize = FONT_SIZE;
/**
* Have axes with no grid lines. If both noGridLines and noTicks are true,
* only min&max value of the axes are given
*/
public static boolean noGridLines;
/**
* Have axes with no ticks. If both noGridLines and noTicks are true, only
* min&max value of the axes are given
*/
public static boolean noTicks;
private static final String PREFS_WIDTH = "pp.width";
private static final String PREFS_HEIGHT = "pp.height";
private static final String PREFS_FONT_SIZE = "pp.fontsize";
private static final String OPTIONS = "pp.options";
private static final int SAVE_X_VALUES = 1;
private static final int AUTO_CLOSE = 2;
private static final int LIST_VALUES = 4;
private static final int INTERPOLATE = 8;
private static final int NO_GRID_LINES = 16;
private static final int NO_TICKS = 32;
private Button list, save, copy, log, costes;
private Label coordinates;
private static int options;
// denotes the current plot
private Plot plot;
// private static Plots staticPlot;
boolean layoutDone; // becomes true after the layout has been done, used by
// PlotCanvas
private String blankLabel = " ";
private Roi[] rangeArrowRois; // these constitute the arrow overlays for
// changing the range
private boolean rangeArrowsVisible;
private int activeRangeArrow = -1;
// new fields
private Plot[] plots;
// default fields from Plot
@SuppressWarnings("deprecation")
int leftMargin = Plot.LEFT_MARGIN, rightMargin = Plot.RIGHT_MARGIN, topMargin = Plot.TOP_MARGIN,
bottomMargin = Plot.BOTTOM_MARGIN;
int frameWidth; // width corresponding to plot range; frame.width is larger
// by 1
int frameHeight; // height corresponding to plot range; frame.height is
// larger by 1
Rectangle stackFrame = null;
private boolean logScale, showCostes;
private ScatterPlotGenerator spg;
private ArrayList <Object> ipRefs = new ArrayList<Object>();
// static initializer
static {
options = Prefs.getInt(OPTIONS, SAVE_X_VALUES);
//saveXValues = (options & SAVE_X_VALUES) != 0;
autoClose = (options & AUTO_CLOSE) != 0;
listValues = (options & LIST_VALUES) != 0;
plotWidth = Prefs.getInt(PREFS_WIDTH, WIDTH);
plotHeight = Prefs.getInt(PREFS_HEIGHT, HEIGHT);
fontSize = Prefs.getInt(PREFS_FONT_SIZE, FONT_SIZE);
interpolate = (options & INTERPOLATE) == 0; // 0=true, 1=false
noGridLines = (options & NO_GRID_LINES) != 0;
noTicks = (options & NO_TICKS) != 0;
}
/** Creates a PlotWindow from a Plot object. */
public PlotStackWindow(Plot plot) {
super(plot.getImagePlus(), new PlotCanvas(plot.getImagePlus()));
this.plot = plot;
// ((PlotCanvas)getCanvas()).setPlot(plot);
((PlotCanvas) getCanvas()).setPlot(plot);
draw();
}
/** Creates a PlotWindow from a Plot object. */
PlotStackWindow(Plot[] plots, ImagePlus imp) {
super(imp, new PlotCanvas(imp));
// ((PlotCanvas)getCanvas()).setPlot(plot);
if (plots != null && plots.length > 0) {
this.plots = plots;
this.plot = plots[0];
((PlotCanvas) getCanvas()).setPlot(plot);
// ImageJ will not update after zoom out
// this is because the displayed ImagePlus doesn't match the one in
// Plot
// Fix it here to get zoom out work properly
for (int i = this.plots.length - 1; i >= 0 ; i--)
this.plots[i].setImagePlus(imp);
draw();
}
}
PlotStackWindow(Plot[] plots, ImagePlus imp, ScatterPlotGenerator spg) {
super(imp, new PlotCanvas(imp));
//Add a handle to ScatterPlotGenerator which will be used to
//Replot data to toggle Costes thresholds on and off
this.spg = spg;
// ((PlotCanvas)getCanvas()).setPlot(plot);
if (plots != null && plots.length > 0) {
this.plots = plots;
this.plot = plots[0];
((PlotCanvas) getCanvas()).setPlot(plot);
// ImageJ will not update after zoom out
// this is because the displayed ImagePlus doesn't match the one in
// Plot
// Fix it here to get zoom out work properly
//save sliceLabels in the constructor in case users change it later
//To adapt to the new method of setImagePlus
//A reverse order is implemented so that the ImageProcessor
//of the first Plot in plots array
//is set to be the first slice
for (int i = this.plots.length - 1; i >= 0 ; i--){
this.plots[i].setImagePlus(imp);
//This might be a dumb workaround
//I'm looking for a unique id to identify which slice
//has been removed or added
//The best identifier I can find and get is pixel array
//ipRefs.insertElementAt(imp.getStack().getProcessor(i + 1).getPixels(), 0);
ipRefs.add(0, imp.getStack().getProcessor(i + 1).getPixels());
}
draw();
}
}
/** Displays the plot. */
protected void draw() {
Panel bottomPanel = new Panel();
int hgap = IJ.isMacOSX() ? 1 : 5;
list = new Button(" List ");
list.addActionListener(this);
bottomPanel.add(list);
bottomPanel.setLayout(new FlowLayout(FlowLayout.RIGHT, hgap, 0));
save = new Button("Save...");
save.addActionListener(this);
bottomPanel.add(save);
copy = new Button(" Copy ");
copy.addActionListener(this);
bottomPanel.add(copy);
log = new Button(" Log ");
log.addActionListener(this);
bottomPanel.add(log);
// add a button to toggle costes thresholds
costes = new Button(" Costes ");
costes.addActionListener(this);
bottomPanel.add(costes);
coordinates = new Label(blankLabel);
coordinates.setFont(new Font("Monospaced", Font.PLAIN, 12));
coordinates.setBackground(new Color(220, 220, 220));
bottomPanel.add(coordinates);
add(bottomPanel);
plot.draw();
LayoutManager lm = getLayout();
if (lm instanceof ImageLayout)
((ImageLayout) lm).ignoreNonImageWidths(true); // don't expand size
// to make the panel
// fit
pack();
ImageProcessor ip = plot.getProcessor();
if ((ip instanceof ColorProcessor) && (imp.getProcessor() instanceof ByteProcessor))
imp.setProcessor(null, ip);
else
imp.updateAndDraw();
layoutDone = true;
if (listValues)
showList();
else
ic.requestFocus(); // have focus on the canvas, not the button, so
// that pressing the space bar allows panning
// get the frame from plot because frame is private in plot
stackFrame = plot.getDrawingFrame();
frameWidth = stackFrame.width;
frameHeight = stackFrame.height;
}
/** Draws a new plot in this window. */
/**
* WARNING: this method is never used or tested
* @param plot
*/
/*
public void drawPlot(Plot plot) {
if (plot != null) {
this.plot = plot;
plots[imp.getCurrentSlice() - 1] = this.plot;
if (imp != null) {
if (ic instanceof PlotCanvas)
((PlotCanvas) ic).setPlot(plot);
imp.setProcessor(null, plot.getProcessor());
plot.setImagePlus(imp); // also adjusts the calibration of imp
}
}
}*/
@Deprecated
public void showStack() {
if ((IJ.macroRunning() && IJ.getInstance() == null) || Interpreter.isBatchMode()) {
imp = plot.getImagePlus();
WindowManager.setTempCurrentImage(imp);
/*
* if (getMainCurveObject() != null) { imp.setProperty("XValues",
* getXValues()); // Allows values to be retrieved by
* imp.setProperty("YValues", getYValues()); // by Plot.getValues()
* macro function } Interpreter.addBatchModeImage(imp); return null;
*/
}
if (imp != null) {
Window win = imp.getWindow();
if (win instanceof PlotStackWindow && win.isVisible()) {
plot.updateImage(); // show in existing window
}
}
if (imp == null)
imp.setProperty(Plot.PROPERTY_KEY, null);
imp = getImagePlus();
imp.setProperty(Plot.PROPERTY_KEY, this);
if (IJ.isMacro() && imp != null) // wait for plot to be displayed
IJ.selectWindow(imp.getID());
}
/** Shows the data of the backing plot in a Textwindow with columns */
void showList() {
ResultsTable rt = plot.getResultsTable(saveXValues);
rt.show("Plot Values");
if (autoClose) {
imp.changes = false;
close();
}
}
/** Copy the first dataset or all values to the clipboard */
void copyToClipboard(boolean writeAllColumns) {
float[] xValues = plot.getXValues();
float[] yValues = plot.getYValues();
if (xValues == null)
return;
Clipboard systemClipboard = null;
try {
systemClipboard = getToolkit().getSystemClipboard();
} catch (Exception e) {
systemClipboard = null;
}
if (systemClipboard == null) {
IJ.error("Unable to copy to Clipboard.");
return;
}
IJ.showStatus("Copying plot values...");
CharArrayWriter aw = new CharArrayWriter(10 * xValues.length);
PrintWriter pw = new PrintWriter(aw); // uses platform's line
// termination characters
if (writeAllColumns) {
ResultsTable rt = plot.getResultsTable(true);
if (!Prefs.dontSaveHeaders) {
String headings = rt.getColumnHeadings();
pw.println(headings);
}
for (int i = 0; i < rt.size(); i++)
pw.println(rt.getRowAsString(i));
} else {
int xdigits = 0;
if (saveXValues)
xdigits = getPrecision(xValues);
int ydigits = getPrecision(yValues);
for (int i = 0; i < Math.min(xValues.length, yValues.length); i++) {
if (saveXValues)
pw.println(IJ.d2s(xValues[i], xdigits) + "\t" + IJ.d2s(yValues[i], ydigits));
else
pw.println(IJ.d2s(yValues[i], ydigits));
}
}
String text = aw.toString();
pw.close();
StringSelection contents = new StringSelection(text);
systemClipboard.setContents(contents, this);
IJ.showStatus(text.length() + " characters copied to Clipboard");
if (autoClose) {
imp.changes = false;
close();
}
}
/** Returns the plot values as a ResultsTable. */
public ResultsTable getResultsTable() {
return plot.getResultsTable(saveXValues);
}
/** Saves the data of the plot in a text file */
void saveAsText() {
if (plot.getXValues() == null) {
IJ.error("Plot has no data");
return;
}
SaveDialog sd = new SaveDialog("Save as Text", "Values", Prefs.defaultResultsExtension());
String name = sd.getFileName();
if (name == null)
return;
String directory = sd.getDirectory();
IJ.wait(250); // give system time to redraw ImageJ window
IJ.showStatus("Saving plot values...");
ResultsTable rt = getResultsTable();
try {
rt.saveAs(directory + name);
} catch (IOException e) {
IJ.error("" + e);
return;
}
if (autoClose) {
imp.changes = false;
close();
}
}
/**
* Creates an overlay with triangular buttons for changing the axis range
* limits and shows it
*/
void showRangeArrows() {
if (imp == null)
return;
hideRangeArrows(); // in case we have old arrows from a different plot
// size or so
rangeArrowRois = new Roi[4 * 2]; // 4 arrows per axis
int i = 0;
int height = imp.getHeight();
int arrowH = topMargin < 14 ? 6 : 8; // height of arrows and distance
// between them; base is twice
// that value
float[] yP = new float[] { height - arrowH / 2, height - 3 * arrowH / 2, height - 5 * arrowH / 2 - 0.1f };
for (float x : new float[] { leftMargin, leftMargin + frameWidth }) { // create
// arrows
// for
// x
// axis
float[] x0 = new float[] { x - arrowH / 2, x - 3 * arrowH / 2 - 0.1f, x - arrowH / 2 };
rangeArrowRois[i++] = new PolygonRoi(x0, yP, 3, Roi.POLYGON);
float[] x1 = new float[] { x + arrowH / 2, x + 3 * arrowH / 2 + 0.1f, x + arrowH / 2 };
rangeArrowRois[i++] = new PolygonRoi(x1, yP, 3, Roi.POLYGON);
}
float[] xP = new float[] { arrowH / 2 - 0.1f, 3 * arrowH / 2, 5 * arrowH / 2 + 0.1f };
for (float y : new float[] { topMargin + frameHeight, topMargin }) { // create
// arrows
// for
// y
// axis
float[] y0 = new float[] { y + arrowH / 2, y + 3 * arrowH / 2 + 0.1f, y + arrowH / 2 };
rangeArrowRois[i++] = new PolygonRoi(xP, y0, 3, Roi.POLYGON);
float[] y1 = new float[] { y - arrowH / 2, y - 3 * arrowH / 2 - 0.1f, y - arrowH / 2 };
rangeArrowRois[i++] = new PolygonRoi(xP, y1, 3, Roi.POLYGON);
}
Overlay ovly = imp.getOverlay();
if (ovly == null)
ovly = new Overlay();
for (Roi roi : rangeArrowRois) {
roi.setFillColor(Color.GRAY);
ovly.add(roi);
}
imp.setOverlay(ovly);
ic.repaint();
rangeArrowsVisible = true;
}
void hideRangeArrows() {
if (imp == null || rangeArrowRois == null)
return;
Overlay ovly = imp.getOverlay();
if (ovly == null)
return;
for (Roi roi : rangeArrowRois)
ovly.remove(roi);
ic.repaint();
rangeArrowsVisible = false;
activeRangeArrow = -1;
}
/**
* Returns the index of the range arrow at cursor position x,y, or -1 of
* none. Index numbers start with 0 at the 'down' arrow of the lower side of
* the x axis and end with the up arrow at the upper side of the y axis.
*/
int getRangeArrowIndex(int x, int y) {
if (!rangeArrowsVisible)
return -1;
for (int i = 0; i < rangeArrowRois.length; i++)
if (rangeArrowRois[i].getBounds().contains(x, y))
return i;
return -1;
}
private String d2s(double n) {
int digits = Tools.getDecimalPlaces(n);
if (digits > 2)
digits = 2;
return IJ.d2s(n, digits);
}
private void setLogScale(boolean doLog) {
if (plots != null) {
ImageProcessor ip = this.imp.getProcessor();
int currentPlot = ipRefs.indexOf(ip.getPixels());
for (int i = 0; i < plots.length; i++) {
if (plots[i] == null)
continue;
plots[i].setAxisXLog(doLog);
plots[i].setAxisYLog(doLog);
plots[i].updateImage();
}
//plot.updateImage();
if(currentPlot == -1){
this.imp.setProcessor(ip);
}else{
plots[currentPlot].updateImage();
}
}
/*
* if (plot != null) { plot.setAxisXLog(doLog); plot.setAxisYLog(doLog);
* plot.updateImage(); }
*/
ic.repaint();
}
@Override
public synchronized void adjustmentValueChanged(AdjustmentEvent e) {
super.adjustmentValueChanged(e);
int currentPlot = ipRefs.indexOf(imp.getStack().getProcessor(e.getValue()).getPixels());
//int currentPlot = ipRefs.indexOf(imp.getProcessor().getPixels());
if (plots != null && !imp.isLocked()) {
if(currentPlot != -1){
plot = plots[currentPlot];
}
else
plot = null;
((PlotCanvas) getCanvas()).setPlot(plot);
//plot might be off sync with imp here but it's OK.
}
}
/**
* Updates the X and Y values when the mouse is moved and, if appropriate,
* shows/hides the overlay with the triangular buttons for changing the axis
* range limits Overrides mouseMoved() in ImageWindow.
*
* @see ij.gui.ImageWindow#mouseMoved
*/
@Override
public void mouseMoved(int x, int y) {
super.mouseMoved(x, y);
if (plot == null)
return;
if (stackFrame == null || coordinates == null)
return;
if (stackFrame.contains(x, y)) { //coordinate readout
String coords = "X=" + d2s(plot.descaleX(x)) + ", Y=" + d2s(plot.descaleY(y)) + blankLabel;
coordinates.setText(coords.substring(0, blankLabel.length()));
}else
coordinates.setText(blankLabel);
// arrows for modifying the plot range
if (x < leftMargin || y > topMargin + frameHeight) {
if (!rangeArrowsVisible && !plot.isFrozen())
showRangeArrows();
if (activeRangeArrow >= 0 && !rangeArrowRois[activeRangeArrow].contains(x, y)) {
rangeArrowRois[activeRangeArrow].setFillColor(Color.GRAY);
ic.repaint(); // de-highlight arrow where cursor has moved out
activeRangeArrow = -1;
}
if (activeRangeArrow < 0) { // highlight arrow below cursor (if any)
int i = getRangeArrowIndex(x, y);
if (i >= 0) { // we have an arrow at cursor position
rangeArrowRois[i].setFillColor(Color.RED);
activeRangeArrow = i;
ic.repaint();
}
}
} else if (rangeArrowsVisible)
hideRangeArrows();
}
@Override
/**
* Update the slice display by the scrollbar
*/
public void run() {
while (!done) {
IJ.wait(50); // delay to make sure the roi has been updated
synchronized (this) {
try {
wait();
} catch (InterruptedException e) {
}
}
if (done)
return;
if (slice > 0) {
int s = slice;
slice = 0;
if (s != imp.getCurrentSlice()) {
if(setSlice(imp, s) && !imp.isLocked())
{
int currentPlot = ipRefs.indexOf(imp.getProcessor().getPixels());
if(currentPlot != -1){
plot = plots[currentPlot];
//Synchronize plot.getProcessor and imp.getProcessor
//They might be different due to zooming
//The actual mechanism is not clear to me
plot.getProcessor().setPixels(imp.getProcessor().getPixels());
}else
plot = null;
((PlotCanvas) getCanvas()).setPlot(plot);
}
}
}
}
}
private boolean setSlice(ImagePlus imp, int n) {
if (imp.isLocked()) {
IJ.beep();
IJ.showStatus("Image is locked");
return false;
} else
imp.setSlice(n);
return true;
}
/** Called if user has activated a button or popup menu item */
@Override
public void actionPerformed(ActionEvent e) {
Object b = e.getSource();
if (b == list)
showList();
else if (b == save)
saveAsText();
else if (b == copy)
copyToClipboard(true);
else if (b == log) {
logScale = !logScale;
if (logScale)
log.setForeground(Color.RED);
else
log.setForeground(Color.BLACK);
setLogScale(logScale);
} else if (b == costes) {
showCostes = !showCostes;
if (showCostes)
costes.setForeground(Color.RED);
else
costes.setForeground(Color.BLACK);
showCostes(showCostes);
}
if (b != list)
ic.requestFocus(); // have focus on the canvas, not the button, so
// that pressing the space bar allows panning
}
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents) {
// TODO Auto-generated method stub
}
// when writing data in scientific mode, use at least 4 decimals behind the
// decimal point
static final int MIN_SCIENTIFIC_DIGITS = 4;
// when writing float data, precision should be at least 1e-5*data range
static final double MIN_FLOAT_PRECISION = 1e-5;
/**
* get the number of digits for writing a column to the results table or the
* clipboard
*/
static int getPrecision(float[] values) {
int setDigits = Analyzer.getPrecision();
int measurements = Analyzer.getMeasurements();
boolean scientificNotation = (measurements & Measurements.SCIENTIFIC_NOTATION) != 0;
if (scientificNotation) {
if (setDigits < MIN_SCIENTIFIC_DIGITS)
setDigits = MIN_SCIENTIFIC_DIGITS;
return -setDigits;
}
boolean allInteger = true;
float min = Float.MAX_VALUE, max = -Float.MAX_VALUE;
for (int i = 0; i < values.length; i++) {
if ((int) values[i] != values[i] && !Float.isNaN(values[i])) {
allInteger = false;
if (values[i] < min)
min = values[i];
if (values[i] > max)
max = values[i];
}
}
if (allInteger)
return 0;
int digits = (max - min) > 0 ? getDigits(min, max, MIN_FLOAT_PRECISION * (max - min), 15)
: getDigits(max, MIN_FLOAT_PRECISION * Math.abs(max), 15);
if (setDigits > Math.abs(digits))
digits = setDigits * (digits < 0 ? -1 : 1); // use scientific
// notation if needed
return digits;
}
// Number of digits to display the number n with resolution 'resolution';
// (if n is integer and small enough to display without scientific notation,
// no decimals are needed, irrespective of 'resolution')
// Scientific notation is used for more than 'maxDigits' (must be >=3), and
// indicated
// by a negative return value
static int getDigits(double n, double resolution, int maxDigits) {
if (n == Math.round(n) && Math.abs(n) < Math.pow(10, maxDigits - 1) - 1) // integers
// and
// not
// too
// big
return 0;
else
return getDigits2(n, resolution, maxDigits);
}
// Number of digits to display the range between n1 and n2 with resolution
// 'resolution';
// Scientific notation is used for more than 'maxDigits' (must be >=3), and
// indicated
// by a negative return value
static int getDigits(double n1, double n2, double resolution, int maxDigits) {
if (n1 == 0 && n2 == 0)
return 0;
return getDigits2(Math.max(Math.abs(n1), Math.abs(n2)), resolution, maxDigits);
}
static int getDigits2(double n, double resolution, int maxDigits) {
int log10ofN = (int) Math.floor(Math.log10(Math.abs(n)) + 1e-7);
int digits = resolution != 0 ? -(int) Math.floor(Math.log10(Math.abs(resolution)) + 1e-7)
: Math.max(0, -log10ofN + maxDigits - 2);
int sciDigits = -Math.max((log10ofN + digits), 1);
// IJ.log("n="+(float)n+"digitsRaw="+digits+" log10ofN="+log10ofN+"
// sciDigits="+sciDigits);
if (digits < -2 && log10ofN >= maxDigits)
digits = sciDigits; // scientific notation for large numbers
else if (digits < 0)
digits = 0;
else if (digits > maxDigits - 1 && log10ofN < -2)
digits = sciDigits; // scientific notation for small numbers
return digits;
}
/**
* Mouse wheel: zooms when shift or ctrl is pressed, scrolls in x if space
* bar down, in y otherwise.
*/
@Override
public synchronized void mouseWheelMoved(MouseWheelEvent e) {
if (plot.isFrozen() || !(ic instanceof PlotCanvas)) { // frozen plots
// are like
// normal images
super.mouseWheelMoved(e);
return;
}
int rotation = e.getWheelRotation();
int amount = e.getScrollAmount();
boolean ctrl = (e.getModifiers() & Event.CTRL_MASK) != 0;
if (amount < 1)
amount = 1;
if (rotation == 0)
return;
if (ctrl || IJ.shiftKeyDown()) {
Point loc = ic.getCursorLoc();
int x = ic.screenX(loc.x);
int y = ic.screenY(loc.y);
if (rotation < 0)
((PlotCanvas) ic).zoomIn(x, y);
else
((PlotCanvas) ic).zoomOut(x, y);
plot.updateImage();
} else if (IJ.spaceBarDown()) {
scroll(plot, rotation * amount * Math.max(imp.getWidth() / 50, 1), 0);
} else {
scroll(plot, 0, rotation * amount * Math.max(imp.getHeight() / 50, 1));
}
ic.repaint();
}
private void scroll(Plot plot, int dx, int dy) {
double[] currentMinMax = plot.getLimits();
Rectangle rct = plot.getDrawingFrame();
double xScale, yScale;
xScale = rct.width / (currentMinMax[1] - currentMinMax[0]);
yScale = rct.height / (currentMinMax[3] - currentMinMax[2]);
if (logScale) {
currentMinMax[0] /= Math.pow(10, dx / xScale);
currentMinMax[1] /= Math.pow(10, dx / xScale);
} else {
currentMinMax[0] -= dx / xScale;
currentMinMax[1] -= dx / xScale;
}
if (logScale) {
currentMinMax[2] *= Math.pow(10, dy / yScale);
currentMinMax[3] *= Math.pow(10, dy / yScale);
} else {
currentMinMax[2] += dy / yScale;
currentMinMax[3] += dy / yScale;
}
plot.setLimits(currentMinMax[0], currentMinMax[1], currentMinMax[2], currentMinMax[3]);
// plot.getImagePlus().duplicate().show();
// ic.repaint();
}
/** Called when the canvas is resized */
void updateMinimumSize() {
if (plot == null)
return;
Dimension d1 = getExtraSizeThis();
Dimension d2 = plot.getMinimumSize();
setMinimumSize(new Dimension(d1.width + d2.width, d1.height + d2.height));
}
private Dimension getExtraSizeThis() {
Insets insets = getInsets();
int extraWidth = insets.left + insets.right + 10;
int extraHeight = insets.top + insets.bottom + 10;
if (extraHeight == 20)
extraHeight = 42;
int members = getComponentCount();
// if (IJ.debugMode) IJ.log("getExtraSize: "+members+" "+insets);
for (int i = 1; i < members; i++) {
Component m = getComponent(i);
Dimension d = m.getPreferredSize();
extraHeight += d.height + 5;
if (IJ.debugMode)
IJ.log(i + " " + d.height + " " + extraHeight);
}
return new Dimension(extraWidth, extraHeight);
}
/*public Plot getPlot() {
return plot;
}*/
private void showCostes(boolean showCostes) {
if (spg == null || imp.isLocked())
return;
ImageProcessor ip = this.imp.getProcessor();
int currentPlot = ipRefs.indexOf(ip.getPixels());
if (showCostes){
spg.addCostes();
if(currentPlot == -1){
this.imp.setProcessor(ip);
}else{
plots[currentPlot].updateImage();
}
//this.imp.duplicate().show();
/*for (int i = 0; i < plots.length; i++){
this.imp.getStack().setProcessor(plots[i].getProcessor(), i + 1);
plots[i].updateImage();
}*/
}else {
Plot[] tempPlot = new Plot[plots.length];
for (int i = 0; i < plots.length; i++){
tempPlot[i] = plots[i];
}
//int iSlice = this.imp.getCurrentSlice();
spg.replot();
//Becuase Plots array is shared between ScatterPlotGenerator and PlotStackWindow
//We could use spg to recreate the plot element in Plots array,
//which will also affect the Plots here
for (int i = 0; i < plots.length; i++){
plots[i].setImagePlus(this.imp);
//plots[i].useTemplate(tempPlot[i]);
double[] limits = spg.getTrueLimits(tempPlot[i]);
//boolean[] logScales = spg.getTrueLogs(tempPlot[i]);
plots[i].setLimits(limits[0], limits[1], limits[2], limits[3]);
plots[i].setAxisXLog(logScale);
plots[i].setAxisYLog(logScale);
plots[i].updateImage();
}
Vector<Object> currentIps = new Vector<Object>();
for (int i = 0; i < this.imp.getStackSize(); i++){
currentIps.add(this.imp.getStack().getProcessor(i + 1).getPixels());
}
for (int i = 0; i < ipRefs.size(); i++){
if(tempPlot[i] == null){
plots[i] = null;
continue;
}
int idxSlice = currentIps.indexOf(ipRefs.get(i));
if (idxSlice != -1){
this.imp.getStack().setProcessor(plots[i].getProcessor(), idxSlice + 1);
}
plots[i].updateImage();
ipRefs.remove(i);
//ipRefs.insertElementAt(plots[i].getProcessor().getPixels(), i);
ipRefs.add(i, plots[i].getProcessor().getPixels());
}
if(currentPlot != -1){
plot = plots[currentPlot];
plot.updateImage();
}else{
plot = null;
this.imp.setProcessor(ip);
}
//The following line will work
//And the above manipulation is synthesized from the following line
//drawPlot(plot);
//For some reason, the following line is not necessary
//However, I keep it here for completeness
if (ic instanceof PlotCanvas)
((PlotCanvas) ic).setPlot(plot);
//This might not be necessary either
//Just in case
if(plot !=null){
stackFrame = plot.getDrawingFrame();
frameWidth = stackFrame.width;
frameHeight = stackFrame.height;
}
}
ic.repaint();
}
@Override
public void updateSliceSelector() {
super.updateSliceSelector();
int currentPlot = ipRefs.indexOf(imp.getProcessor().getPixels());
if(currentPlot != -1)
plot = plots[currentPlot];
else
plot = null;
((PlotCanvas) getCanvas()).setPlot(plot);
}
}
| 29,884 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
HistogramStackWindow.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual2D/HistogramStackWindow.java | package ezcol.visual.visual2D;
import java.awt.*;
import java.awt.image.*;
import java.awt.event.*;
import java.awt.datatransfer.*;
import java.io.*;
import ij.*;
import ij.gui.Roi;
import ij.gui.RoiListener;
import ij.gui.StackWindow;
import ij.gui.TrimmedButton;
import ij.process.*;
import ij.measure.*;
import ij.plugin.filter.Analyzer;
/** This class is a slightly modified version of HistogramWindow from ij.gui. **/
@SuppressWarnings("serial")
public class HistogramStackWindow extends StackWindow
implements Measurements, ClipboardOwner, ImageListener, RoiListener, ActionListener, Runnable {
static final int WIN_WIDTH = 300;
static final int WIN_HEIGHT = 240;
static final int HIST_WIDTH = 256;
static final int HIST_HEIGHT = 128;
static final int BAR_HEIGHT = 12;
static final int XMARGIN = 20;
static final int YMARGIN = 10;
static final int INTENSITY = 0, RED = 1, GREEN = 2, BLUE = 3;
protected ImageStatistics stats;
protected long[] histogram;
protected LookUpTable lut;
protected Rectangle frame = null;
protected Button list, save, copy, log, live, rgb;
protected Label value, count;
protected static String defaultDirectory = null;
protected int decimalPlaces;
protected int digits;
protected long newMaxCount;
protected int plotScale = 1;
protected boolean logScale;
protected Calibration cal;
protected int yMax;
public static int nBins = 256;
private int srcImageID; // ID of source image
private ImagePlus srcImp; // source image for live histograms
private Thread bgThread; // thread background drawing
private boolean doUpdate; // tells background thread to update
private int channel; // RGB channel
private String blankLabel;
private boolean stackHistogram;
// new fields
protected ImageStatistics[] statsArray;
protected long[][] histogramArray;
protected ImageStack impStack;
protected boolean[] logScaleArray;
private int stackSize;
private boolean withScrollBar;
protected int[] numBins;
private Button increase, decrease;
private ImagePlus srcFloatImp;
/** Displays a histogram using the title "Histogram of ImageName". */
public HistogramStackWindow(ImagePlus imp) {
super(createRGBImage("Histogram of " + imp.getShortTitle()));
if (list == null)
setup(imp);
syncStack(imp);
showHistogram(imp, 256, 0.0, 0.0);
getCanvas().requestFocusInWindow();
// updateImage(createRGBImage("Histogram of "+imp.getShortTitle(),
// imp));
}
/**
* Displays a histogram using the specified title and number of bins.
* Currently, the number of bins must be 256 expect for 32 bit images.
*/
public HistogramStackWindow(String title, ImagePlus imp, int bins) {
// super(createRGBImage(title, imp));
super(createRGBImage(title));
if (list == null)
setup(imp);
// this.imp = createRGBImage(title, imp);
syncStack(imp);
showHistogram(imp, bins, 0.0, 0.0);
getCanvas().requestFocusInWindow();
// updateImage(this.imp);
}
/**
* Displays a histogram using the specified title, number of bins and
* histogram range. Currently, the number of bins must be 256 and the
* histogram range range must be the same as the image range expect for 32
* bit images.
*/
public HistogramStackWindow(String title, ImagePlus imp, int bins, double histMin, double histMax) {
super(createRGBImage(title));
if (list == null)
setup(imp);
syncStack(imp);
showHistogram(imp, bins, histMin, histMax);
getCanvas().requestFocusInWindow();
}
/**
* Displays a histogram using the specified title, number of bins, histogram
* range and yMax.
*/
public HistogramStackWindow(String title, ImagePlus imp, int bins, double histMin, double histMax, int yMax) {
super(createRGBImage(title));
this.yMax = yMax;
syncStack(imp);
showHistogram(imp, bins, histMin, histMax);
getCanvas().requestFocusInWindow();
}
/** Displays a histogram using the specified title and ImageStatistics. */
/*
* public HistogramStackWindow(String title, ImagePlus imp, ImageStatistics
* stats) { super(NewImage.createRGBImage(title, WIN_WIDTH, WIN_HEIGHT, 1,
* NewImage.FILL_WHITE)); //IJ.log("HistogramWindow: "+stats.histMin+" "
* +stats.histMax+" "+stats.nBins); this.yMax = stats.histYMax;
* impStack=this.imp.getStack(); showHistogram(imp, stats); }
*/
private void syncStack(ImagePlus imp) {
this.srcFloatImp = imp;
this.impStack = createRGBImage(this.imp.getTitle(), imp).getStack();
this.imp.setStack(null, impStack);
stackSize = impStack.getSize();
ImageStack impStack = imp.getStack();
if (stackSize == 1) {
String label = impStack.getSliceLabel(1);
if (label != null)
this.imp.setProperty("Label", label);
withScrollBar = false;
} else if (impStack.getSize() == stackSize) {
for (int i = 1; i <= stackSize; i++)
this.impStack.setSliceLabel(getShorterLabel(impStack.getSliceLabel(i), 10), i);
}
}
private String getShorterLabel(String str, int len) {
if (str == null)
return "";
else if (str.length() <= len)
return str;
else
return str.substring(0, len);
}
private static ImagePlus createRGBImage(String title, ImagePlus imp) {
ImagePlus rimp = null;
rimp = IJ.createHyperStack(title, WIN_WIDTH, WIN_HEIGHT, imp.getNChannels(), imp.getNSlices(), imp.getNFrames(),
24);
rimp.resetStack();
return rimp;
}
private static ImagePlus createRGBImage(String title) {
ImagePlus rimp = null;
rimp = IJ.createImage(title, WIN_WIDTH, WIN_HEIGHT, 1, 24);
rimp.resetStack();
return rimp;
}
/**
* Draws the histogram using the specified title and number of bins.
* Currently, the number of bins must be 256 expect for 32 bit images.
*/
public void showHistogram(ImagePlus imp, int bins) {
showHistogram(imp, bins, 0.0, 0.0);
}
/**
* Draws the histogram using the specified title, number of bins and
* histogram range. Currently, the number of bins must be 256 and the
* histogram range range must be the same as the image range expect for 32
* bit images.
*/
public void showHistogram(ImagePlus imp, int bins, double histMin, double histMax) {
// if the buttons are set up here, they will be below the slice bar
// Hide the scrollbars first before adding buttons
if (list == null) {
// hideScrollbars();
setup(imp);
// showScrollbars();
}
boolean limitToThreshold = (Analyzer.getMeasurements() & LIMIT) != 0;
ImageStack impStack = imp.getStack();
statsArray = new ImageStatistics[impStack.getSize()];
histogramArray = new long[impStack.getSize()][];
logScaleArray = new boolean[impStack.getSize()];
numBins = new int[impStack.getSize()];
for (int iSlice = 1; iSlice <= impStack.getSize(); iSlice++) {
if (channel != INTENSITY && imp.getType() == ImagePlus.COLOR_RGB) {
ColorProcessor cp = (ColorProcessor) impStack.getProcessor(iSlice);
ImageProcessor ip = cp.getChannel(channel, null);
ImagePlus imp2 = new ImagePlus("", ip);
imp2.setRoi(imp.getRoi());
stats = imp2.getStatistics(AREA + MEAN + MODE + MIN_MAX, bins, histMin, histMax);
} else {
ImagePlus imp2 = new ImagePlus("", impStack.getProcessor(iSlice));
stats = imp2.getStatistics(AREA + MEAN + MODE + MIN_MAX + (limitToThreshold ? LIMIT : 0), bins, histMin,
histMax);
}
statsArray[iSlice - 1] = stats;
numBins[iSlice - 1] = bins;
showHistogram(imp, stats, iSlice);
}
this.imp.updateAndRepaintWindow();
}
/** Draws the histogram using the specified title and ImageStatistics. */
public void showHistogram(ImagePlus imp, ImageStatistics stats, int iSlice) {
ImageStack impStack = imp.getStack();
stackHistogram = stats.stackStatistics;
// if (list==null)
// setup(imp);
this.stats = stats;
cal = imp.getCalibration();
boolean limitToThreshold = (Analyzer.getMeasurements() & LIMIT) != 0;
imp.getMask();
histogram = stats.getHistogram();
histogramArray[iSlice - 1] = histogram;
if (limitToThreshold && histogram.length == 256) {
ImageProcessor ip = impStack.getProcessor(iSlice);
if (ip.getMinThreshold() != ImageProcessor.NO_THRESHOLD) {
int lower = scaleDown(ip, ip.getMinThreshold());
int upper = scaleDown(ip, ip.getMaxThreshold());
for (int i = 0; i < lower; i++)
histogram[i] = 0L;
for (int i = upper + 1; i < 256; i++)
histogram[i] = 0L;
}
}
lut = imp.createLut();
int type = imp.getType();
boolean fixedRange = type == ImagePlus.GRAY8 || type == ImagePlus.COLOR_256 || type == ImagePlus.COLOR_RGB;
ImageProcessor ip = this.impStack.getProcessor(iSlice);
ip.setColor(Color.white);
ip.resetRoi();
ip.fill();
drawHistogram(imp, iSlice, ip, fixedRange, stats.histMin, stats.histMax);
// this.imp.updateAndDraw();
}
private void setup(ImagePlus imp) {
boolean isRGB = imp.getType() == ImagePlus.COLOR_RGB;
Panel buttons = new Panel();
int hgap = IJ.isMacOSX() || isRGB ? 1 : 5;
buttons.setLayout(new FlowLayout(FlowLayout.RIGHT, hgap, 0));
int trim = IJ.isMacOSX() ? 6 : 0;
list = new TrimmedButton("List", trim);
list.addActionListener(this);
buttons.add(list);
copy = new TrimmedButton("Copy", trim);
copy.addActionListener(this);
buttons.add(copy);
//Because inputs have negative values, taking log is not a good idea
/**
log = new TrimmedButton("Log", trim);
log.addActionListener(this);
buttons.add(log);
**/
// New buttons to increase and decrease the number of bins
increase = new TrimmedButton("nBin+", trim);
increase.addActionListener(this);
buttons.add(increase);
decrease = new TrimmedButton("nBin-", trim);
decrease.addActionListener(this);
buttons.add(decrease);
// Now reason to keep live and rgb buttons
/**
* if (!stackHistogram) { live = new TrimmedButton("Live", trim);
* live.addActionListener(this); buttons.add(live); } if (imp!=null &&
* isRGB && !stackHistogram) { rgb = new TrimmedButton("RGB", trim);
* rgb.addActionListener(this); buttons.add(rgb); }
**/
if (!(IJ.isMacOSX() && isRGB)) {
Panel valueAndCount = new Panel();
valueAndCount.setLayout(new GridLayout(2, 1, 0, 0));
blankLabel = IJ.isMacOSX() ? " " : " ";
value = new Label(blankLabel);
Font font = new Font("Monospaced", Font.PLAIN, 12);
value.setFont(font);
valueAndCount.add(value);
count = new Label(blankLabel);
count.setFont(font);
valueAndCount.add(count);
buttons.add(valueAndCount);
}
add(buttons);
pack();
}
public void setup() {
if (list == null)
setup(imp);
}
public void mouseMoved(int x, int y) {
if (value == null || count == null)
return;
if ((frame != null) && x >= frame.x && x <= (frame.x + frame.width)) {
int iSlice = imp.getCurrentSlice();
stats = statsArray[iSlice - 1];
histogram = histogramArray[iSlice - 1];
x = x - frame.x;
if (x > 255)
x = 255;
int index = (int) (x * ((double) histogram.length) / HIST_WIDTH);
String vlabel = null, clabel = null;
if (blankLabel.length() == 11) // OS X
{
vlabel = " ";
clabel = " ";
} else {
vlabel = " value=";
clabel = " count=";
}
String v = vlabel + d2s(cal.getCValue(stats.histMin + index * stats.binSize)) + blankLabel;
String c = clabel + histogram[index] + blankLabel;
int len = vlabel.length() + blankLabel.length();
value.setText(v.substring(0, len));
count.setText(c.substring(0, len));
} else {
value.setText(blankLabel);
count.setText(blankLabel);
}
}
protected void drawHistogram(ImageProcessor ip, boolean fixedRange) {
drawHistogram(null, 1, ip, fixedRange, 0.0, 0.0);
}
void drawHistogram(ImagePlus imp, int iSlice, ImageProcessor ip, boolean fixedRange, double xMin, double xMax) {
int x, y;
long maxCount2 = 0;
@SuppressWarnings("unused")
int mode2 = 0;
long saveModalCount;
ip.setColor(Color.black);
ip.setLineWidth(1);
decimalPlaces = Analyzer.getPrecision();
digits = cal.calibrated() || stats.binSize != 1.0 ? decimalPlaces : 0;
saveModalCount = histogram[stats.mode];
for (int i = 0; i < histogram.length; i++) {
if ((histogram[i] > maxCount2) && (i != stats.mode)) {
maxCount2 = histogram[i];
mode2 = i;
}
}
newMaxCount = histogram[stats.mode];
if ((newMaxCount > (maxCount2 * 2)) && (maxCount2 != 0)) {
newMaxCount = (int) (maxCount2 * 1.5);
// histogram[stats.mode] = newMaxCount;
}
if (logScale || IJ.shiftKeyDown() && !liveMode())
drawLogPlot(yMax > 0 ? yMax : newMaxCount, ip);
drawPlot(yMax > 0 ? yMax : newMaxCount, ip);
histogram[stats.mode] = saveModalCount;
x = XMARGIN + 1;
y = YMARGIN + HIST_HEIGHT + 2;
if (imp == null)
lut.drawUnscaledColorBar(ip, x - 1, y, 256, BAR_HEIGHT);
else
drawAlignedColorBar(imp, iSlice, xMin, xMax, ip, x - 1, y, 256, BAR_HEIGHT);
y += BAR_HEIGHT + 15;
drawText(ip, x, y, fixedRange);
srcImageID = imp.getID();
}
void drawAlignedColorBar(ImagePlus imp, int iSlice, double xMin, double xMax, ImageProcessor ip, int x, int y,
int width, int height) {
ImageProcessor ipSource = imp.getStack().getProcessor(iSlice);
float[] pixels = null;
ImageProcessor ipRamp = null;
if (ipSource instanceof ColorProcessor) {
ipRamp = new FloatProcessor(width, height);
if (channel == RED)
ipRamp.setColorModel(LUT.createLutFromColor(Color.red));
else if (channel == GREEN)
ipRamp.setColorModel(LUT.createLutFromColor(Color.green));
else if (channel == BLUE)
ipRamp.setColorModel(LUT.createLutFromColor(Color.blue));
pixels = (float[]) ipRamp.getPixels();
} else
pixels = new float[width * height];
for (int j = 0; j < height; j++) {
for (int i = 0; i < width; i++)
pixels[i + width * j] = (float) (xMin + i * (xMax - xMin) / (width - 1));
}
double min = stats != null ? stats.min : ipSource.getMin();
double max = stats != null ? stats.max : ipSource.getMax();
if (!(ipSource instanceof ColorProcessor)) {
ColorModel cm = null;
if (imp.isComposite()) {
if (stats != null && stats.pixelCount > ipSource.getPixelCount()) { // stack
// histogram
cm = LUT.createLutFromColor(Color.white);
min = stats.min;
max = stats.max;
} else
cm = ((CompositeImage) imp).getChannelLut();
} else if (ipSource.getMinThreshold() == ImageProcessor.NO_THRESHOLD)
cm = ipSource.getColorModel();
else
cm = ipSource.getCurrentColorModel();
ipRamp = new FloatProcessor(width, height, pixels, cm);
}
ipRamp.setMinAndMax(min, max);
ImageProcessor bar = null;
if (ip instanceof ColorProcessor)
bar = ipRamp.convertToRGB();
else
bar = ipRamp.convertToByte(true);
ip.insert(bar, x, y);
ip.setColor(Color.black);
ip.drawRect(x - 1, y, width + 2, height);
}
/** Scales a threshold level to the range 0-255. */
int scaleDown(ImageProcessor ip, double threshold) {
double min = ip.getMin();
double max = ip.getMax();
if (max > min)
return (int) (((threshold - min) / (max - min)) * 255.0);
else
return 0;
}
void drawPlot(long maxCount, ImageProcessor ip) {
if (maxCount == 0)
maxCount = 1;
frame = new Rectangle(XMARGIN, YMARGIN, HIST_WIDTH, HIST_HEIGHT);
ip.drawRect(frame.x - 1, frame.y, frame.width + 2, frame.height + 1);
if (histogram.length <= HIST_WIDTH) {
int index, y;
for (int i = 0; i < HIST_WIDTH; i++) {
index = (int) (i * (double) histogram.length / HIST_WIDTH);
y = (int) (((double) HIST_HEIGHT * (double) histogram[index]) / maxCount);
if (y > HIST_HEIGHT)
y = HIST_HEIGHT;
ip.drawLine(i + XMARGIN, YMARGIN + HIST_HEIGHT, i + XMARGIN, YMARGIN + HIST_HEIGHT - y);
}
} else {
double xscale = (double) HIST_WIDTH / histogram.length;
for (int i = 0; i < histogram.length; i++) {
long value = histogram[i];
if (value > 0L) {
int y = (int) (((double) HIST_HEIGHT * (double) value) / maxCount);
if (y > HIST_HEIGHT)
y = HIST_HEIGHT;
int x = (int) (i * xscale) + XMARGIN;
ip.drawLine(x, YMARGIN + HIST_HEIGHT, x, YMARGIN + HIST_HEIGHT - y);
}
}
}
}
void drawLogPlot(long maxCount, ImageProcessor ip) {
frame = new Rectangle(XMARGIN, YMARGIN, HIST_WIDTH, HIST_HEIGHT);
ip.drawRect(frame.x - 1, frame.y, frame.width + 2, frame.height + 1);
double max = Math.log(maxCount);
ip.setColor(Color.gray);
if (histogram.length <= HIST_WIDTH) {
int index, y;
for (int i = 0; i < HIST_WIDTH; i++) {
index = (int) (i * (double) histogram.length / HIST_WIDTH);
y = histogram[index] == 0 ? 0 : (int) (HIST_HEIGHT * Math.log(histogram[index]) / max);
if (y > HIST_HEIGHT)
y = HIST_HEIGHT;
ip.drawLine(i + XMARGIN, YMARGIN + HIST_HEIGHT, i + XMARGIN, YMARGIN + HIST_HEIGHT - y);
}
} else {
double xscale = (double) HIST_WIDTH / histogram.length;
for (int i = 0; i < histogram.length; i++) {
long value = histogram[i];
if (value > 0L) {
int y = (int) (HIST_HEIGHT * Math.log(value) / max);
if (y > HIST_HEIGHT)
y = HIST_HEIGHT;
int x = (int) (i * xscale) + XMARGIN;
ip.drawLine(x, YMARGIN + HIST_HEIGHT, x, YMARGIN + HIST_HEIGHT - y);
}
}
}
ip.setColor(Color.black);
}
void drawText(ImageProcessor ip, int x, int y, boolean fixedRange) {
ip.setFont(new Font("SansSerif", Font.PLAIN, 12));
ip.setAntialiasedText(true);
double hmin = cal.getCValue(stats.histMin);
double hmax = cal.getCValue(stats.histMax);
double range = hmax - hmin;
if (fixedRange && !cal.calibrated() && hmin == 0 && hmax == 255)
range = 256;
ip.drawString(d2s(hmin), x - 4, y);
ip.drawString(d2s(hmax), x + HIST_WIDTH - getWidth(hmax, ip) + 10, y);
double binWidth = range / stats.nBins;
binWidth = Math.abs(binWidth);
boolean showBins = binWidth != 1.0 || !fixedRange;
int col1 = XMARGIN + 5;
int col2 = XMARGIN + HIST_WIDTH / 2;
int row1 = y + 25;
if (showBins)
row1 -= 8;
int row2 = row1 + 15;
int row3 = row2 + 15;
int row4 = row3 + 15;
long count = stats.longPixelCount > 0 ? stats.longPixelCount : stats.pixelCount;
String modeCount = " (" + stats.maxCount + ")";
if (modeCount.length() > 12)
modeCount = "";
ip.drawString("Count: " + count, col1, row1);
ip.drawString("Mean: " + d2s(stats.mean), col1, row2);
ip.drawString("StdDev: " + d2s(stats.stdDev), col1, row3);
ip.drawString("Mode: " + d2s(stats.dmode) + modeCount, col2, row3);
ip.drawString("Min: " + d2s(stats.min), col2, row1);
ip.drawString("Max: " + d2s(stats.max), col2, row2);
if (showBins) {
ip.drawString("Bins: " + d2s(stats.nBins), col1, row4);
ip.drawString("Bin Width: " + d2s(binWidth), col2, row4);
}
}
/*
* String d2s(double d) { if (d==Double.MAX_VALUE||d==-Double.MAX_VALUE)
* return "0"; else if (Double.isNaN(d)) return("NaN"); else if
* (Double.isInfinite(d)) return("Infinity"); else if ((int)d==d) return
* ResultsTable.d2s(d,0); else return ResultsTable.d2s(d,decimalPlaces); }
*/
private String d2s(double d) {
if ((int) d == d)
return IJ.d2s(d, 0);
else
return IJ.d2s(d, 3, 8);
}
int getWidth(double d, ImageProcessor ip) {
return ip.getStringWidth(d2s(d));
}
/** Returns the histogram values as a ResultsTable. */
public ResultsTable getResultsTable() {
ResultsTable rt = new ResultsTable();
rt.showRowNumbers(false);
String vheading = stats.binSize == 1.0 ? "value" : "bin start";
if (cal.calibrated() && !cal.isSigned16Bit()) {
for (int i = 0; i < stats.nBins; i++) {
rt.setValue("level", i, i);
rt.setValue(vheading, i, cal.getCValue(stats.histMin + i * stats.binSize));
rt.setValue("count", i, histogram[i]);
}
rt.setDecimalPlaces(0, 0);
rt.setDecimalPlaces(1, digits);
rt.setDecimalPlaces(2, 0);
} else {
for (int i = 0; i < stats.nBins; i++) {
rt.setValue(vheading, i, cal.getCValue(stats.histMin + i * stats.binSize));
rt.setValue("count", i, histogram[i]);
}
rt.setDecimalPlaces(0, digits);
rt.setDecimalPlaces(1, 0);
}
return rt;
}
protected void showList() {
ResultsTable rt = getResultsTable();
rt.show(getTitle());
}
protected void copyToClipboard() {
Clipboard systemClipboard = null;
try {
systemClipboard = getToolkit().getSystemClipboard();
} catch (Exception e) {
systemClipboard = null;
}
if (systemClipboard == null) {
IJ.error("Unable to copy to Clipboard.");
return;
}
IJ.showStatus("Copying histogram values...");
CharArrayWriter aw = new CharArrayWriter(stats.nBins * 4);
PrintWriter pw = new PrintWriter(aw);
for (int i = 0; i < stats.nBins; i++)
pw.print(ResultsTable.d2s(cal.getCValue(stats.histMin + i * stats.binSize), digits) + "\t" + histogram[i]
+ "\n");
String text = aw.toString();
pw.close();
StringSelection contents = new StringSelection(text);
systemClipboard.setContents(contents, this);
IJ.showStatus(text.length() + " characters copied to Clipboard");
}
void replot() {
ImageProcessor ip = this.imp.getProcessor();
frame = new Rectangle(XMARGIN, YMARGIN, HIST_WIDTH, HIST_HEIGHT);
ip.setColor(Color.white);
ip.setRoi(frame.x - 1, frame.y, frame.width + 2, frame.height);
ip.fill();
ip.resetRoi();
ip.setColor(Color.black);
if (logScale) {
drawLogPlot(yMax > 0 ? yMax : newMaxCount, ip);
drawPlot(yMax > 0 ? yMax : newMaxCount, ip);
} else
drawPlot(yMax > 0 ? yMax : newMaxCount, ip);
this.imp.updateAndDraw();
}
/**
* Redraw current histogram after the number of bins has been changed
*/
void replotHistogram(int iSlice){
boolean limitToThreshold = (Analyzer.getMeasurements() & LIMIT) != 0;
ImagePlus imp = this.srcFloatImp;
ImageStack impStack = imp.getStack();
double histMin = stats.histMin;
double histMax = stats.histMax;
int bins = numBins[iSlice - 1];
if (channel != INTENSITY && imp.getType() == ImagePlus.COLOR_RGB) {
ColorProcessor cp = (ColorProcessor) impStack.getProcessor(iSlice);
ImageProcessor ip = cp.getChannel(channel, null);
ImagePlus imp2 = new ImagePlus("", ip);
imp2.setRoi(imp.getRoi());
stats = imp2.getStatistics(AREA + MEAN + MODE + MIN_MAX, bins, histMin, histMax);
} else {
ImagePlus imp2 = new ImagePlus("", impStack.getProcessor(iSlice));
stats = imp2.getStatistics(AREA + MEAN + MODE + MIN_MAX + (limitToThreshold ? LIMIT : 0), bins, histMin,
histMax);
}
statsArray[iSlice - 1] = stats;
numBins[iSlice - 1] = bins;
showHistogram(imp, stats, iSlice);
this.imp.updateAndRepaintWindow();
}
/*
* void rescale() { Graphics g = img.getGraphics(); plotScale *= 2; if
* ((newMaxCount/plotScale)<50) { plotScale = 1; frame = new
* Rectangle(XMARGIN, YMARGIN, HIST_WIDTH, HIST_HEIGHT);
* g.setColor(Color.white); g.fillRect(frame.x, frame.y, frame.width,
* frame.height); g.setColor(Color.black); } drawPlot(newMaxCount/plotScale,
* g); //ImageProcessor ip = new ColorProcessor(img);
* //this.imp.setProcessor(null, ip); this.imp.setImage(img); }
*/
public void actionPerformed(ActionEvent e) {
super.actionPerformed(e);
int iSlice = imp.getCurrentSlice();
stats = statsArray[iSlice - 1];
histogram = histogramArray[iSlice - 1];
logScale = logScaleArray[iSlice - 1];
Object b = e.getSource();
if (b == live)
toggleLiveMode();
else if (b == rgb)
changeChannel();
else if (b == list)
showList();
else if (b == copy)
copyToClipboard();
else if (b == log) {
logScale = !logScale;
logScaleArray[iSlice - 1] = logScale;
replot();
} else if (b == increase) {
numBins[iSlice - 1]++;
replotHistogram(iSlice);
} else if (b == decrease) {
if(numBins[iSlice - 1] > 1){
numBins[iSlice - 1]--;
replotHistogram(iSlice);
}
}
}
public void lostOwnership(Clipboard clipboard, Transferable contents) {
}
public int[] getHistogram() {
int[] hist = new int[histogram.length];
for (int i = 0; i < histogram.length; i++)
hist[i] = (int) histogram[i];
return hist;
}
public double[] getXValues() {
double[] values = new double[stats.nBins];
for (int i = 0; i < stats.nBins; i++)
values[i] = cal.getCValue(stats.histMin + i * stats.binSize);
return values;
}
private void toggleLiveMode() {
if (liveMode())
removeListeners();
else
enableLiveMode();
}
private void changeChannel() {
ImagePlus imp = WindowManager.getImage(srcImageID);
if (imp == null || imp.getType() != ImagePlus.COLOR_RGB) {
channel = INTENSITY;
return;
} else {
channel++;
if (channel > BLUE)
channel = INTENSITY;
showHistogram(imp, 256);
String name = this.imp.getTitle();
if (name.startsWith("Red "))
name = name.substring(4);
else if (name.startsWith("Green "))
name = name.substring(6);
else if (name.startsWith("Blue "))
name = name.substring(5);
switch (channel) {
case INTENSITY:
this.imp.setTitle(name);
break;
case RED:
this.imp.setTitle("Red " + name);
break;
case GREEN:
this.imp.setTitle("Green " + name);
break;
case BLUE:
this.imp.setTitle("Blue " + name);
break;
}
}
}
private boolean liveMode() {
return live != null && live.getForeground() == Color.red;
}
private void enableLiveMode() {
if (bgThread == null) {
srcImp = WindowManager.getImage(srcImageID);
if (srcImp == null)
return;
bgThread = new Thread(this, "Live Histogram");
bgThread.setPriority(Math.max(bgThread.getPriority() - 3, Thread.MIN_PRIORITY));
bgThread.start();
imageUpdated(srcImp);
}
createListeners();
if (srcImp != null)
imageUpdated(srcImp);
}
// Unused
public void imageOpened(ImagePlus imp) {
}
// This listener is called if the source image content is changed
public synchronized void imageUpdated(ImagePlus imp) {
if (imp == srcImp) {
doUpdate = true;
notify();
}
}
public synchronized void roiModified(ImagePlus img, int id) {
if (img == srcImp) {
doUpdate = true;
notify();
}
}
// If either the source image or this image are closed, exit
public void imageClosed(ImagePlus imp) {
if (imp == srcImp || imp == this.imp) {
if (bgThread != null)
bgThread.interrupt();
bgThread = null;
removeListeners();
srcImp = null;
}
}
// the background thread for live plotting.
@Override
public void run() {
while (!done) {
synchronized (this) {
try {
wait();
} // notify wakes up the thread
catch (InterruptedException e) {
}
}
if (done)
return;
if (doUpdate && srcImp != null && Thread.currentThread() == bgThread) {
if (srcImp.getRoi() != null)
IJ.wait(50); // delay to make sure the roi has been updated
if (srcImp != null) {
if (srcImp.getNChannels() != imp.getNChannels() || srcImp.getNFrames() != imp.getNFrames()
|| srcImp.getNSlices() != imp.getNSlices()) {
setImage(createRGBImage(imp.getShortTitle(), srcImp));
updateSliceSelector();
}
syncStack(srcImp);
updateScrollBars();
if (srcImp.getBitDepth() == 16 && ImagePlus.getDefault16bitRange() != 0)
showHistogram(srcImp, 256, 0, Math.pow(2, ImagePlus.getDefault16bitRange()) - 1);
else
showHistogram(srcImp, 256);
repaint();
int slice = srcImp.getCurrentSlice();
if (slice > 0 && slice <= imp.getStackSize() && slice != imp.getCurrentSlice())
imp.setSlice(slice);
}
doUpdate = false;
}
//if (done)
// return;
if (Thread.currentThread() == thread && slice > 0) {
int s = slice;
slice = 0;
if (imp != null && s != imp.getCurrentSlice())
imp.setSlice(s);
}
}
}
private void createListeners() {
if (srcImp == null)
return;
ImagePlus.addImageListener(this);
Roi.addRoiListener(this);
if (live != null) {
Font font = live.getFont();
live.setFont(new Font(font.getName(), Font.BOLD, font.getSize()));
live.setForeground(Color.red);
}
}
private void removeListeners() {
if (srcImp == null)
return;
ImagePlus.removeImageListener(this);
Roi.removeRoiListener(this);
if (live != null) {
Font font = live.getFont();
live.setFont(new Font(font.getName(), Font.PLAIN, font.getSize()));
live.setForeground(Color.black);
}
}
private void updateScrollBars() {
int stackSize = imp.getStackSize();
if (stackSize == 1 && !withScrollBar) {
hideScrollbars();
withScrollBar = true;
} else if (stackSize > 1 && withScrollBar)
showScrollbars();
}
protected void hideScrollbars() {
if (cSelector != null) {
cSelector.setVisible(false);
cSelector.removeAdjustmentListener(this);
}
if (zSelector != null) {
zSelector.setVisible(false);
zSelector.removeAdjustmentListener(this);
}
if (tSelector != null) {
tSelector.setVisible(false);
tSelector.removeAdjustmentListener(this);
}
// pack();
}
protected void showScrollbars() {
if (cSelector != null) {
cSelector.setVisible(true);
cSelector.addAdjustmentListener(this);
}
if (zSelector != null) {
zSelector.setVisible(true);
zSelector.addAdjustmentListener(this);
}
if (tSelector != null) {
tSelector.setVisible(true);
tSelector.addAdjustmentListener(this);
}
// pack();
}
}
| 28,997 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
ScatterPlotGenerator.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual2D/ScatterPlotGenerator.java | package ezcol.visual.visual2D;
import java.util.Arrays;
import ij.ImagePlus;
import ij.ImageStack;
import ij.gui.Plot;
import ezcol.metric.CostesThreshold;
public class ScatterPlotGenerator {
public static final int INITIAL_SIZE = 25;
private ImageStack impStack;
private ImagePlus imp;
private PlotStackWindow psw;
private String title;
private int flags;
private int width = 400, height = 400;
private int nPlots;
private Plot[] plots;
private float[][] xValues;
private float[][] yValues;
private String[] xLabels;
private String[] yLabels;
private String[] sliceLabels;
public ScatterPlotGenerator() {
this(null, Plot.getDefaultFlags());
}
public ScatterPlotGenerator(String title) {
this(title, Plot.getDefaultFlags());
}
public ScatterPlotGenerator(String title, int flags) {
this.title = title;
this.flags = flags;
this.xValues = new float[INITIAL_SIZE][];
this.yValues = new float[INITIAL_SIZE][];
this.xLabels = new String[INITIAL_SIZE];
this.yLabels = new String[INITIAL_SIZE];
this.sliceLabels = new String[INITIAL_SIZE];
}
public ScatterPlotGenerator(String title, String xLabel, String yLabel, float[][] xValues, float[][] yValues,
String[] sliceLabels) {
this(title, xLabel, yLabel, xValues, yValues, sliceLabels, Plot.getDefaultFlags());
}
public ScatterPlotGenerator(float[][] xValues, float[][] yValues, String[] sliceLabels) {
this("Plot", "X", "Y", xValues, yValues, sliceLabels, Plot.getDefaultFlags());
}
public ScatterPlotGenerator(String title, String xLabel, String yLabel, float[][] xValues, float[][] yValues,
String[] sliceLabels, int flags) {
if (yValues != null && yValues.length > 0) {
nPlots = yValues.length;
plots = new Plot[nPlots];
this.title = title;
this.flags = flags;
sliceLabels = alignArray(sliceLabels, nPlots);
xValues = alignArray(xValues, yValues, nPlots);
this.xValues = xValues.clone();
this.yValues = yValues.clone();
this.xLabels = new String[nPlots];
this.yLabels = new String[nPlots];
for (int i = 0; i < nPlots; i++) {
this.xLabels[i] = xLabel;
this.yLabels[i] = yLabel;
}
this.sliceLabels = sliceLabels.clone();
addPlots(this.xLabels, this.yLabels, this.xValues, this.yValues, this.sliceLabels);
}
}
public ScatterPlotGenerator(String title, String[] xLabels, String[] yLabels, float[][] xValues, float[][] yValues,
String[] sliceLabels, int flags) {
if (yValues != null && yValues.length > 0) {
nPlots = yValues.length;
plots = new Plot[nPlots];
this.title = title;
this.flags = flags;
xLabels = alignArray(xLabels, nPlots);
yLabels = alignArray(yLabels, nPlots);
sliceLabels = alignArray(sliceLabels, nPlots);
xValues = alignArray(xValues, yValues, nPlots);
this.xValues = xValues.clone();
this.yValues = yValues.clone();
this.xLabels = xLabels.clone();
this.yLabels = yLabels.clone();
this.sliceLabels = sliceLabels.clone();
addPlots(this.xLabels, this.yLabels, this.xValues, this.yValues, this.sliceLabels);
}
}
public void addPlot(float[] xValues, float[] yValues) {
addPlot(null, null, null, xValues, yValues);
}
/**
* This part of code mimics that of ImageStack addSlice Maybe because of
* performance, the array length is increase by 2-fold at each out-of-bound
* event
*
* @param sliceLabel
* @param xLabel
* @param yLabel
* @param xValues
* @param yValues
*/
public void addPlot(String sliceLabel, String xLabel, String yLabel, float[] xValue, float[] yValue) {
int size = xValues.length;
nPlots++;
if (nPlots >= size) {
float[][] tmp1 = new float[size * 2][];
System.arraycopy(xValues, 0, tmp1, 0, size);
xValues = tmp1;
float[][] tmp2 = new float[size * 2][];
System.arraycopy(yValues, 0, tmp2, 0, size);
yValues = tmp2;
String[] tmp3 = new String[size * 2];
System.arraycopy(xLabels, 0, tmp3, 0, size);
xLabels = tmp3;
String[] tmp4 = new String[size * 2];
System.arraycopy(yLabels, 0, tmp4, 0, size);
yLabels = tmp4;
String[] tmp5 = new String[size * 2];
System.arraycopy(sliceLabels, 0, tmp5, 0, size);
sliceLabels = tmp5;
}
xValues[nPlots - 1] = xValue;
yValues[nPlots - 1] = yValue;
xLabels[nPlots - 1] = xLabel;
yLabels[nPlots - 1] = yLabel;
sliceLabels[nPlots - 1] = sliceLabel;
}
public void showPlot(boolean display) {
if (yValues != null && yValues.length > 0) {
// nPlots = yValues.length;
plots = new Plot[nPlots];
xLabels = alignArray(xLabels, nPlots);
yLabels = alignArray(yLabels, nPlots);
sliceLabels = alignArray(sliceLabels, nPlots);
xValues = alignArray(xValues, yValues, nPlots);
yValues = alignArray(yValues, yValues, nPlots);
addPlots(xLabels, yLabels, xValues, yValues, sliceLabels);
}
if (display)
show();
}
private float[][] alignArray(float[][] array, float[][] fillarray, int length) {
if (length < 0)
return null;
float[][] result = new float[length][];
if (array == null) {
System.arraycopy(fillarray, 0, result, 0, length);
} else if (array.length < length) {
System.arraycopy(array, 0, result, 0, array.length);
if (fillarray.length >= length)
System.arraycopy(fillarray, array.length, result, array.length, length - array.length);
} else if (array.length > length)
System.arraycopy(array, 0, result, 0, length);
else
return array;
return result;
}
private String[] alignArray(String[] array, int length) {
if (length < 0)
return null;
String[] result = new String[length];
if (array == null) {
Arrays.fill(result, "");
} else if (array.length < length) {
System.arraycopy(array, 0, result, 0, array.length);
Arrays.fill(array, array.length, length - 1, "");
} else if (array.length > length)
System.arraycopy(array, 0, result, 0, length);
else
return array;
return result;
}
private void addPlot(String xLabel, String yLabel, float[] xValues, float[] yValues, String sliceLabel,
int iSlice) {
if (plots == null)
return;
plots[iSlice] = new Plot(title, xLabel, yLabel, (float[]) null, (float[]) null, flags);
plots[iSlice].setFrameSize(width, height);
plots[iSlice].addPoints(xValues, yValues, null, Plot.toShape("circle"), sliceLabel);
// Plot bug: the plot cannot automatically generate if there is only one
// data point
// The range must be manually set
// limits will only be generated after Plot.draw();
// Therefore, no need to getLimits here
// double[] limits = plots[iSlice].getLimits();
double[] limits = new double[4];
if (yValues.length == 1) {
limits[2] = yValues[0] * 0.8;
limits[3] = yValues[0] * 1.2;
}
if (xValues.length == 1) {
limits[0] = xValues[0] * 0.8;
limits[1] = xValues[0] * 1.2;
}
if (yValues.length == 1 || xValues.length == 1)
plots[iSlice].setLimits(limits[0], limits[1], limits[2], limits[3]);
if (iSlice == 0) {
imp = plots[iSlice].getImagePlus();
impStack = imp.getStack();
impStack.setSliceLabel(sliceLabel, 1);
} else {
impStack.addSlice(sliceLabel, plots[iSlice].getProcessor());
}
}
private void addPlots(String[] xLabels, String[] yLabels, float[][] xValues, float[][] yValues,
String[] sliceLabels) {
for (int i = 0; i < nPlots; i++) {
addPlot(xLabels[i], yLabels[i], xValues[i], yValues[i], sliceLabels[i], i);
}
imp = new ImagePlus(title, impStack);
}
public PlotStackWindow show() {
if(plots != null && imp != null)
psw = new PlotStackWindow(plots, imp, this);
else
psw = null;
// psw.showStack();
return psw;
}
public void setFrameSize(int width, int height) {
this.width = width;
this.height = height;
if (plots == null)
return;
String[] labels = impStack.getSliceLabels();
for (int iSlice = 0; iSlice < plots.length; iSlice++) {
plots[iSlice].setFrameSize(width, height);
if (iSlice == 0) {
imp = plots[iSlice].getImagePlus();
impStack = imp.getStack();
impStack.setSliceLabel(labels[iSlice], iSlice + 1);
}
impStack.addSlice(labels[iSlice], plots[iSlice].getProcessor());
}
imp = new ImagePlus(title, impStack);
}
public void addCostes() {
if (plots == null)
return;
CostesThreshold costesTholder = new CostesThreshold();
// Must call updateImage() to update the current plot
// addLegend will automatically do that
// Otherwise, it won't show up on the plot until the user zoom
addRegressionLine();
for (int iSlice = 0; iSlice < nPlots ; iSlice++) {
double[] tholds = costesTholder.getCostesThrd(xValues[iSlice], yValues[iSlice]);
addDashLines((float) tholds[0], (float) tholds[1], iSlice);
plots[iSlice].addLegend("Data --- Costes");
plots[iSlice].updateImage();
}
}
/*
* Used for additional threshold lines
*/
public void addDashLines(float xThold, float yThold, int iSlice) {
if (plots == null)
return;
int step = 10;
double[] limits = getTrueLimits(plots[iSlice]);
double[] plotLimits = plots[iSlice].getLimits();
boolean[] logScales = getTrueLogs(plots[iSlice]);
double ystep = ((plotLimits[1] - plotLimits[0]) / step / 2);
double xstep = ((plotLimits[3] - plotLimits[2]) / step / 2);
ystep = ystep > 0 ? ystep : 1;
xstep = xstep > 0 ? xstep : 1;
if (yThold < limits[2])
yThold = (float) limits[2];
else if (yThold > limits[3])
yThold = (float) limits[3];
if (xThold < limits[0])
xThold = (float) limits[0];
else if (xThold > limits[1])
xThold = (float) limits[1];
for (int i = 0; i < step; i++) {
if (logScales[0])
plots[iSlice].drawLine(Math.pow(10, plotLimits[0] + ystep * i * 2), yThold,
Math.pow(10, plotLimits[0] + ystep * (2 * i + 1)), yThold);
else
plots[iSlice].drawLine(plotLimits[0] + ystep * i * 2, yThold, plotLimits[0] + ystep * (2 * i + 1),
yThold);
if (logScales[1])
plots[iSlice].drawLine(xThold, Math.pow(10, plotLimits[2] + xstep * i * 2), xThold,
Math.pow(10, plotLimits[2] + xstep * (2 * i + 1)));
else
plots[iSlice].drawLine(xThold, plotLimits[2] + xstep * i * 2, xThold,
plotLimits[2] + xstep * (2 * i + 1));
}
}
public void addSolidLines(float xThold, float yThold, int iSlice) {
if (plots == null)
return;
int step = 20;
double[] limits = getTrueLimits(plots[iSlice]);
int ystep = (int) ((limits[1] - limits[0]) / step / 2);
int xstep = (int) ((limits[3] - limits[2]) / step / 2);
ystep = ystep > 0 ? ystep : 1;
xstep = xstep > 0 ? xstep : 1;
if (yThold < limits[2])
yThold = (float) limits[2];
else if (yThold > limits[3])
yThold = (float) limits[3];
if (xThold < limits[0])
xThold = (float) limits[0];
else if (xThold > limits[1])
xThold = (float) limits[1];
plots[iSlice].drawLine(limits[0], yThold, limits[1], yThold);
plots[iSlice].drawLine(xThold, limits[2], xThold, limits[3]);
}
private void addRegressionLine() {
addRegressionLine(xValues, yValues);
}
private void addRegressionLine(float[][] xValues, float[][] yValues) {
if (xValues == null || yValues == null)
return;
CostesThreshold costes = new CostesThreshold();
for (int i = 0; i < nPlots; i++) {
double[] lngs = costes.linreg(xValues[i], yValues[i]);
addLine(lngs, i);
}
}
// draw linear regression line
public void addLine(double[] tmps, int iSlice) {
if (plots == null || tmps == null || tmps.length < 2)
return;
double[] limits = getTrueLimits(plots[iSlice]);
boolean[] logScales = getTrueLogs(plots[iSlice]);
//double[] plotLimits = plots[iSlice].getLimits();
// limits: {xMin, xMax, yMin, yMax}
double x1, x2;
//double y1, y2;
if (tmps[0] < 0) {
x1 = ((limits[3] - tmps[1]) / tmps[0]);
//y1 = (limits[0] * tmps[0] + tmps[1]);
x2 = ((limits[2] - tmps[1]) / tmps[0]);
//y2 = (limits[1] * tmps[0] + tmps[1]);
} else {
x1 = ((limits[3] - tmps[1]) / tmps[0]);
//y1 = (limits[1] * tmps[0] + tmps[1]);
x2 = ((limits[2] - tmps[1]) / tmps[0]);
//y2 = (limits[0] * tmps[0] + tmps[1]);
}
if (x1 < limits[0])
x1 = limits[0];
else if (x1 > limits[1])
x1 = limits[1];
/*if (y1 < limits[2])
y1 = limits[2];
else if (y1 > limits[3])
y1 = limits[3];*/
if (x2 < limits[0])
x2 = limits[0];
else if (x2 > limits[1])
x2 = limits[1];
/*if (y2 < limits[2])
y2 = limits[2];
else if (y2 > limits[3])
y2 = limits[3];*/
int n = 100;
float[] xValues = new float[n];
float[] yValues = new float[n];
if (logScales[0]) {
x1 = Math.log10(x1);
x2 = Math.log10(x2);
}
double xInterval = (x2 - x1) / n;
for (int i = 0; i < n; i++) {
if (logScales[0])
xValues[i] = (float) Math.pow(10, x1 + xInterval * i);
else
xValues[i] = (float) (x1 + xInterval * i);
yValues[i] = (float) (xValues[i] * tmps[0] + tmps[1]);
}
plots[iSlice].addPoints(xValues, yValues, null, Plot.LINE, "Linear Regression");
}
/**
* Because ImageJ Plot class doesn't offer a way to remove PlotObjects I
* have to replot the whole thing to remove extra Costes' threshold lines
*/
public ImagePlus replot() {
addPlots(xLabels, yLabels, xValues, yValues, sliceLabels);
return imp;
}
/**
* Tell if a plot really uses log scale
*
* @param plot
* @return {xTruelogScale, yTruelogScale}
*/
public boolean[] getTrueLogs(Plot plot) {
boolean[] trueLogs = new boolean[2];
double xScale1 = plot.scaleXtoPxl(10) - plot.scaleXtoPxl(1);
// if (plot.logXAxis == true) xScale1 = 9 * plot.xScale
// else xScale1 = plot.xScale
double xScale2 = plot.scaleXtoPxl(100) - plot.scaleXtoPxl(10);
// if (plot.logXAxis == true) xScale2 = 99 * plot.xScale
// else xScale2 = plot.xScale
// Assuming xScale != 0, we can tell whether logXAxis is true or not
trueLogs[0] = xScale2 < 5 * xScale1;
double yScale1 = plot.scaleYtoPxl(1) - plot.scaleYtoPxl(10);
// if (plot.logYAxis == true) yScale1 = 9 * plot.yScale
// else yScale1 = plot.yScale
double yScale2 = plot.scaleYtoPxl(10) - plot.scaleYtoPxl(100);
// if (plot.logYAxis == true) yScale2 = 99 * plot.yScale
// else yScale2 = plot.xScale
trueLogs[1] = yScale2 < 5 * yScale1;
return trueLogs;
}
public double[] getTrueLimits(Plot plot) {
boolean[] trueLogs = getTrueLogs(plot);
double[] limits = plot.getLimits();
if (trueLogs[0]) {
limits[0] = Math.pow(10, limits[0]);
limits[1] = Math.pow(10, limits[1]);
}
if (trueLogs[1]) {
limits[2] = Math.pow(10, limits[2]);
limits[3] = Math.pow(10, limits[3]);
}
return limits;
}
} | 14,430 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Rect3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/Rect3D.java | /*******************************************************************************
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
import java.awt.*;
public class Rect3D extends Element3D{
public Point3D[] pt;
public int xsize,ysize,zsize;
// here we have a 3D line
public Rect3D(int x,int y,int z,int xsize1,int ysize1,int zsize1,Color color1){
pt=new Point3D[8];
xsize=xsize1;
ysize=ysize1;
zsize=zsize1;
int halfxsize=xsize/2;
int halfysize=ysize/2;
int halfzsize=zsize/2;
// start with the upper square
pt[0]=new Point3D(x-halfxsize,y-halfysize,z-halfzsize);
pt[1]=new Point3D(x+halfxsize,y-halfysize,z-halfzsize);
pt[2]=new Point3D(x+halfxsize,y+halfysize,z-halfzsize);
pt[3]=new Point3D(x-halfxsize,y+halfysize,z-halfzsize);
pt[4]=new Point3D(x-halfxsize,y-halfysize,z+halfzsize);
pt[5]=new Point3D(x+halfxsize,y-halfysize,z+halfzsize);
pt[6]=new Point3D(x+halfxsize,y+halfysize,z+halfzsize);
pt[7]=new Point3D(x-halfxsize,y+halfysize,z+halfzsize);
color=color1;
}
public void moveto(int x,int y,int z){
int halfxsize=xsize/2;
int halfysize=ysize/2;
int halfzsize=zsize/2;
pt[0].moveto(x-halfxsize,y-halfysize,z-halfzsize);
pt[1].moveto(x+halfxsize,y-halfysize,z-halfzsize);
pt[2].moveto(x+halfxsize,y+halfysize,z-halfzsize);
pt[3].moveto(x-halfxsize,y+halfysize,z-halfzsize);
pt[4].moveto(x-halfxsize,y-halfysize,z+halfzsize);
pt[5].moveto(x+halfxsize,y-halfysize,z+halfzsize);
pt[6].moveto(x+halfxsize,y+halfysize,z+halfzsize);
pt[7].moveto(x-halfxsize,y+halfysize,z+halfzsize);
}
public void translate(int transx,int transy,int transz){
for(int i=0;i<8;i++){
pt[i].translate(transx,transy,transz);
}
}
public void rotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].rotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
}
public void rotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].rotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
}
public void rotatecossin(double cosx1,double cosy1,double cosz1,double sinx1,double siny1,double sinz1,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].rotatecossin(cosx1,cosy1,cosz1,sinx1,siny1,sinz1,centerx,centery,centerz);
}
}
public void addrotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].addrotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
}
public void addrotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].addrotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
}
public void transform_perspective(double horizon_dist,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].transform_perspective(horizon_dist,centerx,centery,centerz);
}
}
public void transform_negative_perspective(double horizon_dist,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].transform_negative_perspective(horizon_dist,centerx,centery,centerz);
}
}
public int getzpos(){
float sum=0.0f;
for(int i=0;i<8;i++){
sum+=pt[i].rz;
}
int zpos=(int)(0.125f*sum);
return zpos;
}
public void drawelement(Graphics g){
Color tempcolor=g.getColor();
g.setColor(color);
// draw the top square
drawLine(g,pt[0].rx,pt[0].ry,pt[1].rx,pt[1].ry,thick);
drawLine(g,pt[1].rx,pt[1].ry,pt[2].rx,pt[2].ry,thick);
drawLine(g,pt[2].rx,pt[2].ry,pt[3].rx,pt[3].ry,thick);
drawLine(g,pt[3].rx,pt[3].ry,pt[0].rx,pt[0].ry,thick);
// draw the bottom square
drawLine(g,pt[4].rx,pt[4].ry,pt[5].rx,pt[5].ry,thick);
drawLine(g,pt[5].rx,pt[5].ry,pt[6].rx,pt[6].ry,thick);
drawLine(g,pt[6].rx,pt[6].ry,pt[7].rx,pt[7].ry,thick);
drawLine(g,pt[7].rx,pt[7].ry,pt[4].rx,pt[4].ry,thick);
// draw the vertical lines
drawLine(g,pt[0].rx,pt[0].ry,pt[4].rx,pt[4].ry,thick);
drawLine(g,pt[1].rx,pt[1].ry,pt[5].rx,pt[5].ry,thick);
drawLine(g,pt[2].rx,pt[2].ry,pt[6].rx,pt[6].ry,thick);
drawLine(g,pt[3].rx,pt[3].ry,pt[7].rx,pt[7].ry,thick);
g.setColor(tempcolor);
}
public void drawElement(GraphicsB3D g){
Color tempcolor=g.getColor();
g.setColor(color);
// draw the top square
g.drawLine(pt[0].rx,pt[0].ry,pt[1].rx,pt[1].ry,thick);
g.drawLine(pt[1].rx,pt[1].ry,pt[2].rx,pt[2].ry,thick);
g.drawLine(pt[2].rx,pt[2].ry,pt[3].rx,pt[3].ry,thick);
g.drawLine(pt[3].rx,pt[3].ry,pt[0].rx,pt[0].ry,thick);
// draw the bottom square
g.drawLine(pt[4].rx,pt[4].ry,pt[5].rx,pt[5].ry,thick);
g.drawLine(pt[5].rx,pt[5].ry,pt[6].rx,pt[6].ry,thick);
g.drawLine(pt[6].rx,pt[6].ry,pt[7].rx,pt[7].ry,thick);
g.drawLine(pt[7].rx,pt[7].ry,pt[4].rx,pt[4].ry,thick);
// draw the vertical lines
g.drawLine(pt[0].rx,pt[0].ry,pt[4].rx,pt[4].ry,thick);
g.drawLine(pt[1].rx,pt[1].ry,pt[5].rx,pt[5].ry,thick);
g.drawLine(pt[2].rx,pt[2].ry,pt[6].rx,pt[6].ry,thick);
g.drawLine(pt[3].rx,pt[3].ry,pt[7].rx,pt[7].ry,thick);
g.setColor(tempcolor);
}
}
| 5,451 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Point3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/Point3D.java | /*******************************************************************************
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
public class Point3D {
public int x, y, z;
public int rx, ry, rz;
public Point3D(int x1, int y1, int z1) {
x = x1;
y = y1;
z = z1;
rx = x;
ry = y;
rz = z;
}
public void moveto(int x1, int y1, int z1) {
x = x1;
y = y1;
z = z1;
rx = x;
ry = y;
rz = z;
}
public void reset() {
rx = x;
ry = y;
rz = z;
}
public void translate(int transx, int transy, int transz) {
x += transx;
y += transy;
z += transz;
rx += transx;
ry += transy;
rz += transz;
}
public void rotatedeg(double degx1, double degy1, double degz1, int centerx, int centery, int centerz) {
double radx = Math.toRadians(degx1);
double rady = Math.toRadians(degy1);
double radz = Math.toRadians(degz1);
setrotation(radx, rady, radz, centerx, centery, centerz);
}
public void rotaterad(double radx1, double rady1, double radz1, int centerx, int centery, int centerz) {
setrotation(radx1, rady1, radz1, centerx, centery, centerz);
}
public void rotatecossin(double cosx1, double cosy1, double cosz1, double sinx1, double siny1, double sinz1,
int centerx, int centery, int centerz) {
setrotation(cosx1, cosy1, cosz1, sinx1, siny1, sinz1, centerx, centery, centerz);
}
public void addrotatedeg(double degx1, double degy1, double degz1, int centerx, int centery, int centerz) {
double radx = Math.toRadians(degx1);
double rady = Math.toRadians(degy1);
double radz = Math.toRadians(degz1);
addrotation(radx, rady, radz, centerx, centery, centerz);
}
public void addrotaterad(double radx1, double rady1, double radz1, int centerx, int centery, int centerz) {
addrotation(radx1, rady1, radz1, centerx, centery, centerz);
}
public void transform_perspective(double horizon_dist, int centerx, int centery, int centerz) {
if (horizon_dist > 0.0) {
double tempx = (double) (rx - centerx);
double tempy = (double) (ry - centery);
double tempz = (double) (rz - centerz);
double temphordist = (tempz + horizon_dist) / horizon_dist;
if (temphordist <= 0) {
tempx = 0;
tempy = 0;
} else {
tempx *= temphordist;
tempy *= temphordist;
}
rx = centerx + (int) tempx;
ry = centery + (int) tempy;
}
}
public void transform_negative_perspective(double horizon_dist, int centerx, int centery, int centerz) {
// here the horizon is in the foreground
if (horizon_dist > 0.0) {
double tempx = (double) (rx - centerx);
double tempy = (double) (ry - centery);
double tempz = (double) (centerz - rz);
double temphordist = (tempz + horizon_dist) / horizon_dist;
if (temphordist <= 0) {
tempx = 0;
tempy = 0;
} else {
tempx *= temphordist;
tempy *= temphordist;
}
rx = centerx + (int) tempx;
ry = centery + (int) tempy;
}
}
public void setrotation(double dx, double dy, double dz, int centerx, int centery, int centerz) {
// rotate about the x, y, and z axes in order
double tempx = (double) (x - centerx);
double tempy = (double) (y - centery);
double tempz = (double) (z - centerz);
if (dz != 0.0) {
double sinval = Math.sin(-dz);
double cosval = Math.cos(-dz);
double tempx1 = tempx * cosval - tempy * sinval;
double tempy1 = tempx * sinval + tempy * cosval;
tempx = tempx1;
tempy = tempy1;
}
if (dy != 0.0) {
double sinval = Math.sin(dy);
double cosval = Math.cos(dy);
double tempx1 = tempx * cosval + tempz * sinval;
double tempz1 = -tempx * sinval + tempz * cosval;
tempx = tempx1;
tempz = tempz1;
}
if (dx != 0.0) {
double sinval = Math.sin(dx);
double cosval = Math.cos(dx);
double tempy1 = tempy * cosval - tempz * sinval;
double tempz1 = tempy * sinval + tempz * cosval;
tempy = tempy1;
tempz = tempz1;
}
rx = centerx + (int) tempx;
ry = centery + (int) tempy;
rz = centerz + (int) tempz;
}
public void setrotation(double cosdx, double cosdy, double cosdz, double sindx, double sindy, double sindz,
int centerx, int centery, int centerz) {
// rotate about the x, y, and z axes in order
double tempx = (double) (x - centerx);
double tempy = (double) (y - centery);
double tempz = (double) (z - centerz);
double sinval,cosval,tempx1,tempy1,tempz1;
if (sindz != 0.0) {
sinval = sindz;
cosval = cosdz;
tempx1 = tempx * cosval - tempy * sinval;
tempy1 = tempx * sinval + tempy * cosval;
tempx = tempx1;
tempy = tempy1;
}
if (sindy != 0.0) {
sinval = sindy;
cosval = cosdy;
tempx1 = tempx * cosval + tempz * sinval;
tempz1 = -tempx * sinval + tempz * cosval;
tempx = tempx1;
tempz = tempz1;
}
if (sindx != 0.0) {
sinval = sindx;
cosval = cosdx;
tempy1 = tempy * cosval - tempz * sinval;
tempz1 = tempy * sinval + tempz * cosval;
tempy = tempy1;
tempz = tempz1;
}
rx = centerx + (int) tempx;
ry = centery + (int) tempy;
rz = centerz + (int) tempz;
}
public void addrotation(double dx, double dy, double dz, int centerx, int centery, int centerz) {
// rotate about the x, y, and z axes in order
double tempx = (double) (rx - centerx);
double tempy = (double) (ry - centery);
double tempz = (double) (rz - centerz);
if (dz != 0.0) {
double sinval = Math.sin(-dz);
double cosval = Math.cos(-dz);
double tempx1 = tempx * cosval - tempy * sinval;
double tempy1 = tempx * sinval + tempy * cosval;
tempx = tempx1;
tempy = tempy1;
}
if (dy != 0.0) {
double sinval = Math.sin(dy);
double cosval = Math.cos(dy);
double tempx1 = tempx * cosval + tempz * sinval;
double tempz1 = -tempx * sinval + tempz * cosval;
tempx = tempx1;
tempz = tempz1;
}
if (dx != 0.0) {
double sinval = Math.sin(dx);
double cosval = Math.cos(dx);
double tempy1 = tempy * cosval - tempz * sinval;
double tempz1 = tempy * sinval + tempz * cosval;
tempy = tempy1;
tempz = tempz1;
}
rx = centerx + (int) tempx;
ry = centery + (int) tempy;
rz = centerz + (int) tempz;
}
public boolean equals(Point3D p3d) {
return x == p3d.x && y == p3d.y && z == p3d.z
&& rx == p3d.rx && ry == p3d.ry && rz == p3d.rz;
}
}
| 6,579 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
ScatterPlot3DWindow.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/ScatterPlot3DWindow.java | /*******************************************************************************
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import ezcol.main.PluginStatic;
import java.awt.datatransfer.*;
import ij.*;
import ij.gui.*;
import ij.io.SaveDialog;
import ij.measure.ResultsTable;
import ij.process.*;
import ij.text.TextWindow;
@SuppressWarnings("serial")
public class ScatterPlot3DWindow extends ImageWindow
implements ActionListener, ClipboardOwner, MouseMotionListener, MouseListener {
private Button list, save, copy, editbutton, selbutton, seldbutton;
private Button rotrightbutton, rotleftbutton, rotupbutton, rotdownbutton, rotcounterbutton, rotclockbutton,
rotresetbutton;
// private Label coordinates;
private static String defaultDirectory = null;
private static String title;
public ScatterPlot3D p3;
private static ColorProcessor cp;
// EDIT: drag lock
private boolean rotLock = false, rawLock = false;
private Button rotLockButton, typeButton;
private ResultsTable rawRT;
private double rotx = -60, roty = 0, rotz = -45;
// EDIT: call Scatter3DPlot
public ScatterPlot3DWindow(String title1, String xLabel1, String yLabel1, String zLabel1, float[][] xValues1,
float[][] yValues1, float[][] zValues1) {
super(createImage(title1));
p3 = new ScatterPlot3D(xLabel1, yLabel1, zLabel1, xValues1, yValues1, zValues1);
}
public ScatterPlot3DWindow(String title1, String xLabel1, String yLabel1, String zLabel1, float[] xValues1,
float[] yValues1, float[] zValues1) {
super(createImage(title1));
p3 = new ScatterPlot3D(xLabel1, yLabel1, zLabel1, xValues1, yValues1, zValues1);
}
public ScatterPlot3DWindow(String title1, String xLabel1, String yLabel1, String zLabel1, float[] xValues1,
float[] yValues1, float[] zValues1, int shape) {
super(createImage(title1));
p3 = new ScatterPlot3D(xLabel1, yLabel1, zLabel1, xValues1, yValues1, zValues1, shape);
}
public ScatterPlot3DWindow(String title1, String xLabel1, String yLabel1, String zLabel1, float[][] xValues1,
float[][] yValues1, float[][] zValues1, int[] shapes) {
super(createImage(title1));
p3 = new ScatterPlot3D(xLabel1, yLabel1, zLabel1, xValues1, yValues1, zValues1, shapes);
}
public ScatterPlot3DWindow(String title1, String xLabel1, String yLabel1, String zLabel1, float[][] xValues1,
float[][] yValues1, float[][] zValues1, int shape) {
super(createImage(title1));
int[] shapes = new int[zValues1.length];
for (int i = 0; i < shapes.length; i++)
shapes[i] = shape;
p3 = new ScatterPlot3D(xLabel1, yLabel1, zLabel1, xValues1, yValues1, zValues1, shapes);
}
public ScatterPlot3DWindow(String title1, String xLabel1, String yLabel1, String zLabel1, float[][] xValues1,
float[][] yValues1, float[][] zValues1, int shape, String[] labels) {
super(createImage(title1));
int[] shapes = new int[zValues1.length];
for (int i = 0; i < shapes.length; i++)
shapes[i] = shape;
p3 = new ScatterPlot3D(xLabel1, yLabel1, zLabel1, xValues1, yValues1, zValues1, shapes, labels);
}
public ScatterPlot3DWindow(String title1, String xLabel1, String yLabel1, String zLabel1, float[][] xValues1,
float[][] yValues1, float[][] zValues1, int shape, float[] customColors, float[] customScales,
Color[] colorScales) {
super(createImage(title1));
int[] shapes = new int[zValues1.length];
for (int i = 0; i < shapes.length; i++)
shapes[i] = shape;
p3 = new ScatterPlot3D(xLabel1, yLabel1, zLabel1, xValues1, yValues1, zValues1, shapes, customColors,
customScales, colorScales);
}
public ScatterPlot3DWindow(String title1, ScatterPlot3D p3) {
super(createImage(title1));
this.p3 = p3;
}
public ScatterPlot3DWindow(ImagePlus imp, ScatterPlot3D p3) {
// turns the passed ImagePlus into a plot window
// used for bioformats which wants to make the window for me
super(imp);
int width = ScatterPlot3D.WIDTH + ScatterPlot3D.LEFT_MARGIN + ScatterPlot3D.RIGHT_MARGIN;
int height = ScatterPlot3D.HEIGHT + ScatterPlot3D.TOP_MARGIN + ScatterPlot3D.BOTTOM_MARGIN;
int[] temp = new int[width * height];
for (int i = 0; i < width * height; i++) {
temp[i] = 0xffffffff;
}
cp = new ColorProcessor(width, height, temp);
imp.setProcessor(cp);
// cp=(ColorProcessor)this.imp.getProcessor();
this.p3 = p3;
}
static ImagePlus createImage(String title1) {
int width = ScatterPlot3D.WIDTH + ScatterPlot3D.LEFT_MARGIN + ScatterPlot3D.RIGHT_MARGIN;
int height = ScatterPlot3D.HEIGHT + ScatterPlot3D.TOP_MARGIN + ScatterPlot3D.BOTTOM_MARGIN;
int[] temp = new int[width * height];
for (int i = 0; i < width * height; i++) {
temp[i] = 0xffffffff;
}
cp = new ColorProcessor(width, height, temp);
title = title1;
return new ImagePlus(title, cp);
}
/** Sets the x-axis and y-axis range. */
public void setLimits(double xMin1, double xMax1, double yMin1, double yMax1, double zMin1, double zMax1) {
p3.setLimits(xMin1, xMax1, yMin1, yMax1, zMin1, zMax1);
updatePlot();
}
public void setLimits(float[] limits) {
p3.setLimits(limits);
updatePlot();
}
/** Sets the x-axis and y-axis range. */
public void setLogAxes(boolean logx1, boolean logy1, boolean logz1) {
p3.setLogAxes(logx1, logy1, logz1);
updatePlot();
}
public void autoscale() {
p3.autoscale();
updatePlot();
}
public void xautoscale() {
p3.xautoscale();
updatePlot();
}
public void yautoscale() {
p3.yautoscale();
updatePlot();
}
public void zautoscale() {
p3.zautoscale();
updatePlot();
}
public void updateSeries(float[] xValues1, float[] yValues1, float[] zValues1, int series, boolean rescale) {
p3.updateSeries(xValues1, yValues1, zValues1, series, rescale);
updatePlot();
}
public void updateSeries(float[] zValues1, int series, boolean rescale) {
p3.updateSeries(zValues1, series, rescale);
updatePlot();
}
public void deleteSeries(int series, boolean rescale) {
p3.deleteSeries(series, rescale);
updatePlot();
}
public void addPoints(float[] xValues1, float[] yValues1, float[] zValues1, boolean rescale) {
p3.addPoints(xValues1, yValues1, zValues1, rescale);
updatePlot();
}
public void addPoints(float[] zValues1, boolean rescale, int startxy) {
p3.addPoints(zValues1, rescale, startxy);
updatePlot();
}
public void updatePlot() {
cp = p3.getProcessor();
imp.setProcessor(null, cp);
imp.updateAndDraw();
}
/** Displays the plot. */
public void draw() {
Panel buttons = new Panel();
buttons.setLayout(new FlowLayout(FlowLayout.RIGHT));
list = new Button(" List ");
list.addActionListener(this);
buttons.add(list);
save = new Button("Save...");
save.addActionListener(this);
buttons.add(save);
copy = new Button("Copy...");
copy.addActionListener(this);
buttons.add(copy);
editbutton = new Button("Edit...");
editbutton.addActionListener(this);
buttons.add(editbutton);
selbutton = new Button("Select+");
selbutton.addActionListener(this);
buttons.add(selbutton);
seldbutton = new Button("Select-");
seldbutton.addActionListener(this);
buttons.add(seldbutton);
typeButton = new Button("Proc");
typeButton.addActionListener(this);
buttons.add(typeButton);
rotLockButton = new Button("Dynamic");
rotLockButton.setForeground(Color.RED);
rotLockButton.addActionListener(this);
buttons.add(rotLockButton);
Panel rotbuttons = new Panel();
rotbuttons.setLayout(new FlowLayout(FlowLayout.RIGHT));
rotrightbutton = new Button(">");
rotrightbutton.addActionListener(this);
rotbuttons.add(rotrightbutton);
rotleftbutton = new Button("<");
rotleftbutton.addActionListener(this);
rotbuttons.add(rotleftbutton);
rotupbutton = new Button("^");
rotupbutton.addActionListener(this);
rotbuttons.add(rotupbutton);
rotdownbutton = new Button("v");
rotdownbutton.addActionListener(this);
rotbuttons.add(rotdownbutton);
rotclockbutton = new Button("Clock+");
rotclockbutton.addActionListener(this);
rotbuttons.add(rotclockbutton);
rotcounterbutton = new Button("Clock-");
rotcounterbutton.addActionListener(this);
rotbuttons.add(rotcounterbutton);
rotresetbutton = new Button("Reset Rot.");
rotresetbutton.addActionListener(this);
rotbuttons.add(rotresetbutton);
// coordinates = new Label("X=12345678, Y=12345678");
// coordinates.setFont(new Font("Monospaced", Font.PLAIN, 12));
// buttons.add(coordinates);
add(buttons);
add(rotbuttons);
pack();
// coordinates.setText("");
getCanvas().addMouseMotionListener(this);
getCanvas().addMouseListener(this);
updatePlot();
}
/**
* Updates the graph X and Y values when the mouse is moved. Overrides
* mouseMoved() in ImageWindow.
*
* @see ij.gui.ImageWindow#mouseMoved
*/
public void mouseMoved(int x, int y) {
super.mouseMoved(x, y);
/*
* float[] temp=getPlotCoords(x,y); coordinates.setText("X="+temp[0]+
* ", Y="+temp[1]);
*/
}
void showList() {
if (rawLock && rawRT != null) {
rawRT.show(title + " Raw Values");
return;
}
if (p3.isCustomColor()) {
ResultsTable rt = new ResultsTable();
float[][] tempxvals = p3.getXValues();
float[][] tempyvals = p3.getYValues();
float[][] tempzvals = p3.getZValues();
float[] tempColors = p3.getColorValues();
for (int i = 0; i < tempColors.length; i++) {
rt.incrementCounter();
rt.addValue("Channel 1 FT", tempxvals[i][0]);
rt.addValue("Channel 2 FT", tempyvals[i][0]);
rt.addValue("Channel 3 FT", tempzvals[i][0]);
rt.addValue("Metric ", tempColors[i]);
}
rt.show(title + " Plot Values");
return;
}
StringBuffer sb = new StringBuffer();
StringBuffer headings = new StringBuffer();
int maxpts = p3.getmaxpts();
int nser = p3.getNSeries();
float[][] tempxvals = p3.getXValues();
float[][] tempyvals = p3.getYValues();
float[][] tempzvals = p3.getZValues();
for (int i = 0; i < nser; i++) {
headings.append("x" + i + "\ty" + i + "\tz" + i + "\t");
}
for (int i = 0; i < maxpts; i++) {
for (int j = 0; j < nser; j++) {
sb.append("" + tempxvals[j][i] + "\t" + tempyvals[j][i] + "\t" + tempzvals[j][i] + "\t");
}
sb.append("\n");
}
new TextWindow(title + " Plot Values", headings.toString(), sb.toString(), 200, 400);
}
void saveAsText() {
/*
* FileDialog fd = new FileDialog(this, "Save as Text...",
* FileDialog.SAVE); if (defaultDirectory != null)
* fd.setDirectory(defaultDirectory); fd.show(); String name =
* fd.getFile(); String directory = fd.getDirectory(); defaultDirectory
* = directory; fd.dispose(); PrintWriter pw = null; try {
* FileOutputStream fos = new FileOutputStream(directory + name);
* BufferedOutputStream bos = new BufferedOutputStream(fos); pw = new
* PrintWriter(bos); } catch (IOException e) { IJ.error("" + e); return;
* } IJ.wait(250); // give system time to redraw ImageJ window
* IJ.showStatus("Saving plot values...");
*/
SaveDialog sd = new SaveDialog("Save as Text", "Values", Prefs.defaultResultsExtension());
String name = sd.getFileName();
if (name == null)
return;
String directory = sd.getDirectory();
IJ.wait(250); // give system time to redraw ImageJ window
IJ.showStatus("Saving plot values...");
if (rawLock && rawRT != null) {
try {
rawRT.saveAs(directory + name);
} catch (IOException e) {
IJ.error("" + e);
}
} else if (p3.isCustomColor()) {
ResultsTable rt = new ResultsTable();
float[][] tempxvals = p3.getXValues();
float[][] tempyvals = p3.getYValues();
float[][] tempzvals = p3.getZValues();
float[] tempColors = p3.getColorValues();
for (int i = 0; i < tempColors.length; i++) {
rt.incrementCounter();
rt.addValue("Channel 1 FT", tempxvals[i][0]);
rt.addValue("Channel 2 FT", tempyvals[i][0]);
rt.addValue("Channel 3 FT", tempzvals[i][0]);
rt.addValue("Metric ", tempColors[i]);
}
try {
rt.saveAs(directory + name);
} catch (IOException e) {
IJ.error("" + e);
return;
}
} else {
PrintWriter pw = null;
try {
FileOutputStream fos = new FileOutputStream(directory + name);
BufferedOutputStream bos = new BufferedOutputStream(fos);
pw = new PrintWriter(bos);
} catch (IOException e) {
IJ.error("" + e);
return;
}
int maxpts = p3.getmaxpts();
int nser = p3.getNSeries();
float[][] xValues = p3.getXValues();
float[][] yValues = p3.getYValues();
float[][] zValues = p3.getZValues();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < maxpts; i++) {
for (int j = 0; j < nser; j++) {
sb.append("" + xValues[j][i] + "\t" + yValues[j][i] + "\t" + zValues[j][i] + "\t");
pw.println(sb.toString());
}
pw.println("\n");
}
pw.close();
}
}
/**
* SaveAsObject is not currently available
*/
/*
* void saveAsObject() { FileDialog fd = new FileDialog(this,
* "Save as Plot Object...", FileDialog.SAVE); if (defaultDirectory != null)
* fd.setDirectory(defaultDirectory); String temptitle = getTitle(); if
* (!temptitle.endsWith(".pw2")) { temptitle += ".pw2"; }
* fd.setFile(temptitle); //fd.setFilenameFilter( new FilenameFilter(){
* public boolean //accept(File dir,String name){ if(name.endsWith(".pw")){
* return true; //} else { return false; } } } ); fd.show(); String name =
* fd.getFile(); String directory = fd.getDirectory(); defaultDirectory =
* directory; fd.dispose(); if (name == null || name == "" || directory ==
* null || directory == "") return; imp.setTitle(name);
* saveAsObject(directory + File.separator + name); }
*/
/**
* SaveAsObject is not currently available
*
* @param filename
*/
/*
* public void saveAsObject(String filename) { p3.saveplot2file(filename); }
*/
void copyToClipboard() {
Clipboard systemClipboard = null;
try {
systemClipboard = getToolkit().getSystemClipboard();
} catch (Exception e) {
systemClipboard = null;
}
if (systemClipboard == null) {
IJ.error("Unable to copy to Clipboard.");
return;
}
IJ.showStatus("Copying plot values...");
CharArrayWriter aw = new CharArrayWriter();
PrintWriter pw = new PrintWriter(aw); // uses platform's line
String text = ""; // termination characters
if (rawLock && rawRT != null) {
if (!Prefs.dontSaveHeaders) {
String headings = rawRT.getColumnHeadings();
pw.println(headings);
}
for (int i = 0; i < rawRT.size(); i++)
pw.println(rawRT.getRowAsString(i));
text = aw.toString();
}
if (p3.isCustomColor()) {
ResultsTable rt = new ResultsTable();
float[][] tempxvals = p3.getXValues();
float[][] tempyvals = p3.getYValues();
float[][] tempzvals = p3.getZValues();
float[] tempColors = p3.getColorValues();
for (int i = 0; i < tempColors.length; i++) {
rt.incrementCounter();
rt.addValue("Channel 1 FT", tempxvals[i][0]);
rt.addValue("Channel 2 FT", tempyvals[i][0]);
rt.addValue("Channel 3 FT", tempzvals[i][0]);
rt.addValue("Metric ", tempColors[i]);
}
if (!Prefs.dontSaveHeaders) {
String headings = rt.getColumnHeadings();
pw.println(headings);
}
for (int i = 0; i < rt.size(); i++)
pw.println(rt.getRowAsString(i));
text = aw.toString();
} else {
StringBuffer sb = new StringBuffer();
int maxpts = p3.getmaxpts();
int nser = p3.getNSeries();
float[][] xValues = p3.getXValues();
float[][] yValues = p3.getYValues();
float[][] zValues = p3.getZValues();
for (int i = 0; i < maxpts; i++) {
for (int j = 0; j < nser; j++) {
sb.append("" + xValues[j][i] + "\t" + yValues[j][i] + "\t" + zValues[j][i] + "\t\n");
}
sb.append("\n");
text = sb.toString();
}
}
StringSelection contents = new StringSelection(text);
systemClipboard.setContents(contents, this);
IJ.showStatus(text.length() + " characters copied to Clipboard");
}
void editPlot() {
GenericDialog gd = new GenericDialog("Plot Options");
float[] limits = p3.getLimits();
gd.addNumericField("x min", limits[0], 5, 10, null);
gd.addNumericField("x max", limits[1], 5, 10, null);
gd.addNumericField("y min", limits[2], 5, 10, null);
gd.addNumericField("y max", limits[3], 5, 10, null);
gd.addNumericField("z min", limits[4], 5, 10, null);
gd.addNumericField("z max", limits[5], 5, 10, null);
boolean[] logs = p3.getLogAxes();
gd.addCheckbox("Log x?", logs[0]);
gd.addCheckbox("Log y?", logs[1]);
gd.addCheckbox("Log z?", logs[2]);
gd.addStringField("x label", p3.getxLabel());
gd.addStringField("y label", p3.getyLabel());
gd.addStringField("z label", p3.getzLabel());
boolean delsel = false;
gd.addCheckbox("Delete Selected", delsel);
boolean ascalex = false;
gd.addCheckbox("AutoScale x", ascalex);
boolean ascaley = false;
gd.addCheckbox("AutoScale y", ascalex);
boolean ascalez = false;
gd.addCheckbox("AutoScale z", ascalez);
gd.showDialog();
if (gd.wasCanceled()) {
return;
}
limits[0] = (float) gd.getNextNumber();
limits[1] = (float) gd.getNextNumber();
limits[2] = (float) gd.getNextNumber();
limits[3] = (float) gd.getNextNumber();
limits[4] = (float) gd.getNextNumber();
limits[5] = (float) gd.getNextNumber();
p3.setLimits(limits);
logs[0] = gd.getNextBoolean();
logs[1] = gd.getNextBoolean();
logs[2] = gd.getNextBoolean();
p3.setLogAxes(logs[0], logs[1], logs[2]);
p3.setxLabel(gd.getNextString());
p3.setyLabel(gd.getNextString());
p3.setzLabel(gd.getNextString());
delsel = gd.getNextBoolean();
ascalex = gd.getNextBoolean();
ascaley = gd.getNextBoolean();
ascalez = gd.getNextBoolean();
if (delsel) {
delsel = false;
p3.deleteSeries(p3.getSelected(), false);
}
if (ascalex) {
ascalex = false;
p3.xautoscale();
}
if (ascaley) {
ascaley = false;
p3.yautoscale();
}
if (ascalez) {
ascalez = false;
p3.zautoscale();
}
updatePlot();
}
public void lostOwnership(Clipboard clipboard, Transferable contents) {
}
public void actionPerformed(ActionEvent e) {
Object b = e.getSource();
if (b == list) {
showList();
} else {
if (b == save) {
saveAsText();
/*
* GenericDialog gd = new GenericDialog("Save Options");
* String[] savechoice = { "Text", "Binary", "Plot Object" };
* gd.addChoice("File Type?", savechoice, savechoice[2]); int
* saveseries = 0; gd.addNumericField(
* "Save Series # (for binary)", saveseries, 0); String[]
* binarytypechoice = { "Float", "Integer", "Short" };
* gd.addChoice("Binary File Type?", binarytypechoice,
* binarytypechoice[0]); gd.showDialog(); if (gd.wasCanceled())
* { return; } int choiceindex = gd.getNextChoiceIndex(); if
* (choiceindex == 0) { saveAsText(); } else { saveAsObject(); }
*/
} else {
if (b == editbutton) {
editPlot();
} else {
if (b == copy) {
copyToClipboard();
} else {
if (b == selbutton) {
// p3.selectSeries(p3.getSelected() + 1);
p3.setCurrSeries(p3.getCurrSeries() + 1);
setCurrLabel();
updatePlot();
} else {
if (b == seldbutton) {
// p3.selectSeries(p3.getSelected() - 1);
p3.setCurrSeries(p3.getCurrSeries() - 1);
setCurrLabel();
updatePlot();
} else {
if (b == typeButton) {
rawLock = !rawLock;
if (rawLock) {
typeButton.setLabel("Raw");
typeButton.setForeground(Color.RED);
} else {
typeButton.setLabel("Proc");
typeButton.setForeground(Color.BLACK);
}
} else {
if (b == rotLockButton) {
rotLock = !rotLock;
if (rotLock) {
rotLockButton.setLabel("Locked");
rotLockButton.setForeground(Color.BLACK);
} else {
rotLockButton.setLabel("Dynamic");
rotLockButton.setForeground(Color.RED);
}
} else {
if (b == rotrightbutton) {
p3.setrotation(p3.getrotation()[0], p3.getrotation()[1],
p3.getrotation()[2] + 10.0);
updatePlot();
} else {
if (b == rotleftbutton) {
p3.setrotation(p3.getrotation()[0], p3.getrotation()[1],
p3.getrotation()[2] - 10.0);
updatePlot();
} else {
if (b == rotupbutton) {
p3.setrotation(p3.getrotation()[0] - 10.0, p3.getrotation()[1],
p3.getrotation()[2]);
updatePlot();
} else {
if (b == rotdownbutton) {
p3.setrotation(p3.getrotation()[0] + 10.0, p3.getrotation()[1],
p3.getrotation()[2]);
updatePlot();
} else {
if (b == rotclockbutton) {
p3.setrotation(p3.getrotation()[0],
p3.getrotation()[1] - 10.0, p3.getrotation()[2]);
updatePlot();
} else {
if (b == rotcounterbutton) {
p3.setrotation(p3.getrotation()[0],
p3.getrotation()[1] + 10.0,
p3.getrotation()[2]);
updatePlot();
} else {
if (b == rotresetbutton) {
p3.setrotation(rotx, roty, rotz);
updatePlot();
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
}
public void selectSeries(int series) {
p3.selectSeries(series);
updatePlot();
}
public float[][] getXValues() {
return p3.getXValues();
}
public float[] getXValues(int series) {
return p3.getXValues(series);
}
public float[][] getYValues() {
return p3.getYValues();
}
public float[] getYValues(int series) {
return p3.getYValues(series);
}
public float[][] getZValues() {
return p3.getZValues();
}
public float[] getZValues(int series) {
return p3.getZValues(series);
}
public String getPlotTitle() {
return imp.getTitle();
}
public String getxLabel() {
return p3.getxLabel();
}
public String getyLabel() {
return p3.getyLabel();
}
public String getzLabel() {
return p3.getzLabel();
}
public int[] getNpts() {
return p3.getNpts();
}
public int getNSeries() {
return p3.getNSeries();
}
public float[] getLimits() {
return p3.getLimits();
}
public int[] getShapes() {
return p3.getShapes();
}
public int[] getColors() {
return p3.getColors();
}
public ScatterPlot3D getPlot() {
return p3;
}
// EDIT: Implement drag and lock
private int xdiff, ydiff, xStart, yStart;
private int toolID = Toolbar.HAND;
@Override
public void mouseDragged(MouseEvent e) {
// TODO Auto-generated method stub
if (!rotLock) {
int xAct = e.getX();
int yAct = e.getY();
xdiff = xAct - xStart;
ydiff = yAct - yStart;
xStart = xAct;
yStart = yAct;
p3.setrotation(p3.getrotation()[0] - ydiff / 2.0, p3.getrotation()[1], p3.getrotation()[2] + xdiff / 2.0);
updatePlot();
}
}
@Override
public void mouseMoved(MouseEvent e) {
// TODO Auto-generated method stub
}
public void mouseReleased(MouseEvent e) {
if (!rotLock && toolID != Toolbar.HAND) {
Toolbar.getInstance().setTool(toolID);
}
}
@Override
public void mouseClicked(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// TODO Auto-generated method stub
if (!rotLock) {
toolID = Toolbar.getToolId();
if (toolID != Toolbar.HAND) {
Toolbar.getInstance().setTool(Toolbar.HAND);
}
xStart = e.getX();
yStart = e.getY();
xdiff = 0;
ydiff = 0;
}
}
@Override
public void mouseEntered(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
public void setCurrLabel() {
if (p3.isLabeled()) {
if (p3.getCurrSeries() == p3.getNSeries())
imp.setProperty("Label", "All Data");
else
imp.setProperty("Label", p3.getLabel(p3.getCurrSeries()));
} else
imp.setProperty("Label", null);
}
public void setDefaultRotation(int rotx, int roty, int rotz) {
this.rotx = rotx;
this.roty = roty;
this.rotz = rotz;
if (p3 != null)
p3.setrotation(rotx, roty, rotz);
}
public void setRawResultsTable(ResultsTable rawRT) {
this.rawRT = rawRT;
}
public static void setPlotTitle(String title) {
ScatterPlot3DWindow.title = title;
}
} | 24,793 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
ScatterPlot3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/ScatterPlot3D.java | /*******************************************************************************
* EDIT: This plugin is modified by Huanjie Sheng from Plot3D by Jay Unruh.
* EDIT: This version will take in zValues with the same dimension as x and y
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.text.DecimalFormat;
import ij.process.*;
public class ScatterPlot3D {
// private Label coordinates;
protected float[][] xValues;
protected float[][] yValues;
protected float[][] zValues;
// npts[i] denote the number of pixel of j-th series.
// This is used to coordinate the number of pixel plotted in case of
// dimension mismatch
protected int[] npts;
protected float xMin, xMax, yMin, yMax, zMin, zMax, xScale, yScale, zScale;
protected float logxmin, logymin, logxscale, logyscale, logxmax, logymax, logzmin, logzmax, logzscale;
protected int maxpts, nseries;
protected int selected;
protected double rotx, roty, rotz;
protected int[] shapes, colors;
protected String xLabel, yLabel, zLabel;
protected boolean logx, logy, logz;
public static final int WIDTH = 250;
public static final int HEIGHT = 150;
public static final int TICK_LENGTH = 3; // length of ticks
public final Color gridColor = new Color(0xc0c0c0); // light gray
public static final int LEFT_MARGIN = 125;
public static final int RIGHT_MARGIN = 125;
public static final int TOP_MARGIN = 175;
public static final int BOTTOM_MARGIN = 175;
public static final int shapesize = 5;
// EDIT:
protected int currSeries;
protected String[] labels;
// the same length as nseries, customized colors for nseries
protected float[] customColors;
// denote color ladder
protected float[] customScales;
protected Color[] colorScales;
protected Renderer jr;
protected boolean plotChanged = true, plotRotated = true;
public ScatterPlot3D() {
} // empty constructor for subclasses
public ScatterPlot3D(String xLabel1, String yLabel1, String zLabel1, float[][] xValues1, float[][] yValues1,
float[][] zValues1) {
xValues = xValues1;
yValues = yValues1;
zValues = zValues1;
xLabel = xLabel1;
yLabel = yLabel1;
zLabel = zLabel1;
nseries = zValues.length;
npts = new int[nseries];
maxpts = zValues[0].length;
for (int i = 0; i < nseries; i++) {
npts[i] = zValues[i].length;
if (maxpts < npts[i])
maxpts = npts[i];
}
float[] temp = findminmax(xValues, npts);
xMin = temp[0];
xMax = temp[1];
temp = findminmax(yValues, npts);
yMin = temp[0];
yMax = temp[1];
temp = findminmax(zValues, npts);
zMin = temp[0];
zMax = temp[1];
logx = false;
logy = false;
logz = false;
shapes = new int[nseries];
colors = new int[nseries];
for (int i = 0; i < nseries; i++) {
colors[i] = i;
}
selected = -1;
rotx = -60.0;
roty = 0.0;
rotz = -45.0;
}
public ScatterPlot3D(String xLabel1, String yLabel1, String zLabel1, float[] xValues1, float[] yValues1,
float[] zValues1) {
xValues = new float[1][zValues1.length];
for (int i = 0; i < zValues1.length; i++) {
xValues[0][i] = xValues1[i];
}
yValues = new float[1][zValues1.length];
for (int i = 0; i < zValues1.length; i++) {
yValues[0][i] = yValues1[i];
}
zValues = new float[1][zValues1.length];
for (int i = 0; i < zValues1.length; i++) {
zValues[0][i] = zValues1[i];
}
xLabel = xLabel1;
yLabel = yLabel1;
zLabel = zLabel1;
maxpts = zValues1.length;
npts = new int[1];
npts[0] = maxpts;
nseries = 1;
float[] temp = findminmax(xValues, npts);
xMin = temp[0];
xMax = temp[1];
temp = findminmax(yValues, npts);
yMin = temp[0];
yMax = temp[1];
temp = findminmax(zValues, npts);
zMin = temp[0];
zMax = temp[1];
logx = false;
logy = false;
logz = false;
shapes = new int[nseries];
colors = new int[nseries];
for (int i = 0; i < nseries; i++) {
colors[i] = i;
}
selected = -1;
rotx = -60.0;
roty = 0.0;
rotz = -45.0;
}
public ScatterPlot3D(String xLabel1, String yLabel1, String zLabel1, float[] zValues1, int startxy) {
xValues = new float[1][zValues1.length];
for (int i = 0; i < zValues1.length; i++) {
xValues[0][i] = (float) (i + startxy);
}
yValues = new float[1][zValues1.length];
for (int i = 0; i < zValues1.length; i++) {
yValues[0][i] = (float) (i + startxy);
}
zValues = new float[1][zValues1.length];
for (int i = 0; i < zValues1.length; i++) {
zValues[0][i] = zValues1[i];
}
xLabel = xLabel1;
yLabel = yLabel1;
zLabel = zLabel1;
maxpts = zValues1.length;
npts = new int[1];
npts[0] = maxpts;
nseries = 1;
float[] temp = findminmax(xValues, npts);
xMin = temp[0];
xMax = temp[1];
temp = findminmax(yValues, npts);
yMin = temp[0];
yMax = temp[1];
temp = findminmax(zValues, npts);
zMin = temp[0];
zMax = temp[1];
logx = false;
logy = false;
logz = false;
shapes = new int[nseries];
colors = new int[nseries];
for (int i = 0; i < nseries; i++) {
colors[i] = i;
}
selected = -1;
rotx = -60.0;
roty = 0.0;
rotz = -45.0;
}
public ScatterPlot3D(String xLabel1, String yLabel1, String zLabel1, float[][] zValues1, int startxy) {
zValues = zValues1;
xLabel = xLabel1;
yLabel = yLabel1;
zLabel = zLabel1;
nseries = zValues.length;
npts = new int[nseries];
maxpts = zValues[0].length;
for (int i = 0; i < nseries; i++) {
npts[i] = zValues[i].length;
if (maxpts < npts[i])
maxpts = npts[i];
}
xValues = new float[nseries][maxpts];
yValues = new float[nseries][maxpts];
for (int i = 0; i < nseries; i++) {
for (int j = 0; j < npts[i]; j++) {
xValues[i][j] = (float) (j + startxy);
}
for (int j = 0; j < npts[i]; j++) {
yValues[i][j] = (float) (j + startxy);
}
}
float[] temp = findminmax(xValues, npts);
xMin = temp[0];
xMax = temp[1];
temp = findminmax(yValues, npts);
yMin = temp[0];
yMax = temp[1];
temp = findminmax(zValues, npts);
zMin = temp[0];
zMax = temp[1];
logx = false;
logy = false;
logz = false;
shapes = new int[nseries];
colors = new int[nseries];
for (int i = 0; i < nseries; i++) {
colors[i] = i;
}
selected = -1;
rotx = -60.0;
roty = 0.0;
rotz = -45.0;
}
public ScatterPlot3D(String xLabel1, String yLabel1, String zLabel1, float[] xValues1, float[] yValues1,
float[] zValues1, int shape) {
this(xLabel1, yLabel1, zLabel1, xValues1, yValues1, zValues1);
shapes[0] = shape;
}
public ScatterPlot3D(String xLabel1, String yLabel1, String zLabel1, float[][] xValues1, float[][] yValues1,
float[][] zValues1, int[] shapes) {
this(xLabel1, yLabel1, zLabel1, xValues1, yValues1, zValues1);
this.shapes = shapes;
}
public ScatterPlot3D(String xLabel1, String yLabel1, String zLabel1, float[][] xValues1, float[][] yValues1,
float[][] zValues1, int[] shapes, String[] labels) {
this(xLabel1, yLabel1, zLabel1, xValues1, yValues1, zValues1, shapes);
this.labels = labels;
}
public ScatterPlot3D(String xLabel1, String yLabel1, String zLabel1, float[][] xValues1, float[][] yValues1,
float[][] zValues1, int[] shapes, float[] customColors, float[] customScales, Color[] colorScales) {
this(xLabel1, yLabel1, zLabel1, xValues1, yValues1, zValues1, shapes);
this.customColors = customColors;
this.customScales = customScales;
this.colorScales = colorScales;
this.currSeries = nseries;
}
/*****
* File saving is currently unavailable. Might be released later
*/
/*
* public Scatter3DPlot(InputStream is) { init_from_is(is); }
*
* public Scatter3DPlot(String filename) { try { InputStream is = new
* BufferedInputStream(new FileInputStream(filename)); init_from_is(is);
* is.close(); } catch (IOException e) { return; } }
*
* private void init_from_is(InputStream is) { jdataio jdio = new jdataio();
* jdio.readstring(is); // read the label jdio.readintelint(is); // now the
* identifier xLabel = jdio.readstring(is); yLabel = jdio.readstring(is);
* zLabel = jdio.readstring(is); nseries = jdio.readintelint(is); maxpts =
* jdio.readintelint(is); npts = new int[nseries]; xValues = new
* float[nseries][maxpts]; yValues = new float[nseries][maxpts]; zValues =
* new float[nseries][maxpts]; shapes = new int[nseries]; colors = new
* int[nseries]; xMin = jdio.readintelfloat(is); xMax =
* jdio.readintelfloat(is); yMin = jdio.readintelfloat(is); yMax =
* jdio.readintelfloat(is); zMin = jdio.readintelfloat(is); zMax =
* jdio.readintelfloat(is); logx = jdio.readintelint(is) == 1; logy =
* jdio.readintelint(is) == 1; logz = jdio.readintelint(is) == 1; for (int l
* = 0; l < nseries; l++) { npts[l] = jdio.readintelint(is); shapes[l] =
* jdio.readintelint(is); colors[l] = jdio.readintelint(is);
* jdio.readintelfloatfile(is, npts[l], xValues[l]);
* jdio.readintelfloatfile(is, npts[l], yValues[l]);
* jdio.readintelfloatfile(is, npts[l], zValues[l]); // y // values }
* selected = -1; rotx = -60.0; roty = 0.0; rotz = -45.0; }
*
* public static boolean is_this(String filename) { int temp = -1; try {
* InputStream is = new BufferedInputStream(new FileInputStream(filename));
* jdataio jdio = new jdataio(); jdio.readstring(is); // read the label temp
* = jdio.readintelint(is); // now the identifier is.close(); } catch
* (IOException e) { return false; } if (temp == 1) return true; else return
* false; }
*/
protected float[] findminmax(float[][] arr, int[] npts1) {
float[] temp = new float[2];
temp[0] = arr[0][0];
temp[1] = arr[0][0];
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < npts1[i]; j++) {
if (arr[i][j] < temp[0]) {
temp[0] = arr[i][j];
}
if (arr[i][j] > temp[1]) {
temp[1] = arr[i][j];
}
}
}
return temp;
}
protected float findmingt0(float[][] arr, int[] npts1, float max) {
float temp = max;
if (max <= 0.0f) {
return 0.0f;
}
for (int i = 0; i < arr.length; i++) {
for (int j = 0; j < npts1[i]; j++) {
if (arr[i][j] < temp && arr[i][j] > 0.0f) {
temp = arr[i][j];
}
}
}
return temp;
}
/** Sets the x-axis and y-axis range. */
public void setLimits(double xMin1, double xMax1, double yMin1, double yMax1, double zMin1, double zMax1) {
xMin = (float) xMin1;
xMax = (float) xMax1;
yMin = (float) yMin1;
yMax = (float) yMax1;
zMin = (float) zMin1;
zMax = (float) zMax1;
plotChanged = true;
}
public void setLimits(float[] limits) {
xMin = limits[0];
xMax = limits[1];
yMin = limits[2];
yMax = limits[3];
zMin = limits[4];
zMax = limits[5];
plotChanged = true;
}
/** Sets the x-axis and y-axis range. */
public void setLogAxes(boolean logx1, boolean logy1, boolean logz1) {
logx = logx1;
logy = logy1;
logz = logz1;
plotChanged = true;
}
public void autoscale() {
float[] temp = findminmax(xValues, npts);
xMin = temp[0];
xMax = temp[1];
temp = findminmax(yValues, npts);
yMin = temp[0];
yMax = temp[1];
temp = findminmax(zValues, npts);
zMin = temp[0];
zMax = temp[1];
}
public void xautoscale() {
float[] temp = findminmax(xValues, npts);
xMin = temp[0];
xMax = temp[1];
}
public void yautoscale() {
float[] temp = findminmax(yValues, npts);
yMin = temp[0];
yMax = temp[1];
}
public void zautoscale() {
float[] temp = findminmax(zValues, npts);
zMin = temp[0];
zMax = temp[1];
}
public void setrotation(double xrot1, double yrot1, double zrot1) {
rotx = xrot1;
roty = yrot1;
rotz = zrot1;
plotRotated = true;
}
public void setrotation(double[] rotation) {
rotx = rotation[0];
roty = rotation[1];
rotz = rotation[2];
plotRotated = true;
}
public double[] getrotation() {
double[] rotation = { rotx, roty, rotz };
return rotation;
}
public void updateSeries(float[] xValues1, float[] yValues1, float[] zValues1, int series, boolean rescale) {
int length = zValues1.length;
npts[series] = length;
if (length > maxpts) {
if (length > maxpts) {
maxpts = length;
}
float[][] newxValues = new float[nseries][maxpts];
float[][] newyValues = new float[nseries][maxpts];
float[][] newzValues = new float[nseries][maxpts];
for (int i = 0; i < series; i++) {
for (int j = 0; j < npts[i]; j++) {
newxValues[i][j] = xValues[i][j];
newyValues[i][j] = yValues[i][j];
newzValues[i][j] = zValues[i][j];
}
}
for (int j = 0; j < npts[series]; j++) {
newxValues[series][j] = xValues1[j];
newyValues[series][j] = yValues1[j];
newzValues[series][j] = zValues1[j];
}
for (int i = series + 1; i < nseries; i++) {
for (int j = 0; j < npts[i]; j++) {
newxValues[i][j] = xValues[i][j];
newyValues[i][j] = yValues[i][j];
newzValues[i][j] = zValues[i][j];
}
}
xValues = newxValues;
yValues = newyValues;
zValues = newzValues;
if (rescale) {
autoscale();
}
} else {
for (int i = 0; i < length; i++) {
xValues[series][i] = xValues1[i];
yValues[series][i] = yValues1[i];
zValues[series][i] = zValues1[i];
}
if (rescale) {
autoscale();
}
}
plotChanged = true;
}
public void updateSeries(float[] zValues1, int series, boolean rescale) {
float[] xValues1 = getXValues(series);
float[] yValues1 = getYValues(series);
updateSeries(xValues1, yValues1, zValues1, series, rescale);
plotChanged = true;
}
public void deleteSeries(int series, boolean rescale) {
nseries -= 1;
float[][] newxValues;
float[][] newyValues;
float[][] newzValues;
int[] newnpts = new int[nseries];
int[] newshapes = new int[nseries];
int[] newcolors = new int[nseries];
int newmaxpts = 0;
if (npts[series] == maxpts) {
for (int i = 0; i <= nseries; i++) {
if (i != series) {
if (npts[i] > newmaxpts) {
newmaxpts = npts[i];
}
}
}
} else {
newmaxpts = maxpts;
}
newxValues = new float[nseries][newmaxpts];
newyValues = new float[nseries][newmaxpts];
newzValues = new float[nseries][newmaxpts];
for (int i = 0; i < series; i++) {
newnpts[i] = npts[i];
newshapes[i] = shapes[i];
newcolors[i] = colors[i];
for (int j = 0; j < newmaxpts; j++) {
newxValues[i][j] = xValues[i][j];
newyValues[i][j] = yValues[i][j];
newzValues[i][j] = zValues[i][j];
}
}
for (int i = series + 1; i <= nseries; i++) {
newnpts[i - 1] = npts[i];
newshapes[i - 1] = shapes[i];
newcolors[i - 1] = colors[i];
for (int j = 0; j < newmaxpts; j++) {
newxValues[i - 1][j] = xValues[i][j];
newyValues[i - 1][j] = yValues[i][j];
newzValues[i - 1][j] = zValues[i][j];
}
}
maxpts = newmaxpts;
npts = newnpts;
xValues = newxValues;
yValues = newyValues;
zValues = newzValues;
shapes = newshapes;
colors = newcolors;
if (rescale) {
autoscale();
}
// IJ.showMessage("Plot Deleted");
if (selected >= nseries) {
selected = -1;
}
plotChanged = true;
// IJ.showMessage("Selected = "+selected);
}
public void addPoints(float[] xValues1, float[] yValues1, float[] zValues1, boolean rescale) {
nseries++;
float[][] newxValues;
float[][] newyValues;
float[][] newzValues;
int[] newnpts = new int[nseries];
int[] newshapes = new int[nseries];
int[] newcolors = new int[nseries];
if (yValues1.length > maxpts || xValues1.length > maxpts | zValues1.length > maxpts) {
maxpts = findmax(new int[] { xValues1.length, yValues1.length, zValues1.length });
newxValues = new float[nseries][maxpts];
newyValues = new float[nseries][maxpts];
newzValues = new float[nseries][maxpts];
for (int i = 0; i < (nseries - 1); i++) {
newnpts[i] = npts[i];
newshapes[i] = shapes[i];
newcolors[i] = colors[i];
for (int j = 0; j < npts[i]; j++) {
newxValues[i][j] = xValues[i][j];
newyValues[i][j] = yValues[i][j];
newzValues[i][j] = zValues[i][j];
}
}
newnpts[nseries - 1] = maxpts;
newshapes[nseries - 1] = 0;
newcolors[nseries - 1] = nseries - 1;
for (int j = 0; j < maxpts; j++) {
newxValues[nseries - 1][j] = xValues1[j];
newyValues[nseries - 1][j] = yValues1[j];
newzValues[nseries - 1][j] = zValues1[j];
}
} else {
newxValues = new float[nseries][maxpts];
newyValues = new float[nseries][maxpts];
newzValues = new float[nseries][maxpts];
for (int i = 0; i < (nseries - 1); i++) {
newnpts[i] = npts[i];
newshapes[i] = shapes[i];
newcolors[i] = colors[i];
for (int j = 0; j < maxpts; j++) {
newxValues[i][j] = xValues[i][j];
newyValues[i][j] = yValues[i][j];
newzValues[i][j] = zValues[i][j];
}
}
newnpts[nseries - 1] = zValues1.length;
newshapes[nseries - 1] = 0;
newcolors[nseries - 1] = nseries - 1;
for (int j = 0; j < newnpts[nseries - 1]; j++) {
newxValues[nseries - 1][j] = xValues1[j];
newyValues[nseries - 1][j] = yValues1[j];
newzValues[nseries - 1][j] = zValues1[j];
}
}
npts = newnpts;
shapes = newshapes;
colors = newcolors;
xValues = newxValues;
yValues = newyValues;
zValues = newzValues;
if (selected >= nseries) {
selected = -1;
}
if (rescale) {
autoscale();
}
plotChanged = true;
}
public void addPoints(float[] zValues1, boolean rescale, int startxy) {
float[] xValues1 = new float[zValues1.length];
for (int i = 0; i < zValues1.length; i++) {
xValues1[i] = (float) (i + startxy);
}
float[] yValues1 = new float[zValues1.length];
for (int i = 0; i < zValues1.length; i++) {
yValues1[i] = (float) (i + startxy);
}
addPoints(xValues1, yValues1, zValues1, rescale);
plotChanged = true;
}
public int getWidth() {
return WIDTH + LEFT_MARGIN + RIGHT_MARGIN;
}
public int getHeight() {
return HEIGHT + TOP_MARGIN + BOTTOM_MARGIN;
}
protected void drawPlot(Renderer jr) {
logxmin = 0;
logymin = 0;
logxscale = 0;
logyscale = 0;
logxmax = 0;
logymax = 0;
logzmin = 0;
logzmax = 0;
logzscale = 0;
if (logx) {
if (xMin <= 0.0f) {
logxmin = (float) Math.log((double) findmingt0(xValues, npts, xMax));
} else {
logxmin = (float) Math.log((double) xMin);
}
logxmax = (float) Math.log((double) xMax);
logxscale = (float) WIDTH / (logxmax - logxmin);
}
if (logy) {
if (yMin <= 0.0f) {
logymin = (float) Math.log((double) findmingt0(yValues, npts, yMax));
} else {
logymin = (float) Math.log((double) yMin);
}
logymax = (float) Math.log((double) yMax);
logyscale = (float) WIDTH / (logymax - logymin);
}
if (logz) {
if (zMin <= 0.0f) {
logzmin = (float) Math.log((double) findmingt0(zValues, npts, zMax));
} else {
logzmin = (float) Math.log((double) zMin);
}
logzmax = (float) Math.log((double) zMax);
logzscale = (float) HEIGHT / (logzmax - logzmin);
}
// IJ.showMessage("testdraw1");
xScale = (float) WIDTH / (xMax - xMin);
yScale = (float) WIDTH / (yMax - yMin);
zScale = (float) HEIGHT / (zMax - zMin);
drawAxisLabels(jr);
int startj, endj;
if (currSeries == nseries) {
startj = 0;
endj = nseries;
} else {
startj = currSeries;
endj = currSeries + 1;
}
if (!logx && !logy && !logz) {
for (int j = startj; j < endj; j++) {
Color tempcolor = getCustomColor(j);
int xpoints[] = new int[npts[j]];
int ypoints[] = new int[npts[j]];
int zpoints[] = new int[npts[j]];
for (int i = 0; i < npts[j]; i++) {
xpoints[i] = LEFT_MARGIN + (int) ((xValues[j][i] - xMin) * xScale);
if (xpoints[i] < LEFT_MARGIN) {
xpoints[i] = LEFT_MARGIN;
}
if (xpoints[i] > LEFT_MARGIN + WIDTH) {
xpoints[i] = LEFT_MARGIN + WIDTH;
}
ypoints[i] = LEFT_MARGIN + (int) ((yValues[j][i] - yMin) * yScale);
if (ypoints[i] < LEFT_MARGIN) {
ypoints[i] = LEFT_MARGIN;
}
if (ypoints[i] > LEFT_MARGIN + WIDTH) {
ypoints[i] = LEFT_MARGIN + WIDTH;
}
zpoints[i] = TOP_MARGIN + HEIGHT - (int) ((zValues[j][i] - zMin) * zScale);
if (zpoints[i] < TOP_MARGIN) {
zpoints[i] = TOP_MARGIN;
}
if (zpoints[i] > TOP_MARGIN + HEIGHT) {
zpoints[i] = TOP_MARGIN + HEIGHT;
}
}
if (j != selected) {
if (shapes[j] == 0) {
drawPolyline(jr, xpoints, ypoints, zpoints, npts[j], tempcolor);
} else if (shapes[j] < 0) {
drawCubes(jr, xpoints, ypoints, zpoints, npts[j], shapes[j], tempcolor);
} else {
drawPolyshape(jr, xpoints, ypoints, zpoints, npts[j], shapes[j], tempcolor);
}
} else {
if (shapes[j] == 0) {
drawPolyshape(jr, xpoints, ypoints, zpoints, npts[j], 1, tempcolor);
} else if (shapes[j] < 0) {
drawCubes(jr, xpoints, ypoints, zpoints, npts[j], shapes[j], tempcolor);
} else {
drawPolyline(jr, xpoints, ypoints, zpoints, npts[j], tempcolor);
}
}
}
} else {
for (int j = startj; j < endj; j++) {
Color tempcolor = getCustomColor(j);
int xpoints[] = new int[npts[j]];
int ypoints[] = new int[npts[j]];
int zpoints[] = new int[npts[j]];
for (int i = 0; i < npts[j]; i++) {
if (logx) {
float xtemp;
if (xValues[j][i] > 0.0f) {
xtemp = (float) Math.log((double) xValues[j][i]);
} else {
xtemp = logxmin;
}
xpoints[i] = LEFT_MARGIN + (int) ((xtemp - logxmin) * logxscale);
} else {
xpoints[i] = LEFT_MARGIN + (int) ((xValues[j][i] - xMin) * xScale);
}
if (xpoints[i] < LEFT_MARGIN) {
xpoints[i] = LEFT_MARGIN;
}
if (xpoints[i] > LEFT_MARGIN + WIDTH) {
xpoints[i] = LEFT_MARGIN + WIDTH;
}
if (logy) {
float ytemp;
if (yValues[j][i] > 0.0f) {
ytemp = (float) Math.log((double) yValues[j][i]);
} else {
ytemp = logymin;
}
ypoints[i] = LEFT_MARGIN + (int) ((ytemp - logymin) * logyscale);
} else {
ypoints[i] = LEFT_MARGIN + (int) ((yValues[j][i] - yMin) * yScale);
}
if (ypoints[i] < LEFT_MARGIN) {
ypoints[i] = LEFT_MARGIN;
}
if (ypoints[i] > LEFT_MARGIN + WIDTH) {
ypoints[i] = LEFT_MARGIN + WIDTH;
}
if (logz) {
float ztemp;
if (zValues[j][i] > 0.0f) {
ztemp = (float) Math.log((double) zValues[j][i]);
} else {
ztemp = logzmin;
}
zpoints[i] = TOP_MARGIN + HEIGHT - (int) ((ztemp - logzmin) * logzscale);
} else {
zpoints[i] = TOP_MARGIN + HEIGHT - (int) ((zValues[j][i] - zMin) * zScale);
}
if (zpoints[i] < TOP_MARGIN) {
zpoints[i] = TOP_MARGIN;
}
if (zpoints[i] > TOP_MARGIN + HEIGHT) {
zpoints[i] = TOP_MARGIN + HEIGHT;
}
}
if (j != selected) {
if (shapes[j] == 0) {
drawPolyline(jr, xpoints, ypoints, zpoints, npts[j], tempcolor);
} else if (shapes[j] < 0) {
drawCubes(jr, xpoints, ypoints, zpoints, npts[j], shapes[j], tempcolor);
} else {
drawPolyshape(jr, xpoints, ypoints, zpoints, npts[j], shapes[j], tempcolor);
}
} else {
if (shapes[j] == 0) {
drawPolyshape(jr, xpoints, ypoints, zpoints, npts[j], 1, tempcolor);
} else if (shapes[j] < 0) {
drawCubes(jr, xpoints, ypoints, zpoints, npts[j], shapes[j], tempcolor);
} else {
drawPolyline(jr, xpoints, ypoints, zpoints, npts[j], tempcolor);
}
}
}
}
rotatePlot(jr);
plotChanged = false;
}
private void drawAxisLabels(Renderer jr) {
// calculate the appropriate label numbers
float[] xticklabels = new float[4];
float[] yticklabels = new float[4];
float[] zticklabels = new float[4];
for (int i = 0; i < 4; i++) {
if (logx) {
float tempx = logxmin + ((float) i / 3.0f) * (logxmax - logxmin);
xticklabels[i] = (float) Math.exp((double) tempx);
} else {
xticklabels[i] = xMin + ((float) i / 3.0f) * (xMax - xMin);
}
if (logy) {
float tempy = logymin + ((float) i / 3.0f) * (logymax - logymin);
yticklabels[i] = (float) Math.exp((double) tempy);
} else {
yticklabels[i] = yMin + ((float) i / 3.0f) * (yMax - yMin);
}
if (logz) {
float tempz = logzmin + ((float) i / 3.0f) * (logzmax - logzmin);
zticklabels[i] = (float) Math.exp((double) tempz);
} else {
zticklabels[i] = zMin + ((float) i / 3.0f) * (zMax - zMin);
}
}
// draw the z axis labels
String s = formatted_string((double) zticklabels[0]);
jr.addText3D(s, LEFT_MARGIN + WIDTH + 10, LEFT_MARGIN, TOP_MARGIN + HEIGHT - 5, Color.BLACK);
s = formatted_string((double) zticklabels[1]);
jr.addText3D(s, LEFT_MARGIN + WIDTH + 10, LEFT_MARGIN, TOP_MARGIN + (int) ((2 * HEIGHT) / 3) - 5, Color.BLACK);
s = formatted_string((double) zticklabels[2]);
jr.addText3D(s, LEFT_MARGIN + WIDTH + 10, LEFT_MARGIN, TOP_MARGIN + (int) (HEIGHT / 3) - 5, Color.BLACK);
s = formatted_string((double) zticklabels[3]);
jr.addText3D(s, LEFT_MARGIN + WIDTH + 10, LEFT_MARGIN, TOP_MARGIN - 5, Color.BLACK);
jr.addText3D(zLabel, LEFT_MARGIN + WIDTH + 25, LEFT_MARGIN, TOP_MARGIN + HEIGHT / 2 - 15, Color.BLACK);
// now the x axis labels
s = formatted_string((double) xticklabels[0]);
jr.addText3D(s, LEFT_MARGIN - 10, LEFT_MARGIN + WIDTH + 40, TOP_MARGIN + HEIGHT, Color.BLACK);
s = formatted_string((double) xticklabels[1]);
jr.addText3D(s, LEFT_MARGIN + (int) (WIDTH / 3) - 10, LEFT_MARGIN + WIDTH + 40, TOP_MARGIN + HEIGHT,
Color.BLACK);
s = formatted_string((double) xticklabels[2]);
jr.addText3D(s, LEFT_MARGIN + (int) (2 * WIDTH / 3) - 10, LEFT_MARGIN + WIDTH + 40, TOP_MARGIN + HEIGHT,
Color.BLACK);
s = formatted_string((double) xticklabels[3]);
jr.addText3D(s, LEFT_MARGIN + WIDTH - 10, LEFT_MARGIN + WIDTH + 40, TOP_MARGIN + HEIGHT, Color.BLACK);
jr.addText3D(xLabel, LEFT_MARGIN + WIDTH / 2, LEFT_MARGIN + WIDTH + 60, TOP_MARGIN + HEIGHT, Color.BLACK);
// and the y axis labels
s = formatted_string((double) yticklabels[0]);
jr.addText3D(s, LEFT_MARGIN + WIDTH + 20, LEFT_MARGIN + 10, TOP_MARGIN + HEIGHT, Color.BLACK);
s = formatted_string((double) yticklabels[1]);
jr.addText3D(s, LEFT_MARGIN + WIDTH + 20, LEFT_MARGIN + (int) (WIDTH / 3) + 10, TOP_MARGIN + HEIGHT,
Color.BLACK);
s = formatted_string((double) yticklabels[2]);
jr.addText3D(s, LEFT_MARGIN + WIDTH + 20, LEFT_MARGIN + (int) (2 * WIDTH / 3) + 10, TOP_MARGIN + HEIGHT,
Color.BLACK);
s = formatted_string((double) yticklabels[3]);
jr.addText3D(s, LEFT_MARGIN + WIDTH + 20, LEFT_MARGIN + WIDTH + 10, TOP_MARGIN + HEIGHT, Color.BLACK);
jr.addText3D(yLabel, LEFT_MARGIN + WIDTH + 60, LEFT_MARGIN + WIDTH / 2, TOP_MARGIN + HEIGHT, Color.BLACK);
// finally the grid lines
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN, TOP_MARGIN, LEFT_MARGIN, LEFT_MARGIN, TOP_MARGIN + HEIGHT, Color.BLACK);
jr.addLine3D(LEFT_MARGIN + WIDTH / 3, LEFT_MARGIN, TOP_MARGIN, LEFT_MARGIN + WIDTH / 3, LEFT_MARGIN,
TOP_MARGIN + HEIGHT, gridColor);
jr.addLine3D(LEFT_MARGIN + (2 * WIDTH) / 3, LEFT_MARGIN, TOP_MARGIN, LEFT_MARGIN + (2 * WIDTH) / 3, LEFT_MARGIN,
TOP_MARGIN + HEIGHT, gridColor);
jr.addLine3D(LEFT_MARGIN + WIDTH, LEFT_MARGIN, TOP_MARGIN, LEFT_MARGIN + WIDTH, LEFT_MARGIN,
TOP_MARGIN + HEIGHT, Color.BLACK);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN, TOP_MARGIN, LEFT_MARGIN + WIDTH, LEFT_MARGIN, TOP_MARGIN, Color.BLACK);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN, TOP_MARGIN + HEIGHT / 3, LEFT_MARGIN + WIDTH, LEFT_MARGIN,
TOP_MARGIN + HEIGHT / 3, gridColor);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN, TOP_MARGIN + (2 * HEIGHT) / 3, LEFT_MARGIN + WIDTH, LEFT_MARGIN,
TOP_MARGIN + (2 * HEIGHT) / 3, gridColor);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN, TOP_MARGIN + HEIGHT, LEFT_MARGIN + WIDTH, LEFT_MARGIN,
TOP_MARGIN + HEIGHT, Color.BLACK);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN + WIDTH / 3, TOP_MARGIN, LEFT_MARGIN, LEFT_MARGIN + WIDTH / 3,
TOP_MARGIN + HEIGHT, gridColor);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN + (2 * WIDTH) / 3, TOP_MARGIN, LEFT_MARGIN, LEFT_MARGIN + (2 * WIDTH) / 3,
TOP_MARGIN + HEIGHT, gridColor);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN + WIDTH, TOP_MARGIN, LEFT_MARGIN, LEFT_MARGIN + WIDTH,
TOP_MARGIN + HEIGHT, Color.BLACK);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN, TOP_MARGIN, LEFT_MARGIN, LEFT_MARGIN + WIDTH, TOP_MARGIN, Color.BLACK);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN, TOP_MARGIN + HEIGHT / 3, LEFT_MARGIN, LEFT_MARGIN + WIDTH,
TOP_MARGIN + HEIGHT / 3, gridColor);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN, TOP_MARGIN + (2 * HEIGHT) / 3, LEFT_MARGIN, LEFT_MARGIN + WIDTH,
TOP_MARGIN + (2 * HEIGHT) / 3, gridColor);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN, TOP_MARGIN + HEIGHT, LEFT_MARGIN, LEFT_MARGIN + WIDTH,
TOP_MARGIN + HEIGHT, Color.BLACK);
jr.addLine3D(LEFT_MARGIN + WIDTH / 3, LEFT_MARGIN, TOP_MARGIN + HEIGHT, LEFT_MARGIN + WIDTH / 3,
LEFT_MARGIN + WIDTH, TOP_MARGIN + HEIGHT, gridColor);
jr.addLine3D(LEFT_MARGIN + (2 * WIDTH) / 3, LEFT_MARGIN, TOP_MARGIN + HEIGHT, LEFT_MARGIN + (2 * WIDTH) / 3,
LEFT_MARGIN + WIDTH, TOP_MARGIN + HEIGHT, gridColor);
jr.addLine3D(LEFT_MARGIN + WIDTH, LEFT_MARGIN, TOP_MARGIN + HEIGHT, LEFT_MARGIN + WIDTH, LEFT_MARGIN + WIDTH,
TOP_MARGIN + HEIGHT, Color.BLACK);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN + WIDTH / 3, TOP_MARGIN + HEIGHT, LEFT_MARGIN + WIDTH,
LEFT_MARGIN + WIDTH / 3, TOP_MARGIN + HEIGHT, gridColor);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN + (2 * WIDTH) / 3, TOP_MARGIN + HEIGHT, LEFT_MARGIN + WIDTH,
LEFT_MARGIN + (2 * WIDTH) / 3, TOP_MARGIN + HEIGHT, gridColor);
jr.addLine3D(LEFT_MARGIN, LEFT_MARGIN + WIDTH, TOP_MARGIN + HEIGHT, LEFT_MARGIN + WIDTH, LEFT_MARGIN + WIDTH,
TOP_MARGIN + HEIGHT, Color.BLACK);
}
private void drawPolyline(Renderer jr, int[] xpoints, int[] ypoints, int[] zpoints, int npts, Color color) {
for (int i = 1; i < npts; i++) {
jr.addLine3D(xpoints[i - 1], ypoints[i], zpoints[i - 1], xpoints[i], ypoints[i], zpoints[i], color);
}
}
private void drawPolyshape(Renderer jr, int[] xpoints, int[] ypoints, int[] zpoints, int npts, int shape,
Color color) {
for (int i = 0; i < npts; i++) {
// jr.addPoint3D(xpoints[j],ypoints[i],zpoints[j][i],shapesize,color,Point3D.CIRCLE);
jr.addPoint3D(xpoints[i], ypoints[i], zpoints[i], shape - 1, color);
}
}
private void drawCubes(Renderer jr, int[] xpoints, int[] ypoints, int[] zpoints, int npts, int shape, Color color) {
for (int i = 0; i < npts; i++) {
// jr.addPoint3D(xpoints[j],ypoints[i],zpoints[j][i],shapesize,color,Point3D.CIRCLE);
jr.addCube3D(xpoints[i], ypoints[i], zpoints[i], -shape, color);
}
}
Color getColor(int index) {
int temp = index;
if (temp >= 8) {
temp = index % 8;
}
Color[] temp2 = { Color.black, Color.blue, new Color(0, 175, 0), Color.red, Color.magenta,
new Color(0, 175, 175), new Color(175, 175, 0), new Color(255, 175, 0) };
return temp2[temp];
}
public void selectSeries(int series) {
selected = series;
if (selected >= nseries) {
selected = -1;
}
}
public int getSelected() {
return selected;
}
public float[][] getXValues() {
return xValues;
}
public float[] getXValues(int series) {
return xValues[series];
}
public float[][] getYValues() {
return yValues;
}
public float[] getYValues(int series) {
return yValues[series];
}
public float[][] getZValues() {
return zValues;
}
public float[] getZValues(int series) {
return zValues[series];
}
public String getxLabel() {
return xLabel;
}
public void setxLabel(String xLabel1) {
xLabel = xLabel1;
plotChanged = true;
}
public String getyLabel() {
return yLabel;
}
public void setyLabel(String yLabel1) {
yLabel = yLabel1;
plotChanged = true;
}
public String getzLabel() {
return zLabel;
}
public void setzLabel(String zLabel1) {
zLabel = zLabel1;
plotChanged = true;
}
public int[] getNpts() {
return npts;
}
public int getNSeries() {
return nseries;
}
public int getmaxpts() {
return maxpts;
}
public float[] getLimits() {
float[] temp = { xMin, xMax, yMin, yMax, zMin, zMax };
return temp;
}
public boolean[] getLogAxes() {
boolean[] temp = { logx, logy, logz };
return temp;
}
public int[] getShapes() {
return shapes;
}
public int[] getColors() {
return colors;
}
public ColorProcessor getProcessor() {
return new ColorProcessor(getImage());
}
public void rotatePlot(Renderer jr) {
jr.setrotation((int) rotx, (int) roty, (int) rotz);
plotRotated = false;
}
public Image getImage() {
if (jr == null)
jr = new Renderer(getWidth(), getHeight());
if (plotChanged){
jr.flush();
drawPlot(jr);
}else if (plotRotated)
rotatePlot(jr);
if (!isCustomColor())
jr.setBackground(Color.WHITE);
Image renderedImg = jr.renderimage();
Graphics g = renderedImg.getGraphics();
if (isCustomColor()) {
Dimension chartSize = new Dimension(getWidth() / 2, TOP_MARGIN / 8);
g.drawImage(getColorBar(chartSize), getWidth() / 4, TOP_MARGIN / 20, chartSize.width, chartSize.height,
null);
}
return renderedImg;
}
/*
* public void saveAsEMF(String path){ byte[] binaryEMF=getEMFBinary();
* jdataio jdio=new jdataio(); try{ OutputStream os=new
* BufferedOutputStream(new FileOutputStream(path));
* jdio.writebytearray(os,binaryEMF); os.close(); }catch(IOException e){
* return; } }
*/
/**
* Saveplot2os is not currently available public byte[] getEMFBinary(){
* renderer jr=new renderer(getWidth(),getHeight()); drawPlot(jr); return
* jr.renderEMF(); }
*/
/*
* public void saveplot2file(String filename) { try { OutputStream os = new
* BufferedOutputStream(new FileOutputStream(filename)); saveplot2os(os);
* os.close(); } catch (IOException e) { return; } }
*/
/**
* Saveplot2os is not currently available
*
* @param arr
* @return
*/
/*
* public void saveplot2os(OutputStream os) { jdataio jdio = new jdataio();
* // start with unique identifier for a 3D plot jdio.writestring(os,
* "pw2_file_type"); jdio.writeintelint(os, 1); jdio.writestring(os,
* getxLabel()); jdio.writestring(os, getyLabel()); jdio.writestring(os,
* getzLabel()); jdio.writeintelint(os, nseries); // number of series'
* jdio.writeintelint(os, getmaxpts()); // max number of pts
* jdio.writeintelfloat(os, xMin); // min x axis jdio.writeintelfloat(os,
* xMax); // max x axis jdio.writeintelfloat(os, yMin); // min y axis
* jdio.writeintelfloat(os, yMax); // max y axis jdio.writeintelfloat(os,
* zMin); // min z axis jdio.writeintelfloat(os, zMax); // max z axis
* jdio.writeintelint(os, logx ? 1 : 0); // logx? jdio.writeintelint(os,
* logy ? 1 : 0); // logy? jdio.writeintelint(os, logz ? 1 : 0); // logz?
* for (int l = 0; l < nseries; l++) { jdio.writeintelint(os, npts[l]); //
* number of points in this // series jdio.writeintelint(os, shapes[l]); //
* shape index jdio.writeintelint(os, colors[l]); // color index
* jdio.writeintelfloatarray(os, xValues[l], npts[l]); // x values
* jdio.writeintelfloatarray(os, yValues[l], npts[l]); // y values
* jdio.writeintelfloatarray(os, zValues[l], npts[l]); // z values // values
* } // save the errors if they exist }
*/
private int findmax(int[] arr) {
int r = arr[0];
for (int i = 0; i < arr.length; i++)
if (r < arr[i])
r = arr[i];
return r;
}
/*
* private int findmin(int[] arr){ int r=arr[0]; for(int
* i=0;i<arr.length;i++) if(r > arr[i]) r = arr[i]; return r; }
*/
// EDIT:
public void setCurrSeries(int currSeries) {
int lastSeries = this.currSeries;
this.currSeries = currSeries % (nseries + 1);
if (this.currSeries < 0)
this.currSeries += (nseries + 1);
if (lastSeries != this.currSeries)
plotChanged = true;
}
public int getCurrSeries() {
return currSeries;
}
public boolean isLabeled() {
return labels != null;
}
public String getLabel(int i) {
if (labels == null || i < 0 || i > labels.length)
return null;
else
return labels[i];
}
Color getCustomColor(int index) {
if (isCustomColor())
return getDotColour(customColors[index], customScales, colorScales);
else
return getColor(colors[index]);
}
private Color getDotColour(float data, float[] scales, Color[] colors) {
// What proportion of the way through the possible values is that.
int index = binOf(data, scales);
if (index == 0)
return Color.BLACK;
double percentPosition = percentPosition(data, scales[index - 1], scales[index]);
int r, g, b;
r = getPositionValues(percentPosition, colors[index - 1].getRed(), colors[index].getRed());
g = getPositionValues(percentPosition, colors[index - 1].getGreen(), colors[index].getGreen());
b = getPositionValues(percentPosition, colors[index - 1].getBlue(), colors[index].getBlue());
return new Color(r, g, b);
}
private double percentPosition(float data, float b1, float b2) {
if (b1 > b2)
return (data - b2) / (b1 - b2);
else
return (data - b1) / (b2 - b1);
}
private int getPositionValues(double percent, int start, int end) {
return (int) (start + (end - start) * percent);
}
private int binOf(float data, float[] arr) {
for (int i = 1; i < arr.length; i++) {
if (data <= arr[i] && data >= arr[i - 1])
return i;
}
return 0;
}
public boolean isCustomColor() {
return (customColors != null && colorScales != null);
}
public float[] getColorValues() {
return customColors;
}
public Image getColorBar(Dimension chartSize) {
if (!isCustomColor())
return null;
int xoffset = 10, yoffset = 10, colorBarHeight = chartSize.height - yoffset,
colorBarWidth = chartSize.width - xoffset * 2;
BufferedImage chartImage = new BufferedImage(chartSize.width, chartSize.height, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D chartGraphics = chartImage.createGraphics();
// Calculate the available size for the heatmap.
float[] data = new float[colorBarWidth];
double increment = (customScales[customScales.length - 1] - customScales[0]) / colorBarWidth;
for (int i = 0; i < data.length; i++) {
data[i] = (float) (customScales[0] + increment * i);
}
chartGraphics.setColor(new Color(0, 255, 0, 0));
chartGraphics.fillRect(0, 0, chartSize.width, chartSize.height);
for (int bar = 0; bar < colorBarWidth; bar++) {
// Set colour depending on zValues.
int index = binOf(data[bar], customScales);
chartGraphics.setColor(getDotColour(data[bar], new float[] { customScales[index - 1], customScales[index] },
new Color[] { colorScales[index - 1], colorScales[index] }));
chartGraphics.fillRect(xoffset + bar, yoffset, 1, colorBarHeight);
}
for (int iScale = 0; iScale < customScales.length; iScale++) {
chartGraphics.setColor(Color.BLACK);
chartGraphics.setFont(new Font("Lucida Grande", Font.PLAIN, 12));
chartGraphics
.drawString("" + customScales[iScale],
xoffset + iScale * colorBarWidth / (customScales.length - 1)
- chartGraphics.getFontMetrics().stringWidth("" + customScales[iScale]) / 2,
yoffset);
}
// new ImagePlus("colorBar",chartImage).show();
return chartImage;
// Draw the heat map onto the chart.
}
public static String formatted_string(double number) {
double absnumber = Math.abs(number);
if (absnumber >= 1000.0 || absnumber < 0.01) {
DecimalFormat expformat = new DecimalFormat("0.00E0");
return expformat.format(number);
} else {
if (absnumber >= 100.0) {
DecimalFormat tempformat = new DecimalFormat("000.0");
return tempformat.format(number);
} else {
if (absnumber >= 10.0) {
DecimalFormat tempformat = new DecimalFormat("00.00");
return tempformat.format(number);
} else {
DecimalFormat tempformat = new DecimalFormat("0.000");
return tempformat.format(number);
}
}
}
}
}
| 39,942 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Element3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/Element3D.java | /*******************************************************************************
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
import java.awt.*;
public abstract class Element3D{
public Color color;
public boolean thick;
public abstract int getzpos();
public abstract void translate(int transx,int transy,int transz);
public abstract void moveto(int ptx,int pty,int ptz);
public abstract void rotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz);
public abstract void rotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz);
public abstract void rotatecossin(double cosx1,double cosy1,double cosz1,double sinx1,double siny1,double sinz1,int centerx,int centery,int centerz);
public abstract void addrotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz);
public abstract void addrotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz);
public abstract void transform_perspective(double horizon_dist,int centerx,int centery,int centerz);
public abstract void transform_negative_perspective(double horizon_dist,int centerx,int centery,int centerz);
@Deprecated
public abstract void drawelement(Graphics g);
public abstract void drawElement(GraphicsB3D g);
public void drawLine(Graphics g,int x1,int y1,int x2,int y2,boolean thick){
if(thick){
drawThickLine(g,x1,y1,x2,y2);
}else{
g.drawLine(x1,y1,x2,y2);
}
}
public void drawThickLine(Graphics g,int x1,int y1,int x2,int y2){
float length=(float)Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
float dx=(float)(x2-x1)/length;
float dy=(float)(y2-y1)/length;
float xpos=(float)x1;
float ypos=(float)y1;
for(int i=0;i<(int)length;i++){
drawDot(g,(int)xpos,(int)ypos);
xpos+=dx;
ypos+=dy;
}
drawDot(g,x2,y2);
}
public void drawDot(Graphics g,int x,int y){
g.drawLine(x-1,y-1,x,y-1);
g.drawLine(x-1,y,x,y);
}
}
| 2,353 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Text3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/Text3D.java | /*******************************************************************************
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
import java.awt.*;
public class Text3D extends Element3D{
public Point3D point;
public String text; // shapes are square,plus,x,triangle
public static final int fontsize=10;
public Text3D(String text1,int x,int y,int z,Color color1){
point=new Point3D(x,y,z);
text=text1;
color=color1;
}
public void moveto(int ptx,int pty,int ptz){
point.moveto(ptx,pty,ptz);
}
public void translate(int transx,int transy,int transz){
point.translate(transx,transy,transz);
}
public void rotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
point.rotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
public void rotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
point.rotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
public void rotatecossin(double cosx1,double cosy1,double cosz1,double sinx1,double siny1,double sinz1,int centerx,int centery,int centerz){
point.rotatecossin(cosx1,cosy1,cosz1,sinx1,siny1,sinz1,centerx,centery,centerz);
}
public void addrotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
point.addrotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
public void addrotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
point.addrotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
public void transform_perspective(double horizon_dist,int centerx,int centery,int centerz){
point.transform_perspective(horizon_dist,centerx,centery,centerz);
}
public void transform_negative_perspective(double horizon_dist,int centerx,int centery,int centerz){
point.transform_negative_perspective(horizon_dist,centerx,centery,centerz);
}
public int getzpos(){
return point.rz;
}
public void drawelement(Graphics g){
Color tempcolor=g.getColor();
g.setColor(color);
Font temp=g.getFont().deriveFont((float)fontsize);
g.setFont(temp);
g.drawString(text,point.rx,point.ry);
g.setColor(tempcolor);
}
public void drawElement(GraphicsB3D g){
Color tempcolor=g.getColor();
g.setColor(color);
Font temp=g.getFont().deriveFont((float)fontsize);
g.setFont(temp);
g.drawString(text,point.rx,point.ry);
g.setColor(tempcolor);
}
}
| 2,777 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
GraphicsB3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/GraphicsB3D.java | package ezcol.visual.visual3D;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
public class GraphicsB3D {
private int colorValue = Color.BLACK.getRGB();
private BufferedImage txtImage;
private Graphics txtGraphics;
private int[] pixels;
private int width, height;
public GraphicsB3D(int width, int height) {
this(null, width, height);
}
public GraphicsB3D(int[] pixels, int width, int height) {
if (pixels != null && pixels.length == width * height) {
this.pixels = pixels.clone();
this.width = width;
this.height = pixels.length / width;
} else {
this.pixels = new int[width * height];
this.width = width;
this.height = height;
}
txtImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
txtGraphics = txtImage.getGraphics();
txtGraphics.setColor(new Color(255, 255, 255, 0));
txtGraphics.fillRect(0, 0, width, height);
}
public int[] getPixels() {
return pixels.clone();
}
public BufferedImage getImage() {
BufferedImage bimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics bGr = bimage.getGraphics();
// Draw the image on to the buffered image
bimage.setRGB(0, 0, width, height, pixels, 0, width);
bGr.drawImage(txtImage, 0, 0, null);
bGr.dispose();
return bimage;
}
public void setRGB(int colorValue) {
this.colorValue = colorValue;
}
public int getRGB() {
return colorValue;
}
public void setColor(Color color) {
this.colorValue = color.getRGB();
}
public Color getColor() {
return new Color(colorValue);
}
public void setFont(Font font) {
txtGraphics.setFont(font);
}
public Font getFont() {
return txtGraphics.getFont();
}
/**
* Custom function to draw a line to an integer array
* <p>
* see <A href=
* "http://www.geeksforgeeks.org/mid-point-line-generation-algorithm/"> http
* ://www.geeksforgeeks.org/mid-point-line-generation-algorithm/ </A>.
*
* @param pixels
* input
* @param width
* offset
* @param x1
* the first point's <i>x</i> coordinate.
* @param y1
* the first point's <i>y</i> coordinate.
* @param x2
* the second point's <i>x</i> coordinate.
* @param y2
* the second point's <i>y</i> coordinate.
* @see Graphics
*
*/
void drawLine(int x1, int y1, int x2, int y2) {
int increX = y1 == y2 ? 0 : (y1 < y2 ? 1 : -1);
int increY = x1 == x2 ? 0 : (x1 < x2 ? 1 : -1);
// calculate dx & dy
int dy = y2 - y1;
int dx = x2 - x1;
int y1_y2 = y1 + y2, x1_x2 = x1 + x2;
boolean xDominant = dx * increY < dy * increX;
// initial value of decision parameter d
int d;
if (xDominant)
d = dx * increX - (dy / 2) * increY;
else
d = dy * increY - (dx / 2) * increX;
int x = x1, y = y1;
// Plot initial given point
// putpixel(x,y) can be used to print pixel
// of line in graphics
drawPixel(x, y);
drawPixel(x1_x2 - x, y1_y2 - y);
if (increX == 0 && increY == 0)
return;
boolean notMid = true;
// iterate through value of X
while (notMid) {
// E or East is chosen
if (xDominant) {
if (d * increX * increY <= 0) {
d += dx * increX;
}
// NE or North East is chosen
else {
d += (dx * increX - dy * increY);
x += increY;
}
y += increX;
notMid = (increX >= 0 && y <= y1_y2 / 2) || (increX <= 0 && y >= y1_y2 / 2);
} else {
if (d * increX * increY <= 0) {
d += dy * increY;
} else {
d += (dy * increY - dx * increX);
y += increX;
}
x += increY;
notMid = (increY >= 0 && x <= x1_x2 / 2) || (increY <= 0 && x >= x1_x2 / 2);
}
// Plot intermediate points
// putpixel(x,y) is used to print pixel
// of line in graphics
drawPixel(x, y);
drawPixel(x1_x2 - x, y1_y2 - y);
}
}
void drawOval(int sx, int sy, int w, int h){
if(w==h)
drawOval(sx,sy,w);
else
drawEllipse(sx,sy,w,h);
}
void drawEllipse(int sx, int sy, int w, int h) {
int x, y;
int offsetA = w % 2, offsetB = h % 2;
int a = (w - offsetA) / 2, b = (h - offsetB) / 2;
int a2 = a * a, b2 = b * b;
int cx = (w + offsetA) / 2, cy = (h + offsetB) / 2;
x = w - cx;
y = b - cy;
drawPixel(x + cx + sx, y + cy + sy);
// When radius is zero only a single
// point will be printed
if (w > 0) {
drawPixel(x + cx + sx, h - y - cy + sy);
drawPixel(w - x - cx + sx, y + cy + sy);
drawPixel(w - x - cx + sx, h - y - cy + sy);
}
// Initialising the value of P
int P = x * x * b2 - x * b2 + b2 / 4 + a2 - a2 * b2;
while (x * b >= y * a) {
y++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P = P + 2 * y * a2 + a2;
// Mid-point is outside the perimeter
else {
x--;
P = P + 2 * y * a2 + a2 - 2 * x * b2;
}
// All the perimeter points have already been printed
if (x * b < y * a)
break;
// Printing the generated point and its reflection
// in the other octants after translation
drawPixel(x + cx + sx, y + cy + sy);
drawPixel(x + cx + sx, h - y - cy + sy);
drawPixel(w - x - cx + sx, h - y - cy + sy);
drawPixel(w - x - cx + sx, y + cy + sy);
}
x = a - cx;
y = h - cy;
drawPixel(x + cx + sx, y + cy + sy);
// When radius is zero only a single
// point will be printed
if (w > 0) {
drawPixel(x + cx + sx, h - y - cy + sy);
drawPixel(w - x - cx + sx, y + cy + sy);
drawPixel(w - x - cx + sx, h - y - cy + sy);
}
P = y * y * a2 - y * a2 + a2 / 4 + b2 - a2 * b2;
while (x * b <= y * a) {
x++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P = P + 2 * x * b2 + b2;
// Mid-point is outside the perimeter
else {
y--;
P = P + 2 * x * b2 + b2 - 2 * y * a2;
}
// All the perimeter points have already been printed
if (x * b > y * a)
break;
// Printing the generated point and its reflection
// in the other octants after translation
drawPixel(x + cx + sx, y + cy + sy);
drawPixel(x + cx + sx, h - y - cy + sy);
drawPixel(w - x - cx + sx, h - y - cy + sy);
drawPixel(w - x - cx + sx, y + cy + sy);
}
}
void drawOval(int sx, int sy, int size) {
int x, y;
int offset = size % 2;
int r = (size - offset) / 2;
int c = (size + offset) / 2;
x = size - c;
y = r - c;
drawPixel(x + c + sx, y + c + sy);
// When radius is zero only a single
// point will be printed
if (size > 0) {
drawPixel(x + c + sx, size - y - c + sy);
drawPixel(size - x - c + sx, y + c + sy);
drawPixel(size - x - c + sx, size - y - c + sy);
drawPixel(y + c + sx, x + c + sy);
drawPixel(y + c + sx, size - x - c + sy);
drawPixel(size - y - c + sx, x + c + sy);
drawPixel(size - y - c + sx, size - x - c + sy);
}
// Initialising the value of P
int P = x * x - x + 1 - r * r;
while (x > y) {
y++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P += + 2 * y + 1;
// Mid-point is outside the perimeter
else {
x--;
P += + 2 * y + 1 - 2 * x;
}
// All the perimeter points have already been printed
if (x < y)
break;
// Printing the generated point and its reflection
// in the other octants after translation
drawPixel(x + c + sx, y + c + sy);
drawPixel(x + c + sx, size - y - c + sy);
drawPixel(size - x - c + sx, size - y - c + sy);
drawPixel(size - x - c + sx, y + c + sy);
if(x!=y){
drawPixel(y + c + sx, x + c + sy);
drawPixel(y + c + sx, size - x - c + sy);
drawPixel(size - y - c + sx, size - x - c + sy);
drawPixel(size - y - c + sx, x + c + sy);
}
}
}
void fillOval(int sx, int sy, int w, int h){
if(w==h)
fillOval(sx,sy,w);
else
fillEllipse(sx,sy,w,h);
}
void fillOval(int sx, int sy, int size) {
int x, y;
int offset = size % 2;
int r = (size - offset) / 2;
int c = (size + offset) / 2;
x = size - c;
y = r - c;
drawPixel(x + c + sx, y + c + sy);
// When radius is zero only a single
// point will be printed
if (size > 0) {
for (int j = size - y - c; j <= y+c; j++) {
drawPixel(x + c + sx, j + sy);
drawPixel(size - x - c + sx, j + sy);
drawPixel(j + sx, x +c + sy);
drawPixel(j + sx, size - x - c + sy);
}
}
// Initialising the value of P
int P = x * x - x + 1 - r * r;
while (x > y) {
y++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P += + 2 * y + 1;
// Mid-point is outside the perimeter
else {
x--;
P += + 2 * y + 1 - 2 * x;
}
// All the perimeter points have already been printed
if (x < y)
break;
// Printing the generated point and its reflection
// in the other octants after translation
for (int j = size - y - c; j <= y+c; j++) {
drawPixel(x + c + sx, j + sy);
drawPixel(size - x - c + sx, j + sy);
drawPixel(j + sx, x +c + sy);
drawPixel(j + sx, size - x - c + sy);
}
}
for (int i = size - x - c + sx; i <= x + c + sx; i++) {
for (int j = size - y - c + sy; j <= y + c + sy; j++) {
drawPixel(i, j);
}
}
}
void fillEllipse(int sx, int sy, int w, int h) {
int x, y;
int offsetA = w % 2, offsetB = h % 2;
int a = (w - offsetA) / 2, b = (h - offsetB) / 2;
int a2 = a * a, b2 = b * b;
int cx = (w + offsetA) / 2, cy = (h + offsetB) / 2;
int innerX, innerY;
x = w - cx;
y = b - cy;
// When radius is zero only a single
// point will be printed
if (w > 0) {
for (int j = h - y - cy + sy; j <= y + cy + sy; j++) {
drawPixel(x + cx + sx, j);
drawPixel(w - x - cx + sx, j);
}
}
// Initialising the value of P
int P = x * x * b2 - x * b2 + b2 / 4 + a2 - a2 * b2;
while (x * b >= y * a) {
y++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P = P + 2 * y * a2 + a2;
// Mid-point is outside the perimeter
else {
x--;
P = P + 2 * y * a2 + a2 - 2 * x * b2;
}
// All the perimeter points have already been printed
if (x * b < y * a)
break;
// Printing the generated point and its reflection
// in the other octants after translation
for (int j = h - y - cy + sy; j <= y + cy + sy; j++) {
drawPixel(x + cx + sx, j);
drawPixel(w - x - cx + sx, j);
}
}
innerX = x;
innerY = y;
x = a - cx;
y = h - cy;
// When radius is zero only a single
// point will be printed
if (h > 0) {
for (int i = w - x - cx + sx; i <= x + cx + sx; i++) {
drawPixel(i, y + cy + sy);
drawPixel(i, h - y - cy + sy);
}
}
P = y * y * a2 - y * a2 + a2 / 4 + b2 - a2 * b2;
while (x * b <= y * a) {
x++;
// Mid-point is inside or on the perimeter
if (P <= 0)
P = P + 2 * x * b2 + b2;
// Mid-point is outside the perimeter
else {
y--;
P = P + 2 * x * b2 + b2 - 2 * y * a2;
}
// All the perimeter points have already been printed
if (x * b > y * a)
break;
// Printing the generated point and its reflection
// in the other octants after translation
for (int i = w - x - cx + sx; i <= x + cx + sx; i++) {
drawPixel(i, y + cy + sy);
drawPixel(i, h - y - cy + sy);
}
}
innerX = x < innerX ? x : innerX;
innerY = y < innerY ? y : innerY;
for (int i = w - innerX - cx + sx; i <= innerX + cx + sx; i++) {
for (int j = h - innerY - cy + sy; j <= innerY + cy + sy; j++) {
drawPixel(i, j);
}
}
}
void drawRect(int x, int y, int w, int h) {
for (int i = x; i <= x + w; i++) {
drawPixel(i, y);
drawPixel(i, y + h);
}
for (int j = y; j <= y + h; j++) {
drawPixel(x, j);
drawPixel(x + w, j);
}
}
void fillRect(int x, int y, int w, int h) {
for (int i = x; i <= x + w; i++) {
for (int j = y; j <= y + h; j++) {
drawPixel(i, j);
}
}
}
void drawPixel(int x, int y) {
int idx = y * width + x;
if (x >= 0 && x < width && y >= 0 && y < pixels.length / width)
pixels[idx] = colorValue;
}
void drawSquare(int x, int y, int size) {
drawLine(x - size / 2, y - size / 2, x + size / 2, y - size / 2);
drawLine(x + size / 2, y - size / 2, x + size / 2, y + size / 2);
drawLine(x + size / 2, y + size / 2, x - size / 2, y + size / 2);
drawLine(x - size / 2, y + size / 2, x - size / 2, y - size / 2);
}
void drawCircle(int x, int y, int size) {
drawOval(x - size / 2, y - size / 2, size, size);
}
void drawFilledCircle(int x, int y, int size) {
fillOval(x - size / 2, y - size / 2, size, size);
}
void drawFilledSquare(int x, int y, int size) {
fillRect(x - size / 2, y - size / 2, size, size);
}
void drawPlus(int x, int y, int size) {
drawLine(x - size / 2, y, x + size / 2, y);
drawLine(x, y - size / 2, x, y + size / 2);
}
void drawX(int x, int y, int size) {
drawLine(x - size / 2, y - size / 2, x + size / 2, y + size / 2);
drawLine(x - size / 2, y + size / 2, x + size / 2, y - size / 2);
}
void drawTriangle(int x, int y, int size) {
drawLine(x, y - size / 2, x - size / 2, y + size / 2);
drawLine(x - size / 2, y + size / 2, x + size / 2, y + size / 2);
drawLine(x + size / 2, y + size / 2, x, y - size / 2);
}
void draw_arrow(Graphics g, int x1, int y1, int x2, int y2, boolean thick) {
float length = (float) Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
if (length == 0.0f) {
return;
}
float xinc = (float) (x2 - x1) / length;
float yinc = (float) (y2 - y1) / length;
float crossx = (float) x2 - xinc * 5.0f;
float crossy = (float) y2 - yinc * 5.0f;
float x3 = crossx - yinc * 3.5f;
float x4 = crossx + yinc * 3.5f;
float y3 = crossy + xinc * 3.5f;
float y4 = crossy - xinc * 3.5f;
drawLine(x1, y1, x2, y2, thick);
drawLine(x2, y2, Math.round(x3), Math.round(y3), thick);
drawLine(x2, y2, Math.round(x4), Math.round(y4), thick);
}
void drawLine(int x1, int y1, int x2, int y2, boolean thick) {
if (thick) {
drawThickLine(x1, y1, x2, y2);
} else {
drawLine(x1, y1, x2, y2);
}
}
void drawThickLine(int x1, int y1, int x2, int y2) {
float length = (float) Math.sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
float dx = (float) (x2 - x1) / length;
float dy = (float) (y2 - y1) / length;
float xpos = (float) x1;
float ypos = (float) y1;
for (int i = 0; i < (int) length; i++) {
drawPixel((int) xpos, (int) ypos);
xpos += dx;
ypos += dy;
}
drawPixel(x2, y2);
}
/*
* void drawDot(int x,int y){ drawLine(x-1,y-1,x,y-1); drawLine(x-1,y,x,y);
* }
*/
/**
* Not very many string will be drew, there hold it up
*/
void drawString(String str, int x, int y) {
txtGraphics.setColor(new Color(colorValue));
txtGraphics.drawString(str, x, y);
}
}
| 14,639 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Arrow3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/Arrow3D.java | /*******************************************************************************
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
import java.awt.Color;
import java.awt.Graphics;
public class Arrow3D extends Line3D{
// here we have a 3D arrow
public Arrow3D(int x11,int y11,int z11,int x21,int y21,int z21,Color color1){
super(x11,y11,z11,x21,y21,z21,color1);
}
public void drawelement(Graphics g){
Color tempcolor=g.getColor();
g.setColor(color);
draw_arrow(g,pt1.rx,pt1.ry,pt2.rx,pt2.ry);
g.setColor(tempcolor);
}
public void draw_arrow(Graphics g,int x1,int y1,int x2,int y2){
float length=(float)Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
if(length==0.0f){
return;
}
float xinc=(float)(x2-x1)/length;
float yinc=(float)(y2-y1)/length;
float crossx=(float)x2-xinc*5.0f;
float crossy=(float)y2-yinc*5.0f;
float x3=crossx-yinc*3.5f;
float x4=crossx+yinc*3.5f;
float y3=crossy+xinc*3.5f;
float y4=crossy-xinc*3.5f;
drawLine(g,x1,y1,x2,y2,thick);
drawLine(g,x2,y2,Math.round(x3),Math.round(y3),thick);
drawLine(g,x2,y2,Math.round(x4),Math.round(y4),thick);
}
}
| 1,506 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Renderer.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/Renderer.java | /*******************************************************************************
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
import java.awt.*;
import java.awt.image.*;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Set;
//import java.io.ByteArrayOutputStream;
//import org.freehep.graphicsio.emf.EMFGraphics2D;
import java.util.Vector;
public class Renderer {
// this class returns an awt image based on transformations of 3D spots and
// lines
public Set<Element3D> elementSet = new HashSet<Element3D>();
public Vector<Element3D> elements = new Vector<Element3D>();
public int width, height, centerx, centery, centerz;
public double degx, degy, degz, horizon_dist;
public Color background;
public Renderer(int width1, int height1) {
width = width1;
centerx = width / 2;
height = height1;
centery = height / 2;
centerz = height / 2;
degx = 0.0;
degy = 0.0;
degz = 0.0;
background = Color.GRAY;
}
public void flush(){
elementSet.clear();
elements.clear();
}
public void addelement(Element3D element) {
// element.translate(width/2,width/2,height/2);
if (!elementSet.contains(element)) {
elements.add(element);
elementSet.add(element);
}
}
public void addText3D(String s, int x, int y, int z, Color color) {
addelement(new Text3D(s, x, y, z, color));
}
public void addLine3D(int x1, int y1, int z1, int x2, int y2, int z2, Color color) {
addelement(new Line3D(x1, y1, z1, x2, y2, z2, color));
}
public void addPoint3D(int x, int y, int z, int shape, Color color) {
addelement(new Spot3D(x, y, z, shape % Spot3D.ALL_SHAPES, color, shape / Spot3D.ALL_SHAPES));
}
public void addCube3D(int x, int y, int z, int size, Color color) {
addelement(new Cube3D(x, y, z, size, color));
}
// public void setelementarray(element3D[] elements) {
// this.elements.addAll(new ArrayList<element3D>(Arrays.asList(elements)));
/*
* for(int i=0;i<elements.size();i++){
* elements.get(i).translate(width/2,width/2,height/2); }
*/
// }
public void addpointarray(int[] x, int[] y, int[] z, int shape, Color color) {
for (int i = 0; i < x.length; i++)
elements.add(new Spot3D(x[i], y[i], z[i], shape, color));
}
public void addpolyline(int[] x, int[] y, int[] z, Color color) {
for (int i = 0; i < x.length - 1; i++)
elements.add(new Line3D(x[i], y[i], z[i], x[i + 1], y[i + 1], z[i + 1], color));
}
public void setrotation(int degx1, int degy1, int degz1) {
degx = (double) degx1;
degy = (double) degy1;
degz = (double) degz1;
double cosx = Math.cos(Math.toRadians(degx));
double cosy = Math.cos(Math.toRadians(degy));
double cosz = Math.cos(Math.toRadians(-degz));
double sinx = Math.sin(Math.toRadians(degx));
double siny = Math.sin(Math.toRadians(degy));
double sinz = Math.sin(Math.toRadians(-degz));
for (int i = 0; i < elements.size(); i++) {
elements.get(i).rotatecossin(cosx, cosy, cosz, sinx, siny, sinz, centerx, centery, centerz);
}
}
public void setrotation(float degx1, float degy1, float degz1) {
degx = (double) degx1;
degy = (double) degy1;
degz = (double) degz1;
double cosx = Math.cos(Math.toRadians(degx));
double cosy = Math.cos(Math.toRadians(degy));
double cosz = Math.cos(Math.toRadians(-degz));
double sinx = Math.sin(Math.toRadians(degx));
double siny = Math.sin(Math.toRadians(degy));
double sinz = Math.sin(Math.toRadians(-degz));
for (int i = 0; i < elements.size(); i++) {
elements.get(i).rotatecossin(cosx, cosy, cosz, sinx, siny, sinz, centerx, centery, centerz);
}
}
public void set_perspective(double horizon_dist1) {
horizon_dist = horizon_dist1;
for (int i = 0; i < elements.size(); i++) {
elements.get(i).transform_perspective(horizon_dist, centerx, centery, centerz);
}
}
public void set_negative_perspective(double horizon_dist1) {
horizon_dist = horizon_dist1;
for (int i = 0; i < elements.size(); i++) {
elements.get(i).transform_negative_perspective(horizon_dist, centerx, centery, centerz);
}
}
public void rotate(int dx, int dy, int dz) {
degx += (double) dx;
degy += (double) dy;
degz += (double) dz;
for (int i = 0; i < elements.size(); i++) {
elements.get(i).rotatedeg(degx, degy, degz, centerx, centery, centerz);
}
}
public void addrotation(int dx, int dy, int dz) {
for (int i = 0; i < elements.size(); i++) {
elements.get(i).addrotatedeg((double) dx, (double) dy, (double) dz, centerx, centery, centerz);
}
}
private void setyorder() {
// here we sort the element list in order of decreasing z value
// that way closer z values will be drawn last, on top of further z
// values
float[] zvals = new float[elements.size()];
for (int i = 0; i < elements.size(); i++) {
zvals[i] = (float) elements.get(i).getzpos();
}
Collections.sort(elements, new Comparator<Element3D>() {
@Override
public int compare(Element3D o1, Element3D o2) {
// TODO Auto-generated method stub
if (o1.getzpos() < o2.getzpos())
return 1;
else if (o1.getzpos() > o2.getzpos())
return -1;
else
return 0;
}
});
}
@SuppressWarnings("deprecation")
public Image renderimage() {
/* @deprecated
* too slow to use Graphics to draw
* Image retimage=new
* BufferedImage(width,height,BufferedImage.TYPE_4BYTE_ABGR); Graphics
* g=retimage.getGraphics(); Color tempcolor=g.getColor();
* g.setColor(background); g.fillRect(0,0,width,height);
* g.setColor(tempcolor);
*/
GraphicsB3D g3D = new GraphicsB3D(width, height);
Color tempColor = g3D.getColor();
g3D.setColor(background);
g3D.fillRect(0, 0, width, height);
g3D.setColor(tempColor);
setyorder();
for (int i = 0; i < elements.size(); i++) {
elements.get(i).drawElement(g3D);
}
Image retimage = g3D.getImage();
return retimage;
}
/*
* public byte[] renderEMF(){ try{ ByteArrayOutputStream os=new
* ByteArrayOutputStream(); EMFGraphics2D g=new EMFGraphics2D(os,new
* Dimension(width,height)); g=new EMFGraphics2D(os,new
* Dimension(width,height)); g.setDeviceIndependent(true); g.startExport();
* Color tempcolor=g.getColor(); g.setColor(background);
* g.fillRect(0,0,width,height); g.setColor(tempcolor); setyorder(); for(int
* i=0;i<elements.size();i++){ elements.get(i).drawelement(g); }
* g.endExport(); return os.toByteArray(); }catch(Throwable e){ return null;
* } }
*/
public float[] renderfloat(float value) {
Image retimage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = retimage.getGraphics();
Color tempcolor = g.getColor();
g.setColor(background);
g.fillRect(0, 0, width, height);
g.setColor(tempcolor);
setyorder();
for (int i = 0; i < elements.size(); i++) {
elements.get(i).drawelement(g);
}
int[] pixels = ((BufferedImage) retimage).getRGB(0, 0, width, height, null, 0, width);
float[] output = new float[width * height];
for (int i = 0; i < width * height; i++) {
if ((pixels[i] & 0xffffff) > 0)
output[i] = value;
}
return output;
}
public Image renderanalglyph(Color leftcolor, Color rightcolor, double angle) {
Color[] colors = new Color[elements.size()];
for (int i = 0; i < elements.size(); i++) {
colors[i] = copycolor(elements.get(i).color);
}
Color[] leftcolors = new Color[elements.size()];
for (int i = 0; i < elements.size(); i++) {
leftcolors[i] = scalecolor(leftcolor, colormagnitude(colors[i]));
}
Color[] rightcolors = new Color[elements.size()];
for (int i = 0; i < elements.size(); i++) {
rightcolors[i] = scalecolor(rightcolor, colormagnitude(colors[i]));
}
// set up the drawing
Image retimage1 = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Image retimage2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g1 = retimage1.getGraphics();
Color tempcolor = g1.getColor();
g1.setColor(background);
g1.fillRect(0, 0, width, height);
g1.setColor(tempcolor);
Graphics g2 = retimage2.getGraphics();
tempcolor = g2.getColor();
g2.setColor(background);
g2.fillRect(0, 0, width, height);
g2.setColor(tempcolor);
// start by drawing the left color
// for(int
// i=0;i<elements.size();i++){elements.get(i).color=scalecolor(leftcolor,colormagnitude(colors[i]));}
for (int i = 0; i < elements.size(); i++) {
elements.get(i).color = leftcolor;
}
addrotation(0, -(int) (angle / 2.0), 0);
setyorder();
for (int i = 0; i < elements.size(); i++) {
elements.get(i).drawelement(g1);
}
// now draw the right color
// for(int
// i=0;i<elements.size();i++){elements.get(i).color=scalecolor(rightcolor,colormagnitude(colors[i]));}
for (int i = 0; i < elements.size(); i++) {
elements.get(i).color = rightcolor;
}
setrotation((int) degx, (int) degy, (int) degz);
set_perspective(horizon_dist);
addrotation(0, (int) (angle / 2.0), 0);
setyorder();
for (int i = 0; i < elements.size(); i++) {
elements.get(i).drawelement(g2);
}
// now reset everything
for (int i = 0; i < elements.size(); i++) {
elements.get(i).color = colors[i];
}
setrotation((int) degx, (int) degy, (int) degz);
set_perspective(horizon_dist);
return combinecoloranalglyphs(retimage1, retimage2);
}
public Image renderinterlacedanalglyph(double angle) {
return renderinterlacedanalglyph(angle, 0);
}
public Image renderinterlacedanalglyph(double angle, int interlacetype) {
// note that interlace types are 0:diagonal,1:vertical,and 2:horizontal
// set up the drawing
Image retimage1 = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Image retimage2 = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g1 = retimage1.getGraphics();
Color tempcolor = g1.getColor();
g1.setColor(background);
g1.fillRect(0, 0, width, height);
g1.setColor(tempcolor);
Graphics g2 = retimage2.getGraphics();
tempcolor = g2.getColor();
g2.setColor(background);
g2.fillRect(0, 0, width, height);
g2.setColor(tempcolor);
// start by drawing the left image
double tempdegy = degy;
addrotation(0, -(int) (angle / 2.0), 0);
setyorder();
for (int i = 0; i < elements.size(); i++) {
elements.get(i).drawelement(g1);
}
// now draw the right image
setrotation((int) degx, (int) degy, (int) degz);
set_perspective(horizon_dist);
addrotation(0, (int) (angle / 2.0), 0);
setyorder();
for (int i = 0; i < elements.size(); i++) {
elements.get(i).drawelement(g2);
}
// now reset everything
setrotation((int) degx, (int) tempdegy, (int) degz);
set_perspective(horizon_dist);
return interlaceanalglyphs(retimage1, retimage2, interlacetype);
}
public Image combinecoloranalglyphs(Image leftimage, Image rightimage) {
// here we add two images typically orthogonal color spaces should be
// used
int width = leftimage.getWidth(null);
int height = leftimage.getHeight(null);
int[] pix1 = getimagepixels(leftimage);
int[] pix2 = getimagepixels(rightimage);
int[] retpix = new int[width * height];
for (int i = 0; i < width; i++) {
// run the left image first
for (int j = 0; j < height; j++) {
retpix[i + j * width] = maxcolor(pix1[i + j * width], pix2[i + j * width]);
}
}
return getimagefrompixels(retpix, width, height);
}
public Image interlaceanalglyphs(Image leftimage, Image rightimage, int interlace) {
int width = leftimage.getWidth(null);
int height = leftimage.getHeight(null);
int[] pix1 = getimagepixels(leftimage);
int[] pix2 = getimagepixels(rightimage);
int[] retpix = new int[width * height];
// eliminate every other line and every other row
if (interlace < 2) {
boolean even = true;
boolean vinterlace = (interlace == 1);
for (int i = 0; i < height; i++) {
for (int j = 0; j < width; j += 2) {
int pixval1 = 0;
int pixval2 = 0;
if (vinterlace || even) {
pixval1 = maxcolor(pix1[j + i * width], pix1[j + 1 + i * width]);
pixval2 = maxcolor(pix2[j + i * width], pix2[j + 1 + i * width]);
} else {
pixval1 = maxcolor(pix2[j + i * width], pix2[j + 1 + i * width]);
pixval2 = maxcolor(pix1[j + i * width], pix1[j + 1 + i * width]);
}
retpix[j + i * width] = pixval1;
retpix[j + 1 + i * width] = pixval2;
}
even = !even;
}
} else {
for (int i = 0; i < height; i += 2) {
for (int j = 0; j < width; j++) {
int pixval1 = 0;
int pixval2 = 0;
pixval1 = maxcolor(pix1[j + i * width], pix1[j + (i + 1) * width]);
pixval2 = maxcolor(pix2[j + i * width], pix2[j + (i + 1) * width]);
retpix[j + i * width] = pixval1;
retpix[j + 1 + i * width] = pixval2;
}
}
}
return getimagefrompixels(retpix, width, height);
}
public int maxcolor(int pix1, int pix2) {
boolean white1 = (pix1 == 0xffffffff);
boolean white2 = (pix2 == 0xffffffff);
int r1 = (pix1 & 0xff0000) >> 16;
int g1 = (pix1 & 0xff00) >> 8;
int b1 = pix1 & 0xff;
if (!white2) {
int r2 = (pix2 & 0xff0000) >> 16;
int g2 = (pix2 & 0xff00) >> 8;
int b2 = (pix2 & 0xff);
if (!white1) {
r1 += r2;
g1 += g2;
b1 += b2;
} else {
r1 = r2;
g1 = g2;
b1 = b2;
}
}
return 0xff000000 + (r1 << 16) + (g1 << 8) + b1;
}
public int colormagnitude(Color colorval) {
int r1 = colorval.getRed();
int max = r1;
int g1 = colorval.getGreen();
if (g1 > max) {
max = g1;
}
int b1 = colorval.getBlue();
if (b1 > max) {
max = b1;
}
// int mag=(int)Math.sqrt(r1*r1+g1*g1+b1*b1);
// if(mag>255){mag=255;}
// return (int)(0.33f*(r1+g1+b1));
return max;
}
public Color scalecolor(Color colorval, int scale) {
float factor = (float) scale / 255.0f;
int r1 = (int) (factor * colorval.getRed());
int g1 = (int) (factor * colorval.getGreen());
int b1 = (int) (factor * colorval.getBlue());
return new Color(r1, g1, b1);
}
public Color copycolor(Color colorval) {
return new Color(colorval.getRed(), colorval.getGreen(), colorval.getBlue());
}
public Image getimagefrompixels(int[] pixels, int width, int height) {
MemoryImageSource source = new MemoryImageSource(width, height, pixels, 0, width);
return Toolkit.getDefaultToolkit().createImage(source);
}
public int[] getimagepixels(Image input) {
int width = input.getWidth(null);
int height = input.getHeight(null);
int[] pixels = new int[width * height];
PixelGrabber pg = new PixelGrabber(input, 0, 0, width, height, pixels, 0, width);
try {
pg.grabPixels();
} catch (InterruptedException e) {
}
;
return pixels;
}
public void setBackground(Color color){
background = color;
}
}
| 15,016 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Square3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/Square3D.java | /*******************************************************************************
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
import java.awt.*;
public class Square3D extends Element3D{
public Point3D[] pt;
public final int size;
public final String[] orientations={"xy","xz","yz"};
public int orientation;
// here we have a 3D square
public Square3D(int x,int y,int z,int size1,int orientation1,Color color1){
pt=new Point3D[4];
size=size1;
orientation=orientation1;
int halfsize=size/2;
if(orientation==0){
pt[0]=new Point3D(x-halfsize,y-halfsize,z);
pt[1]=new Point3D(x+halfsize,y-halfsize,z);
pt[2]=new Point3D(x+halfsize,y+halfsize,z);
pt[3]=new Point3D(x-halfsize,y+halfsize,z);
}else{
if(orientation==1){
pt[0]=new Point3D(x-halfsize,y,z-halfsize);
pt[1]=new Point3D(x+halfsize,y,z-halfsize);
pt[2]=new Point3D(x+halfsize,y,z+halfsize);
pt[3]=new Point3D(x-halfsize,y,z+halfsize);
}else{
pt[0]=new Point3D(x,y-halfsize,z-halfsize);
pt[1]=new Point3D(x,y+halfsize,z-halfsize);
pt[2]=new Point3D(x,y+halfsize,z+halfsize);
pt[3]=new Point3D(x,y-halfsize,z+halfsize);
}
}
color=color1;
}
public void moveto(int x,int y,int z){
int halfsize=size/2;
if(orientation==0){
pt[0]=new Point3D(x-halfsize,y-halfsize,z);
pt[1]=new Point3D(x+halfsize,y-halfsize,z);
pt[2]=new Point3D(x+halfsize,y+halfsize,z);
pt[3]=new Point3D(x-halfsize,y+halfsize,z);
}else{
if(orientation==1){
pt[0]=new Point3D(x-halfsize,y,z-halfsize);
pt[1]=new Point3D(x+halfsize,y,z-halfsize);
pt[2]=new Point3D(x+halfsize,y,z+halfsize);
pt[3]=new Point3D(x-halfsize,y,z+halfsize);
}else{
pt[0]=new Point3D(x,y-halfsize,z-halfsize);
pt[1]=new Point3D(x,y+halfsize,z-halfsize);
pt[2]=new Point3D(x,y+halfsize,z+halfsize);
pt[3]=new Point3D(x,y-halfsize,z+halfsize);
}
}
}
public void translate(int transx,int transy,int transz){
for(int i=0;i<4;i++){
pt[i].translate(transx,transy,transz);
}
}
public void rotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
for(int i=0;i<4;i++){
pt[i].rotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
}
public void rotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
for(int i=0;i<4;i++){
pt[i].rotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
}
public void rotatecossin(double cosx1,double cosy1,double cosz1,double sinx1,double siny1,double sinz1,int centerx,int centery,int centerz){
for(int i=0;i<4;i++){
pt[i].rotatecossin(cosx1,cosy1,cosz1,sinx1,siny1,sinz1,centerx,centery,centerz);
}
}
public void addrotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
for(int i=0;i<4;i++){
pt[i].addrotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
}
public void addrotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
for(int i=0;i<4;i++){
pt[i].addrotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
}
public void transform_perspective(double horizon_dist,int centerx,int centery,int centerz){
for(int i=0;i<4;i++){
pt[i].transform_perspective(horizon_dist,centerx,centery,centerz);
}
}
public void transform_negative_perspective(double horizon_dist,int centerx,int centery,int centerz){
for(int i=0;i<4;i++){
pt[i].transform_negative_perspective(horizon_dist,centerx,centery,centerz);
}
}
public int getzpos(){
float sum=0.0f;
for(int i=0;i<4;i++){
sum+=pt[i].rz;
}
int zpos=(int)(0.125f*sum);
return zpos;
}
public void drawelement(Graphics g){
Color tempcolor=g.getColor();
g.setColor(color);
// draw the top square
drawLine(g,pt[0].rx,pt[0].ry,pt[1].rx,pt[1].ry,thick);
drawLine(g,pt[1].rx,pt[1].ry,pt[2].rx,pt[2].ry,thick);
drawLine(g,pt[2].rx,pt[2].ry,pt[3].rx,pt[3].ry,thick);
drawLine(g,pt[3].rx,pt[3].ry,pt[0].rx,pt[0].ry,thick);
g.setColor(tempcolor);
}
public void drawElement(GraphicsB3D g){
Color tempcolor=g.getColor();
g.setColor(color);
// draw the top square
g.drawLine(pt[0].rx,pt[0].ry,pt[1].rx,pt[1].ry,thick);
g.drawLine(pt[1].rx,pt[1].ry,pt[2].rx,pt[2].ry,thick);
g.drawLine(pt[2].rx,pt[2].ry,pt[3].rx,pt[3].ry,thick);
g.drawLine(pt[3].rx,pt[3].ry,pt[0].rx,pt[0].ry,thick);
g.setColor(tempcolor);
}
}
| 4,756 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Polygon3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/Polygon3D.java | /*******************************************************************************
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
import java.awt.*;
public class Polygon3D extends Element3D{
public Point3D[] pt;
public boolean closed;
// here we have a 3D line
public Polygon3D(int[] xpts,int[] ypts,int[] zpts,Color color1){
pt=new Point3D[xpts.length];
color=color1;
for(int i=0;i<xpts.length;i++){
pt[i]=new Point3D(xpts[i],ypts[i],zpts[i]);
}
color=color1;
closed=true;
}
public Polygon3D(Polygon poly,Color color1){
pt=new Point3D[poly.xpoints.length];
color=color1;
for(int i=0;i<poly.xpoints.length;i++){
pt[i]=new Point3D(poly.xpoints[i],poly.ypoints[i],0);
}
color=color1;
closed=true;
}
public Polygon getPolygon(){
int[] xpoints=new int[pt.length];
int[] ypoints=new int[pt.length];
for(int i=0;i<pt.length;i++){
xpoints[i]=pt[i].rx;
ypoints[i]=pt[i].ry;
}
return new Polygon(xpoints,ypoints,pt.length);
}
public void moveto(int x,int y,int z){
translate(x-pt[0].rx,y-pt[0].ry,z-pt[0].rz);
}
public void translate(int transx,int transy,int transz){
for(int i=0;i<pt.length;i++){
pt[i].translate(transx,transy,transz);
}
}
public void rotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
for(int i=0;i<pt.length;i++){
pt[i].rotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
}
public void rotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
for(int i=0;i<pt.length;i++){
pt[i].rotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
}
public void rotatecossin(double cosx1,double cosy1,double cosz1,double sinx1,double siny1,double sinz1,int centerx,int centery,int centerz){
for(int i=0;i<pt.length;i++){
pt[i].rotatecossin(cosx1,cosy1,cosz1,sinx1,siny1,sinz1,centerx,centery,centerz);
}
}
public void addrotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
for(int i=0;i<pt.length;i++){
pt[i].addrotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
}
public void addrotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
for(int i=0;i<pt.length;i++){
pt[i].addrotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
}
public void transform_perspective(double horizon_dist,int centerx,int centery,int centerz){
for(int i=0;i<pt.length;i++){
pt[i].transform_perspective(horizon_dist,centerx,centery,centerz);
}
}
public void transform_negative_perspective(double horizon_dist,int centerx,int centery,int centerz){
for(int i=0;i<pt.length;i++){
pt[i].transform_negative_perspective(horizon_dist,centerx,centery,centerz);
}
}
public int getzpos(){
float sum=0.0f;
for(int i=0;i<pt.length;i++){
sum+=pt[i].rz;
}
int zpos=(int)(sum/pt.length);
return zpos;
}
public void drawelement(Graphics g){
Color tempcolor=g.getColor();
g.setColor(color);
for(int i=1;i<pt.length;i++){
drawLine(g,pt[i-1].rx,pt[i-1].ry,pt[i].rx,pt[i].ry,thick);
}
if(closed){
drawLine(g,pt[pt.length-1].rx,pt[pt.length-1].ry,pt[0].rx,pt[0].ry,thick);
}
g.setColor(tempcolor);
}
public void drawElement(GraphicsB3D g){
Color tempcolor=g.getColor();
g.setColor(color);
for(int i=1;i<pt.length;i++){
g.drawLine(pt[i-1].rx,pt[i-1].ry,pt[i].rx,pt[i].ry,thick);
}
if(closed){
g.drawLine(pt[pt.length-1].rx,pt[pt.length-1].ry,pt[0].rx,pt[0].ry,thick);
}
g.setColor(tempcolor);
}
}
| 3,895 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Spot3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/Spot3D.java | /*******************************************************************************
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
import java.awt.*;
public class Spot3D extends Element3D{
public Point3D point;
public int shape; // shapes are square,plus,x,triangle
public int shapesize=8;
private int transshapesize;
//EDIT:
public static final int SQUARE = 0, PLUS = 1, CROSS = 2, TRIANGLE = 3, CIRCLE = 4, FILLED_SQUARE = 5, FILLED_CIRCLE = 6, ALL_SHAPES = 7;
public Spot3D(int x,int y,int z,int shape1,Color color1){
point=new Point3D(x,y,z);
shape=shape1;
color=color1;
transshapesize=shapesize;
}
public Spot3D(int x,int y,int z,int shape1,Color color1, int shapesize){
point=new Point3D(x,y,z);
shape=shape1;
color=color1;
if(shapesize>this.shapesize)
this.shapesize = shapesize;
transshapesize = this.shapesize;
}
public void moveto(int ptx,int pty,int ptz){
point.moveto(ptx,pty,ptz);
}
public void translate(int transx,int transy,int transz){
point.translate(transx,transy,transz);
}
public void rotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
point.rotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
public void rotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
point.rotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
public void rotatecossin(double cosx1,double cosy1,double cosz1,double sinx1,double siny1,double sinz1,int centerx,int centery,int centerz){
point.rotatecossin(cosx1,cosy1,cosz1,sinx1,siny1,sinz1,centerx,centery,centerz);
}
public void addrotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
point.addrotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
public void addrotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
point.addrotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
public void transform_perspective(double horizon_dist,int centerx,int centery,int centerz){
point.transform_perspective(horizon_dist,centerx,centery,centerz);
if(horizon_dist<=0.0){
transshapesize=shapesize;
}else{
double tempz=(double)(point.z-centerz);
double temphordist=(tempz+horizon_dist)/horizon_dist;
if(temphordist<=0){
transshapesize=0;
}else{
transshapesize=(int)(shapesize*temphordist);
}
}
}
public void transform_negative_perspective(double horizon_dist,int centerx,int centery,int centerz){
point.transform_negative_perspective(horizon_dist,centerx,centery,centerz);
if(horizon_dist<=0.0){
transshapesize=shapesize;
}else{
double tempz=(double)(centerz-point.z);
double temphordist=(horizon_dist-tempz)/horizon_dist;
if(temphordist<=0){
transshapesize=0;
}else{
transshapesize=(int)(shapesize*temphordist);
}
}
}
public int getzpos(){
return point.rz;
}
public void drawelement(Graphics g){
Color tempcolor=g.getColor();
g.setColor(color);
switch(shape){
case SQUARE:
drawSquare(g,point.rx,point.ry,transshapesize);
break;
case PLUS:
drawPlus(g,point.rx,point.ry,transshapesize);
break;
case CROSS:
drawX(g,point.rx,point.ry,transshapesize);
break;
case TRIANGLE:
drawTriangle(g,point.rx,point.ry,transshapesize);
break;
case CIRCLE:
drawCircle(g,point.rx,point.ry,transshapesize);
break;
case FILLED_SQUARE:
drawFilledSquare(g,point.rx,point.ry,transshapesize);
break;
case FILLED_CIRCLE:
drawFilledCircle(g,point.rx,point.ry,transshapesize);
}
g.setColor(tempcolor);
}
void drawSquare(Graphics g,int x,int y,int size){
g.drawLine(x-size/2,y-size/2,x+size/2,y-size/2);
g.drawLine(x+size/2,y-size/2,x+size/2,y+size/2);
g.drawLine(x+size/2,y+size/2,x-size/2,y+size/2);
g.drawLine(x-size/2,y+size/2,x-size/2,y-size/2);
}
void drawCircle(Graphics g,int x,int y,int size){
g.drawOval(x-size/2,y-size/2,size,size);
}
void drawFilledCircle(Graphics g,int x,int y,int size){
g.fillOval(x-size/2,y-size/2,size,size);
}
void drawFilledSquare(Graphics g,int x,int y,int size){
g.fillRect(x-size/2,y-size/2,size,size);
}
void drawPlus(Graphics g,int x,int y,int size){
g.drawLine(x-size/2,y,x+size/2,y);
g.drawLine(x,y-size/2,x,y+size/2);
}
void drawX(Graphics g,int x,int y,int size){
g.drawLine(x-size/2,y-size/2,x+size/2,y+size/2);
g.drawLine(x-size/2,y+size/2,x+size/2,y-size/2);
}
void drawTriangle(Graphics g,int x,int y,int size){
g.drawLine(x,y-size/2,x-size/2,y+size/2);
g.drawLine(x-size/2,y+size/2,x+size/2,y+size/2);
g.drawLine(x+size/2,y+size/2,x,y-size/2);
}
public void drawElement(GraphicsB3D g){
Color tempcolor = g.getColor();
g.setColor(color);
switch(shape){
case SQUARE:
g.drawSquare(point.rx,point.ry,transshapesize);
break;
case PLUS:
g.drawPlus(point.rx,point.ry,transshapesize);
break;
case CROSS:
g.drawX(point.rx,point.ry,transshapesize);
break;
case TRIANGLE:
g.drawTriangle(point.rx,point.ry,transshapesize);
break;
case CIRCLE:
g.drawCircle(point.rx,point.ry,transshapesize);
break;
case FILLED_SQUARE:
g.drawFilledSquare(point.rx,point.ry,transshapesize);
break;
case FILLED_CIRCLE:
g.drawFilledCircle(point.rx,point.ry,transshapesize);
}
g.setColor(tempcolor);
}
}
| 5,742 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Cube3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/Cube3D.java | /*******************************************************************************
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
import java.awt.*;
public class Cube3D extends Element3D{
public Point3D[] pt;
public final int size;
// here we have a 3D line
public Cube3D(int x,int y,int z,int size1,Color color1){
pt=new Point3D[8];
size=size1;
int halfsize=size/2;
// start with the upper square
pt[0]=new Point3D(x-halfsize,y-halfsize,z-halfsize);
pt[1]=new Point3D(x+halfsize,y-halfsize,z-halfsize);
pt[2]=new Point3D(x+halfsize,y+halfsize,z-halfsize);
pt[3]=new Point3D(x-halfsize,y+halfsize,z-halfsize);
pt[4]=new Point3D(x-halfsize,y-halfsize,z+halfsize);
pt[5]=new Point3D(x+halfsize,y-halfsize,z+halfsize);
pt[6]=new Point3D(x+halfsize,y+halfsize,z+halfsize);
pt[7]=new Point3D(x-halfsize,y+halfsize,z+halfsize);
color=color1;
}
public void moveto(int x,int y,int z){
int halfsize=size/2;
pt[0].moveto(x-halfsize,y-halfsize,z-halfsize);
pt[1].moveto(x+halfsize,y-halfsize,z-halfsize);
pt[2].moveto(x+halfsize,y+halfsize,z-halfsize);
pt[3].moveto(x-halfsize,y+halfsize,z-halfsize);
pt[4].moveto(x-halfsize,y-halfsize,z+halfsize);
pt[5].moveto(x+halfsize,y-halfsize,z+halfsize);
pt[6].moveto(x+halfsize,y+halfsize,z+halfsize);
pt[7].moveto(x-halfsize,y+halfsize,z+halfsize);
}
public void translate(int transx,int transy,int transz){
for(int i=0;i<8;i++){
pt[i].translate(transx,transy,transz);
}
}
public void rotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].rotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
}
public void rotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].rotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
}
public void rotatecossin(double cosx1,double cosy1,double cosz1,double sinx1,double siny1,double sinz1,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].rotatecossin(cosx1,cosy1,cosz1,sinx1,siny1,sinz1,centerx,centery,centerz);
}
}
public void addrotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].addrotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
}
public void addrotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].addrotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
}
public void transform_perspective(double horizon_dist,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].transform_perspective(horizon_dist,centerx,centery,centerz);
}
}
public void transform_negative_perspective(double horizon_dist,int centerx,int centery,int centerz){
for(int i=0;i<8;i++){
pt[i].transform_negative_perspective(horizon_dist,centerx,centery,centerz);
}
}
public int getzpos(){
float sum=0.0f;
for(int i=0;i<8;i++){
sum+=pt[i].rz;
}
int zpos=(int)(0.125f*sum);
return zpos;
}
public void drawelement(Graphics g){
Color tempcolor=g.getColor();
g.setColor(color);
// draw the top square
drawLine(g,pt[0].rx,pt[0].ry,pt[1].rx,pt[1].ry,thick);
drawLine(g,pt[1].rx,pt[1].ry,pt[2].rx,pt[2].ry,thick);
drawLine(g,pt[2].rx,pt[2].ry,pt[3].rx,pt[3].ry,thick);
drawLine(g,pt[3].rx,pt[3].ry,pt[0].rx,pt[0].ry,thick);
// draw the bottom square
drawLine(g,pt[4].rx,pt[4].ry,pt[5].rx,pt[5].ry,thick);
drawLine(g,pt[5].rx,pt[5].ry,pt[6].rx,pt[6].ry,thick);
drawLine(g,pt[6].rx,pt[6].ry,pt[7].rx,pt[7].ry,thick);
drawLine(g,pt[7].rx,pt[7].ry,pt[4].rx,pt[4].ry,thick);
// draw the vertical lines
drawLine(g,pt[0].rx,pt[0].ry,pt[4].rx,pt[4].ry,thick);
drawLine(g,pt[1].rx,pt[1].ry,pt[5].rx,pt[5].ry,thick);
drawLine(g,pt[2].rx,pt[2].ry,pt[6].rx,pt[6].ry,thick);
drawLine(g,pt[3].rx,pt[3].ry,pt[7].rx,pt[7].ry,thick);
g.setColor(tempcolor);
}
public void drawElement(GraphicsB3D g){
Color tempcolor=g.getColor();
g.setColor(color);
// draw the top square
g.drawLine(pt[0].rx,pt[0].ry,pt[1].rx,pt[1].ry,thick);
g.drawLine(pt[1].rx,pt[1].ry,pt[2].rx,pt[2].ry,thick);
g.drawLine(pt[2].rx,pt[2].ry,pt[3].rx,pt[3].ry,thick);
g.drawLine(pt[3].rx,pt[3].ry,pt[0].rx,pt[0].ry,thick);
// draw the bottom square
g.drawLine(pt[4].rx,pt[4].ry,pt[5].rx,pt[5].ry,thick);
g.drawLine(pt[5].rx,pt[5].ry,pt[6].rx,pt[6].ry,thick);
g.drawLine(pt[6].rx,pt[6].ry,pt[7].rx,pt[7].ry,thick);
g.drawLine(pt[7].rx,pt[7].ry,pt[4].rx,pt[4].ry,thick);
// draw the vertical lines
g.drawLine(pt[0].rx,pt[0].ry,pt[4].rx,pt[4].ry,thick);
g.drawLine(pt[1].rx,pt[1].ry,pt[5].rx,pt[5].ry,thick);
g.drawLine(pt[2].rx,pt[2].ry,pt[6].rx,pt[6].ry,thick);
g.drawLine(pt[3].rx,pt[3].ry,pt[7].rx,pt[7].ry,thick);
g.setColor(tempcolor);
}
}
| 5,235 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
Line3D.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/visual/visual3D/Line3D.java | /*******************************************************************************
* Copyright (c) 2013 Jay Unruh, Stowers Institute for Medical Research.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Public License v2.0
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
******************************************************************************/
package ezcol.visual.visual3D;
import java.awt.*;
public class Line3D extends Element3D{
public Point3D pt1,pt2;
// here we have a 3D line
public Line3D(int x11,int y11,int z11,int x21,int y21,int z21,Color color1){
pt1=new Point3D(x11,y11,z11);
pt2=new Point3D(x21,y21,z21);
color=color1;
}
public void moveto(int x,int y,int z){
int centerx=(int)(0.5f*(pt1.x+pt2.x));
int centery=(int)(0.5f*(pt1.y+pt2.y));
int centerz=(int)(0.5f*(pt1.z+pt2.z));
translate(x-centerx,y-centery,z-centerz);
pt1.reset();
pt2.reset();
}
public void translate(int transx,int transy,int transz){
pt1.translate(transx,transy,transz);
pt2.translate(transx,transy,transz);
}
public void rotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
pt1.rotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
pt2.rotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
public void rotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
pt1.rotaterad(radx1,rady1,radz1,centerx,centery,centerz);
pt2.rotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
public void rotatecossin(double cosx1,double cosy1,double cosz1,double sinx1,double siny1,double sinz1,int centerx,int centery,int centerz){
pt1.rotatecossin(cosx1,cosy1,cosz1,sinx1,siny1,sinz1,centerx,centery,centerz);
pt2.rotatecossin(cosx1,cosy1,cosz1,sinx1,siny1,sinz1,centerx,centery,centerz);
}
public void addrotatedeg(double degx1,double degy1,double degz1,int centerx,int centery,int centerz){
pt1.addrotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
pt2.addrotatedeg(degx1,degy1,degz1,centerx,centery,centerz);
}
public void addrotaterad(double radx1,double rady1,double radz1,int centerx,int centery,int centerz){
pt1.addrotaterad(radx1,rady1,radz1,centerx,centery,centerz);
pt2.addrotaterad(radx1,rady1,radz1,centerx,centery,centerz);
}
public void transform_perspective(double horizon_dist,int centerx,int centery,int centerz){
pt1.transform_perspective(horizon_dist,centerx,centery,centerz);
pt2.transform_perspective(horizon_dist,centerx,centery,centerz);
}
public void transform_negative_perspective(double horizon_dist,int centerx,int centery,int centerz){
pt1.transform_negative_perspective(horizon_dist,centerx,centery,centerz);
pt2.transform_negative_perspective(horizon_dist,centerx,centery,centerz);
}
public int getzpos(){
int zpos=(int)(0.5f*((float)pt1.rz+(float)pt2.rz));
return zpos;
}
public void drawelement(Graphics g){
Color tempcolor=g.getColor();
g.setColor(color);
drawLine(g,pt1.rx,pt1.ry,pt2.rx,pt2.ry,thick);
g.setColor(tempcolor);
}
public void drawElement(GraphicsB3D g){
Color tempcolor=g.getColor();
g.setColor(color);
g.drawLine(pt1.rx,pt1.ry,pt2.rx,pt2.ry,thick);
g.setColor(tempcolor);
}
}
| 3,328 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
TurboRegMod.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/align/TurboRegMod.java | package ezcol.align;
//Java 1.1
import java.awt.BorderLayout;
import java.awt.Button;
import java.awt.Canvas;
import java.awt.Checkbox;
import java.awt.CheckboxGroup;
import java.awt.Choice;
import java.awt.Color;
import java.awt.Component;
import java.awt.Container;
import java.awt.Dialog;
import java.awt.Event;
import java.awt.FileDialog;
import java.awt.FlowLayout;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.GridLayout;
import java.awt.Insets;
import java.awt.Label;
import java.awt.Panel;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.Scrollbar;
import java.awt.TextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.AdjustmentEvent;
import java.awt.event.AdjustmentListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.StreamTokenizer;
import java.io.StringReader;
import java.util.Stack;
import java.util.Vector;
/*====================================================================
| Version: July 7, 2011
\===================================================================*/
/*====================================================================
| Philippe Thevenaz
| EPFL/STI/IMT/LIB/BM.4.137
| Station 17
| CH-1015 Lausanne VD
| Switzerland
|
| phone (CET): +41(21)693.51.61
| fax: +41(21)693.37.01
| RFC-822: [email protected]
| X-400: /C=ch/A=400net/P=switch/O=epfl/S=thevenaz/G=philippe/
| URL: http://bigwww.epfl.ch/
\===================================================================*/
/*====================================================================
| This work is based on the following paper:
|
| P. Thevenaz, U.E. Ruttimann, M. Unser
| A Pyramid Approach to Subpixel Registration Based on Intensity
| IEEE Transactions on Image Processing
| vol. 7, no. 1, pp. 27-41, January 1998.
|
| This paper is available on-line at
| http://bigwww.epfl.ch/publications/thevenaz9801.html
|
| Other relevant on-line publications are available at
| http://bigwww.epfl.ch/publications/
\===================================================================*/
/*====================================================================
| Additional help available at http://bigwww.epfl.ch/thevenaz/turboreg/
|
| You'll be free to use this software for research purposes, but you
| should not redistribute it without our consent. In addition, we expect
| you to include a citation or acknowledgment whenever you present or
| publish results that are based on it.
\===================================================================*/
// ImageJ
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.Macro;
import ij.WindowManager;
import ij.gui.GUI;
import ij.gui.ImageCanvas;
import ij.gui.ImageWindow;
import ij.gui.PolygonRoi;
import ij.gui.StackWindow;
import ij.gui.Toolbar;
import ij.measure.Calibration;
import ij.measure.ResultsTable;
import ij.plugin.PlugIn;
import ij.plugin.filter.Analyzer;
import ij.process.FloatProcessor;
import ij.process.ImageConverter;
import ij.process.StackConverter;
import ezcol.debug.ExceptionHandler;
/*====================================================================
| TurboReg_
\===================================================================*/
/*********************************************************************
This class is the only one that is accessed directly by imageJ;
it launches a modeless dialog and dies. Note that it implements
<code>PlugIn</code> rather than <code>PlugInFilter</code>.
********************************************************************/
public class TurboRegMod
implements
PlugIn
{ /* class TurboReg_ */
/*....................................................................
private variables
....................................................................*/
private double[][] sourcePoints =
new double[turboRegPointHandler.NUM_POINTS][2];
private double[][] targetPoints =
new double[turboRegPointHandler.NUM_POINTS][2];
private ImagePlus transformedImage = null;
/*....................................................................
PlugIn methods
....................................................................*/
/*********************************************************************
This method is the only one called by ImageJ. It checks that there
are at least two grayscale images to register. If the command line
is empty, then the plugin is executed in interactive mode. Else, the
command line has the following syntax:
<br>
<br>
<table border="1">
<tr>
<th>command</th><th>parameter</th><th>index</th><th>comment</th>
</tr><tr>
<td>−help</td><td></td><td>00</td><td>prints out the syntax</td>
</tr><tr>
<td>−align</td><td></td><td>00</td><td>do refine the landmarks</td>
</tr><tr>
<td></td><td>−file<br>−window</td>
<td>01</td><td>reference type</td>
</tr><tr>
<td></td><td>sourceFilename<br>sourceWindowTitle</td><td>02</td>
<td>string with optional quotes</td>
</tr><tr>
<td></td><td>sourceCropLeft</td><td>03</td><td>integer</td>
</tr><tr>
<td></td><td>sourceCropTop</td><td>04</td><td>integer</td>
</tr><tr>
<td></td><td>sourceCropRight</td><td>05</td><td>integer</td>
</tr><tr>
<td></td><td>sourceCropBottom</td><td>06</td><td>integer</td>
</tr><tr>
<td></td><td>−file<br>−window</td><td>07</td>
<td>reference type</td>
</tr><tr>
<td></td><td>targetFilename<br>targetWindowTitle</td><td>08</td>
<td>string with optional quotes</td>
</tr><tr>
<td></td><td>targetCropLeft</td><td>09</td><td>integer</td>
</tr><tr>
<td></td><td>targetCropTop</td><td>10</td><td>integer</td>
</tr><tr>
<td></td><td>targetCropRight</td><td>11</td><td>integer</td>
</tr><tr>
<td></td><td>targetCropBottom</td><td>12</td><td>integer</td>
</tr><tr>
<td></td><td>−translation<br>−rigidBody<br>
−scaledRotation<br>−affine<br>−bilinear</td>
<td>13</td><td>transformation (TRSAB)</td>
</tr><tr>
<td></td><td>sourcePoints[0][0]</td><td>14</td><td>floating-point (TRSAB)</td>
</tr><tr>
<td></td><td>sourcePoints[0][1]</td><td>15</td><td>floating-point (TRSAB)</td>
</tr><tr>
<td></td><td>targetPoints[0][0]</td><td>16</td><td>floating-point (TRSAB)</td>
</tr><tr>
<td></td><td>targetPoints[0][1]</td><td>17</td><td>floating-point (TRSAB)</td>
</tr><tr>
<td></td><td>sourcePoints[1][0]</td><td>18</td><td>floating-point (RSAB)</td>
</tr><tr>
<td></td><td>sourcePoints[1][1]</td><td>19</td><td>floating-point (RSAB)</td>
</tr><tr>
<td></td><td>targetPoints[1][0]</td><td>20</td><td>floating-point (RSAB)</td>
</tr><tr>
<td></td><td>targetPoints[1][1]</td><td>21</td><td>floating-point (RSAB)</td>
</tr><tr>
<td></td><td>sourcePoints[2][0]</td><td>22</td><td>floating-point (RAB)</td>
</tr><tr>
<td></td><td>sourcePoints[2][1]</td><td>23</td><td>floating-point (RAB)</td>
</tr><tr>
<td></td><td>targetPoints[2][0]</td><td>24</td><td>floating-point (RAB)</td>
</tr><tr>
<td></td><td>targetPoints[2][1]</td><td>25</td><td>floating-point (RAB)</td>
</tr><tr>
<td></td><td>sourcePoints[3][0]</td><td>26</td><td>floating-point (B)</td>
</tr><tr>
<td></td><td>sourcePoints[3][1]</td><td>27</td><td>floating-point (B)</td>
</tr><tr>
<td></td><td>targetPoints[3][0]</td><td>28</td><td>floating-point (B)</td>
</tr><tr>
<td></td><td>targetPoints[3][1]</td><td>29</td><td>floating-point (B)</td>
</tr><tr>
<td></td><td>−hideOutput<br>−showOutput</td><td>18 (T)<br>
22 (S)<br>26 (RA)<br>30 (B)</td><td></td>
</tr><tr>
<td>−transform</td><td></td>
<td>00</td><td>do not refine the landmarks</td>
</tr><tr>
<td></td><td>−file<br>−window</td><td>01</td>
<td>reference type</td>
</tr><tr>
<td></td><td>sourceFilename<br>sourceWindowTitle</td><td>02</td>
<td>string with optional quotes</td>
</tr><tr>
<td></td><td>outputWidth</td><td>03</td><td>integer</td>
</tr><tr>
<td></td><td>outputHeight</td><td>04</td><td>integer</td>
</tr><tr>
<td></td><td>−translation<br>−rigidBody<br>
−scaledRotation<br>
−affine<br>−bilinear</td><td>05</td><td>transformation (TRSAB)</td>
</tr><tr>
<td></td><td>sourcePoints[0][0]</td><td>06</td><td>floating-point (TRSAB)</td>
</tr><tr>
<td></td><td>sourcePoints[0][1]</td><td>07</td><td>floating-point (TRSAB)</td>
</tr><tr>
<td></td><td>targetPoints[0][0]</td><td>08</td><td>floating-point (TRSAB)</td>
</tr><tr>
<td></td><td>targetPoints[0][1]</td><td>09</td><td>floating-point (TRSAB)</td>
</tr><tr>
<td></td><td>sourcePoints[1][0]</td><td>10</td><td>floating-point (RSAB)</td>
</tr><tr>
<td></td><td>sourcePoints[1][1]</td><td>11</td><td>floating-point (RSAB)</td>
</tr><tr>
<td></td><td>targetPoints[1][0]</td><td>12</td><td>floating-point (RSAB)</td>
</tr><tr>
<td></td><td>targetPoints[1][1]</td><td>13</td><td>floating-point (RSAB)</td>
</tr><tr>
<td></td><td>sourcePoints[2][0]</td><td>14</td><td>floating-point (RAB)</td>
</tr><tr>
<td></td><td>sourcePoints[2][1]</td><td>15</td><td>floating-point (RAB)</td>
</tr><tr>
<td></td><td>targetPoints[2][0]</td><td>16</td><td>floating-point (RAB)</td>
</tr><tr>
<td></td><td>targetPoints[2][1]</td><td>17</td><td>floating-point (RAB)</td>
</tr><tr>
<td></td><td>sourcePoints[3][0]</td><td>18</td><td>floating-point (B)</td>
</tr><tr>
<td></td><td>sourcePoints[3][1]</td><td>19</td><td>floating-point (B)</td>
</tr><tr>
<td></td><td>targetPoints[3][0]</td><td>20</td><td>floating-point (B)</td>
</tr><tr>
<td></td><td>targetPoints[3][1]</td><td>21</td><td>floating-point (B)</td>
</tr><tr>
<td></td><td>−hideOutput<br>−showOutput</td><td>10 (T)<br>
14 (S)<br>18 (RA)<br>22 (B)</td><td></td>
</tr>
</table>
<br>
Example: The command line
<br>
<code>−align −file path/source.tif 40 80 639 479
−file path/target.tif 0 0 639 479
−translation 320 240 331.7 210 −showOutput</code>
<br>
aligns 'source.tif' to 'target.tif' by translation, by refining an
initial horizontal offset
<br>
<i>dx</i> = (331.7 − 320) = 11.7
<br>
and an initial vertical offset
<br>
<i>dy</i> = (210 − 240) = −30
<br>
The effective size of 'source.tif' is 600 x 400. The effective size
of 'target.tif' is 640 x 480. The source and target points are given
in relation to the original (uncropped) system of coordinates. The
resulting output will be displayed.
<br>
<div style="color:red">IMPORTANT: You MUST use a pair of double quotes
to enclose paths and filenames that contain white characters. Example:
<code>"my path/my file"</code>. Escape characters (<i>e.g.</i>, a
backslash) are not interpreted.</div>
@param commandLine <code>String</code> optional list of parameters.
********************************************************************/
public void run (
final String commandLine
) {
String options = Macro.getOptions();
if (!commandLine.equals("")) {
options = commandLine;
}
if (options == null) {
Runtime.getRuntime().gc();
final ImagePlus[] admissibleImageList = createAdmissibleImageList();
if (admissibleImageList.length < 2) {
ExceptionHandler.addError(Thread.currentThread(),
"At least two grayscale or RGB-stack images are required");
return;
}
final turboRegDialog dialog = new turboRegDialog(IJ.getInstance(),
admissibleImageList);
GUI.center(dialog);
dialog.setVisible(true);
}
else {
final String[] token = getTokens(options);
if (token.length < 1) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid syntax");
return;
}
if (token[0].equals("-help")) {
dumpSyntax(options);
return;
}
else if (token[0].equals("-align")) {
switch (token.length) {
case 19:
case 23:
case 27:
case 31: {
break;
}
default: {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid syntax");
return;
}
}
ImagePlus source = null;
final int[] sourceCrop = new int[4];
ImagePlus target = null;
final int[] targetCrop = new int[4];
int transformation = turboRegDialog.GENERIC_TRANSFORMATION;
Boolean interactive = null;
try {
if (token[1].equals("-file")) {
source = new ImagePlus(token[2]);
}
else if (token[1].equals("-window")) {
final int[] IDlist = WindowManager.getIDList();
if (IDlist == null) {
source = null;
}
else {
for (int k = 0; (k < IDlist.length); k++) {
source = WindowManager.getImage(IDlist[k]);
if (source.getTitle().equals(token[2])) {
break;
}
else {
source = null;
}
}
}
}
else {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid reference type: " + token[1]);
return;
}
if (source == null) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid source: " + token[2]);
return;
}
for (int i = 0; (i < 4); i++) {
sourceCrop[i] = new Integer(token[i + 3]).intValue();
}
if (token[7].equals("-file")) {
target = new ImagePlus(token[8]);
}
else if (token[7].equals("-window")) {
final int[] IDlist = WindowManager.getIDList();
if (IDlist == null) {
target = null;
}
else {
for (int k = 0; (k < IDlist.length); k++) {
target = WindowManager.getImage(IDlist[k]);
if (target.getTitle().equals(token[8])) {
break;
}
else {
target = null;
}
}
}
}
else {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid reference type: " + token[7]);
return;
}
if (target == null) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid target: " + token[8]);
return;
}
for (int i = 0; (i < 4); i++) {
targetCrop[i] = new Integer(token[i + 9]).intValue();
}
transformation = getTransformation(token[13]);
switch (transformation) {
case turboRegDialog.TRANSLATION: {
if (token.length != 19) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid number of source and target points");
return;
}
sourcePoints[0][0] =
new Double(token[14]).doubleValue();
sourcePoints[0][1] =
new Double(token[15]).doubleValue();
targetPoints[0][0] =
new Double(token[16]).doubleValue();
targetPoints[0][1] =
new Double(token[17]).doubleValue();
interactive = getInteractive(token[18]);
break;
}
case turboRegDialog.SCALED_ROTATION: {
if (token.length != 23) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid number of source and target points");
return;
}
sourcePoints[0][0] =
new Double(token[14]).doubleValue();
sourcePoints[0][1] =
new Double(token[15]).doubleValue();
targetPoints[0][0] =
new Double(token[16]).doubleValue();
targetPoints[0][1] =
new Double(token[17]).doubleValue();
sourcePoints[1][0] =
new Double(token[18]).doubleValue();
sourcePoints[1][1] =
new Double(token[19]).doubleValue();
targetPoints[1][0] =
new Double(token[20]).doubleValue();
targetPoints[1][1] =
new Double(token[21]).doubleValue();
interactive = getInteractive(token[22]);
break;
}
case turboRegDialog.RIGID_BODY:
case turboRegDialog.AFFINE: {
if (token.length != 27) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid number of source and target points");
return;
}
sourcePoints[0][0] =
new Double(token[14]).doubleValue();
sourcePoints[0][1] =
new Double(token[15]).doubleValue();
targetPoints[0][0] =
new Double(token[16]).doubleValue();
targetPoints[0][1] =
new Double(token[17]).doubleValue();
sourcePoints[1][0] =
new Double(token[18]).doubleValue();
sourcePoints[1][1] =
new Double(token[19]).doubleValue();
targetPoints[1][0] =
new Double(token[20]).doubleValue();
targetPoints[1][1] =
new Double(token[21]).doubleValue();
sourcePoints[2][0] =
new Double(token[22]).doubleValue();
sourcePoints[2][1] =
new Double(token[23]).doubleValue();
targetPoints[2][0] =
new Double(token[24]).doubleValue();
targetPoints[2][1] =
new Double(token[25]).doubleValue();
interactive = getInteractive(token[26]);
break;
}
case turboRegDialog.BILINEAR: {
if (token.length != 31) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid number of source and target points");
return;
}
sourcePoints[0][0] =
new Double(token[14]).doubleValue();
sourcePoints[0][1] =
new Double(token[15]).doubleValue();
targetPoints[0][0] =
new Double(token[16]).doubleValue();
targetPoints[0][1] =
new Double(token[17]).doubleValue();
sourcePoints[1][0] =
new Double(token[18]).doubleValue();
sourcePoints[1][1] =
new Double(token[19]).doubleValue();
targetPoints[1][0] =
new Double(token[20]).doubleValue();
targetPoints[1][1] =
new Double(token[21]).doubleValue();
sourcePoints[2][0] =
new Double(token[22]).doubleValue();
sourcePoints[2][1] =
new Double(token[23]).doubleValue();
targetPoints[2][0] =
new Double(token[24]).doubleValue();
targetPoints[2][1] =
new Double(token[25]).doubleValue();
sourcePoints[3][0] =
new Double(token[26]).doubleValue();
sourcePoints[3][1] =
new Double(token[27]).doubleValue();
targetPoints[3][0] =
new Double(token[28]).doubleValue();
targetPoints[3][1] =
new Double(token[29]).doubleValue();
interactive = getInteractive(token[30]);
break;
}
default: {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid transformation");
return;
}
}
} catch (NumberFormatException e) {
dumpSyntax(options);
IJ.log(
"Number format exception " + e.getMessage());
ExceptionHandler.addError(Thread.currentThread(),
"Invalid syntax");
return;
}
if (interactive == null) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid directive for interactivity");
return;
}
transformedImage = alignImages(source, sourceCrop,
target, targetCrop,
transformation, interactive.booleanValue());
}
else if (token[0].equals("-transform")) {
switch (token.length) {
case 11:
case 15:
case 19:
case 23: {
break;
}
default: {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid syntax");
return;
}
}
ImagePlus source = null;
int outputWidth = -1;
int outputHeight = -1;
int transformation = turboRegDialog.GENERIC_TRANSFORMATION;
Boolean interactive = null;
try {
if (token[1].equals("-file")) {
source = new ImagePlus(token[2]);
}
else if (token[1].equals("-window")) {
final int[] IDlist = WindowManager.getIDList();
for (int k = 0; (k < IDlist.length); k++) {
source = WindowManager.getImage(IDlist[k]);
if (source.getTitle().equals(token[2])) {
break;
}
else {
source = null;
}
}
}
else {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid reference type: " + token[1]);
return;
}
if (source == null) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid source: " + token[2]);
return;
}
outputWidth = new Integer(token[3]).intValue();
if (outputWidth <= 0) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid output width: " + token[3]);
return;
}
outputHeight = new Integer(token[4]).intValue();
if (outputHeight <= 0) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid output height: " + token[4]);
return;
}
transformation = getTransformation(token[5]);
switch (transformation) {
case turboRegDialog.TRANSLATION: {
if (token.length != 11) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid number of source and target points");
return;
}
sourcePoints[0][0] =
new Double(token[6]).doubleValue();
sourcePoints[0][1] =
new Double(token[7]).doubleValue();
targetPoints[0][0] =
new Double(token[8]).doubleValue();
targetPoints[0][1] =
new Double(token[9]).doubleValue();
interactive = getInteractive(token[10]);
break;
}
case turboRegDialog.SCALED_ROTATION: {
if (token.length != 15) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid number of source and target points");
return;
}
sourcePoints[0][0] =
new Double(token[6]).doubleValue();
sourcePoints[0][1] =
new Double(token[7]).doubleValue();
targetPoints[0][0] =
new Double(token[8]).doubleValue();
targetPoints[0][1] =
new Double(token[9]).doubleValue();
sourcePoints[1][0] =
new Double(token[10]).doubleValue();
sourcePoints[1][1] =
new Double(token[11]).doubleValue();
targetPoints[1][0] =
new Double(token[12]).doubleValue();
targetPoints[1][1] =
new Double(token[13]).doubleValue();
interactive = getInteractive(token[14]);
break;
}
case turboRegDialog.RIGID_BODY:
case turboRegDialog.AFFINE: {
if (token.length != 19) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid number of source and target points");
return;
}
sourcePoints[0][0] =
new Double(token[6]).doubleValue();
sourcePoints[0][1] =
new Double(token[7]).doubleValue();
targetPoints[0][0] =
new Double(token[8]).doubleValue();
targetPoints[0][1] =
new Double(token[9]).doubleValue();
sourcePoints[1][0] =
new Double(token[10]).doubleValue();
sourcePoints[1][1] =
new Double(token[11]).doubleValue();
targetPoints[1][0] =
new Double(token[12]).doubleValue();
targetPoints[1][1] =
new Double(token[13]).doubleValue();
sourcePoints[2][0] =
new Double(token[14]).doubleValue();
sourcePoints[2][1] =
new Double(token[15]).doubleValue();
targetPoints[2][0] =
new Double(token[16]).doubleValue();
targetPoints[2][1] =
new Double(token[17]).doubleValue();
interactive = getInteractive(token[18]);
break;
}
case turboRegDialog.BILINEAR: {
if (token.length != 23) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid number of source and target points");
return;
}
sourcePoints[0][0] =
new Double(token[6]).doubleValue();
sourcePoints[0][1] =
new Double(token[7]).doubleValue();
targetPoints[0][0] =
new Double(token[8]).doubleValue();
targetPoints[0][1] =
new Double(token[9]).doubleValue();
sourcePoints[1][0] =
new Double(token[10]).doubleValue();
sourcePoints[1][1] =
new Double(token[11]).doubleValue();
targetPoints[1][0] =
new Double(token[12]).doubleValue();
targetPoints[1][1] =
new Double(token[13]).doubleValue();
sourcePoints[2][0] =
new Double(token[14]).doubleValue();
sourcePoints[2][1] =
new Double(token[15]).doubleValue();
targetPoints[2][0] =
new Double(token[16]).doubleValue();
targetPoints[2][1] =
new Double(token[17]).doubleValue();
sourcePoints[3][0] =
new Double(token[18]).doubleValue();
sourcePoints[3][1] =
new Double(token[19]).doubleValue();
targetPoints[3][0] =
new Double(token[20]).doubleValue();
targetPoints[3][1] =
new Double(token[21]).doubleValue();
interactive = getInteractive(token[22]);
break;
}
default: {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid transformation");
return;
}
}
} catch (NumberFormatException e) {
dumpSyntax(options);
IJ.log(
"Number format exception " + e.getMessage());
ExceptionHandler.addError(Thread.currentThread(),
"Invalid syntax");
return;
}
if (interactive == null) {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid directive for interactivity");
return;
}
transformedImage = transformImage(source, outputWidth, outputHeight,
transformation, interactive.booleanValue());
}
else {
dumpSyntax(options);
ExceptionHandler.addError(Thread.currentThread(),
"Invalid operation");
return;
}
}
} /* end run */
/*....................................................................
public methods
....................................................................*/
/*********************************************************************
Accessor method for the <code>(double[][])sourcePoints</code> variable.
This variable is valid only after a call to <code>run</code> with the
option <code>-align</code> has been issued. What is returned is a
two-dimensional array of type <code>double[][]</code> that contains
coordinates from the image <code>sourceFilename</code>. These coordinates
are given relative to the original image, before that the cropping
described by the <code>sourceCropLeft</code>, <code>sourceCropTop</code>,
<code>sourceCropRight</code>, and <code>sourceCropBottom</code> has been
applied. These coordinates match those available from
<code>targetPoints</code>. The total number of coordinates, equal to
<code>sourcePoints[*].length</code>, is given by the constant
<code>turboRegPointHandler.NUM_POINTS</code> which corresponds to four
coordinates in the present version. The second index gives the horizontal
component for <code>[0]</code> and the vertical component for
<code>[1]</code>. The number of <i>useful</i> coordinates depends on the
specific transformation for which the alignment has been performed:
translation (1), scaled rotation (2), rotation (3), affine transformation
(3), and bilinear transformation (4).
@see TurboReg_#run
@see TurboReg_#getTargetPoints
********************************************************************/
public double[][] getSourcePoints (
) {
return(sourcePoints);
} /* end getSourcePoints */
/*********************************************************************
Accessor method for the <code>(double[][])targetPoints</code> variable.
This variable is valid only after a call to <code>run</code> with the
option <code>-align</code> has been issued. What is returned is a
two-dimensional array of type <code>double[][]</code> that contains
coordinates from the image <code>targetFilename</code>. These coordinates
are given relative to the original image, before that the cropping
described by the <code>targetCropLeft</code>, <code>targetCropTop</code>,
<code>targetCropRight</code>, and <code>targetCropBottom</code> has been
applied. These coordinates match those available from
<code>sourcePoints</code>. The total number of coordinates, equal to
<code>targetPoints[*].length</code>, is given by the constant
<code>turboRegPointHandler.NUM_POINTS</code> which corresponds to four
coordinates in the present version. The second index gives the horizontal
component for <code>[0]</code> and the vertical component for
<code>[1]</code>. The number of <i>useful</i> coordinates depends on the
specific transformation for which the alignment has been performed:
translation (1), scaled rotation (2), rotation (3), affine transformation
(3), and bilinear transformation (4).
@see TurboReg_#run
@see TurboReg_#getSourcePoints
********************************************************************/
public double[][] getTargetPoints (
) {
return(targetPoints);
} /* end getTargetPoints */
/*********************************************************************
Accessor method for the <code>(ImagePlus)transformedImage</code>
variable. This variable is valid only after a call to <code>run</code>
with the option <code>-transform</code> has been issued. What is returned
is an <code>ImagePlus</code> object of the size described by the
<code>outputWidth</code> and <code>outputHeight</code> parameters of
the call to the <code>run</code> method of <code>TurboReg_</code>.
@see TurboReg_#run
********************************************************************/
public ImagePlus getTransformedImage (
) {
return(transformedImage);
} /* end getTransformedImage */
/*....................................................................
private methods
....................................................................*/
/*------------------------------------------------------------------*/
private ImagePlus alignImages (
final ImagePlus source,
final int[] sourceCrop,
final ImagePlus target,
final int[] targetCrop,
final int transformation,
final boolean interactive
) {
if ((source.getType() != ImagePlus.GRAY16)
&& (source.getType() != ImagePlus.GRAY32)
&& ((source.getType() != ImagePlus.GRAY8)
|| source.getStack().isRGB() || source.getStack().isHSB())) {
ExceptionHandler.addError(Thread.currentThread(),
source.getTitle() + " should be grayscale (8, 16, or 32 bit)");
return(null);
}
if ((target.getType() != ImagePlus.GRAY16)
&& (target.getType() != ImagePlus.GRAY32)
&& ((target.getType() != ImagePlus.GRAY8)
|| target.getStack().isRGB() || target.getStack().isHSB())) {
ExceptionHandler.addError(Thread.currentThread(),
target.getTitle() + " should be grayscale (8, 16, or 32 bit)");
return(null);
}
source.setRoi(sourceCrop[0], sourceCrop[1], sourceCrop[2], sourceCrop[3]);
target.setRoi(targetCrop[0], targetCrop[1], targetCrop[2], targetCrop[3]);
source.setSlice(1);
target.setSlice(1);
final ImagePlus sourceImp = new ImagePlus("source",
source.getProcessor().crop());
final ImagePlus targetImp = new ImagePlus("target",
target.getProcessor().crop());
final turboRegImage sourceImg = new turboRegImage(
sourceImp, transformation, false);
final turboRegImage targetImg = new turboRegImage(
targetImp, transformation, true);
final int pyramidDepth = getPyramidDepth(
sourceImp.getWidth(), sourceImp.getHeight(),
targetImp.getWidth(), targetImp.getHeight());
sourceImg.setPyramidDepth(pyramidDepth);
targetImg.setPyramidDepth(pyramidDepth);
sourceImg.getThread().start();
targetImg.getThread().start();
if (2 <= source.getStackSize()) {
source.setSlice(2);
}
if (2 <= target.getStackSize()) {
target.setSlice(2);
}
final ImagePlus sourceMskImp = new ImagePlus("source mask",
source.getProcessor().crop());
final ImagePlus targetMskImp = new ImagePlus("target mask",
target.getProcessor().crop());
final turboRegMask sourceMsk = new turboRegMask(sourceMskImp);
final turboRegMask targetMsk = new turboRegMask(targetMskImp);
source.setSlice(1);
target.setSlice(1);
if (source.getStackSize() < 2) {
sourceMsk.clearMask();
}
if (target.getStackSize() < 2) {
targetMsk.clearMask();
}
sourceMsk.setPyramidDepth(pyramidDepth);
targetMsk.setPyramidDepth(pyramidDepth);
sourceMsk.getThread().start();
targetMsk.getThread().start();
switch (transformation) {
case turboRegDialog.TRANSLATION: {
sourcePoints[0][0] -= sourceCrop[0];
sourcePoints[0][1] -= sourceCrop[1];
targetPoints[0][0] -= targetCrop[0];
targetPoints[0][1] -= targetCrop[1];
break;
}
case turboRegDialog.SCALED_ROTATION: {
for (int k = 0; (k < 2); k++) {
sourcePoints[k][0] -= sourceCrop[0];
sourcePoints[k][1] -= sourceCrop[1];
targetPoints[k][0] -= targetCrop[0];
targetPoints[k][1] -= targetCrop[1];
}
break;
}
case turboRegDialog.RIGID_BODY:
case turboRegDialog.AFFINE: {
for (int k = 0; (k < 3); k++) {
sourcePoints[k][0] -= sourceCrop[0];
sourcePoints[k][1] -= sourceCrop[1];
targetPoints[k][0] -= targetCrop[0];
targetPoints[k][1] -= targetCrop[1];
}
break;
}
case turboRegDialog.BILINEAR: {
for (int k = 0; (k < 4); k++) {
sourcePoints[k][0] -= sourceCrop[0];
sourcePoints[k][1] -= sourceCrop[1];
targetPoints[k][0] -= targetCrop[0];
targetPoints[k][1] -= targetCrop[1];
}
break;
}
}
final turboRegPointHandler sourcePh = (null == sourceImp.getWindow())
? (new turboRegPointHandler(transformation, sourceImp))
: (new turboRegPointHandler(sourceImp, transformation));
final turboRegPointHandler targetPh = (null == sourceImp.getWindow())
? (new turboRegPointHandler(transformation, targetImp))
: (new turboRegPointHandler(targetImp, transformation));
sourcePh.setPoints(sourcePoints);
targetPh.setPoints(targetPoints);
try {
sourceMsk.getThread().join();
targetMsk.getThread().join();
sourceImg.getThread().join();
targetImg.getThread().join();
} catch (InterruptedException e) {
IJ.log(
"Unexpected interruption exception " + e.getMessage());
}
final turboRegFinalAction finalAction = new turboRegFinalAction(
sourceImg, sourceMsk, sourcePh,
targetImg, targetMsk, targetPh, transformation);
finalAction.getThread().start();
try {
finalAction.getThread().join();
} catch (InterruptedException e) {
IJ.log(
"Unexpected interruption exception " + e.getMessage());
}
sourcePoints = sourcePh.getPoints();
targetPoints = targetPh.getPoints();
final ResultsTable table = Analyzer.getResultsTable();
table.reset();
switch (transformation) {
case turboRegDialog.TRANSLATION: {
table.incrementCounter();
sourcePoints[0][0] += sourceCrop[0];
table.addValue("sourceX", sourcePoints[0][0]);
sourcePoints[0][1] += sourceCrop[1];
table.addValue("sourceY", sourcePoints[0][1]);
targetPoints[0][0] += targetCrop[0];
table.addValue("targetX", targetPoints[0][0]);
targetPoints[0][1] += targetCrop[1];
table.addValue("targetY", targetPoints[0][1]);
break;
}
case turboRegDialog.SCALED_ROTATION: {
for (int k = 0; (k < 2); k++) {
table.incrementCounter();
sourcePoints[k][0] += sourceCrop[0];
table.addValue("sourceX", sourcePoints[k][0]);
sourcePoints[k][1] += sourceCrop[1];
table.addValue("sourceY", sourcePoints[k][1]);
targetPoints[k][0] += targetCrop[0];
table.addValue("targetX", targetPoints[k][0]);
targetPoints[k][1] += targetCrop[1];
table.addValue("targetY", targetPoints[k][1]);
}
break;
}
case turboRegDialog.RIGID_BODY:
case turboRegDialog.AFFINE: {
for (int k = 0; (k < 3); k++) {
table.incrementCounter();
sourcePoints[k][0] += sourceCrop[0];
table.addValue("sourceX", sourcePoints[k][0]);
sourcePoints[k][1] += sourceCrop[1];
table.addValue("sourceY", sourcePoints[k][1]);
targetPoints[k][0] += targetCrop[0];
table.addValue("targetX", targetPoints[k][0]);
targetPoints[k][1] += targetCrop[1];
table.addValue("targetY", targetPoints[k][1]);
}
break;
}
case turboRegDialog.BILINEAR: {
for (int k = 0; (k < 4); k++) {
table.incrementCounter();
sourcePoints[k][0] += sourceCrop[0];
table.addValue("sourceX", sourcePoints[k][0]);
sourcePoints[k][1] += sourceCrop[1];
table.addValue("sourceY", sourcePoints[k][1]);
targetPoints[k][0] += targetCrop[0];
table.addValue("targetX", targetPoints[k][0]);
targetPoints[k][1] += targetCrop[1];
table.addValue("targetY", targetPoints[k][1]);
}
break;
}
}
if (interactive) {
table.show("Results");
}
source.killRoi();
target.killRoi();
return(transformImage(source, target.getWidth(), target.getHeight(),
transformation, interactive));
} /* end alignImages */
/*------------------------------------------------------------------*/
private ImagePlus[] createAdmissibleImageList (
) {
final int[] windowList = WindowManager.getIDList();
final Stack<ImagePlus> stack = new Stack<ImagePlus>();
for (int k = 0; ((windowList != null) && (k < windowList.length)); k++) {
final ImagePlus imp = WindowManager.getImage(windowList[k]);
if ((imp != null) && ((imp.getType() == ImagePlus.GRAY16)
|| (imp.getType() == ImagePlus.GRAY32)
|| ((imp.getType() == ImagePlus.GRAY8)
&& !imp.getStack().isHSB()))) {
stack.push(imp);
}
}
final ImagePlus[] admissibleImageList = new ImagePlus[stack.size()];
int k = 0;
while (!stack.isEmpty()) {
admissibleImageList[k++] = stack.pop();
}
return(admissibleImageList);
} /* end createAdmissibleImageList */
/*------------------------------------------------------------------*/
private void dumpSyntax (
final String options
) {
IJ.log(options);
IJ.log("");
IJ.log("___");
IJ.log("");
IJ.log("ARGUMENTS: { -help | -align | -transform }");
IJ.log("");
IJ.log("-help SHOWS THIS MESSAGE");
IJ.log("");
IJ.log("-align");
IJ.log("{ -file | -window }");
IJ.log(" sourceFilename STRING WITH OPTIONAL QUOTES");
IJ.log(" sourceWindowTitle STRING WITH OPTIONAL QUOTES");
IJ.log("sourceCropLeft INTEGER");
IJ.log("sourceCropTop INTEGER");
IJ.log("sourceCropRight INTEGER");
IJ.log("sourceCropBottom INTEGER");
IJ.log("{ -file | -window }");
IJ.log(" targetFilename STRING WITH OPTIONAL QUOTES");
IJ.log(" targetWindowTitle STRING WITH OPTIONAL QUOTES");
IJ.log("targetCropLeft INTEGER");
IJ.log("targetCropTop INTEGER");
IJ.log("targetCropRight INTEGER");
IJ.log("targetCropBottom INTEGER");
IJ.log(
"{ -translation | -rigidBody | -scaledRotation | -affine | -bilinear }");
IJ.log("sourcePointsX[<*>] FLOATING-POINT");
IJ.log("sourcePointsY[<*>] FLOATING-POINT");
IJ.log("targetPointsX[<*>] FLOATING-POINT");
IJ.log("targetPointsY[<*>] FLOATING-POINT");
IJ.log("{ -hideOutput | -showOutput }");
IJ.log("");
IJ.log("-transform");
IJ.log("{ -file | -window }");
IJ.log(" sourceFilename STRING WITH OPTIONAL QUOTES");
IJ.log(" sourceWindowTitle STRING WITH OPTIONAL QUOTES");
IJ.log("outputWidth INTEGER");
IJ.log("outputHeight INTEGER");
IJ.log(
"{ -translation | -rigidBody | -scaledRotation | -affine | -bilinear }");
IJ.log("sourcePointsX[<*>] FLOATING-POINT");
IJ.log("sourcePointsY[<*>] FLOATING-POINT");
IJ.log("targetPointsX[<*>] FLOATING-POINT");
IJ.log("targetPointsY[<*>] FLOATING-POINT");
IJ.log("{ -hideOutput | -showOutput }");
IJ.log("");
IJ.log("<*> FOR TRANSLATION: 1 BLOCK OF FOUR COORDINATES");
IJ.log("<*> FOR RIGID-BODY: 3 BLOCKS OF FOUR COORDINATES");
IJ.log("<*> FOR SCALED-ROTATION: 2 BLOCKS OF FOUR COORDINATES");
IJ.log("<*> FOR AFFINE: 3 BLOCKS OF FOUR COORDINATES");
IJ.log("<*> FOR BILINEAR: 4 BLOCKS OF FOUR COORDINATES");
IJ.log("");
IJ.log("~~~");
} /* end dumpSyntax */
/*------------------------------------------------------------------*/
private Boolean getInteractive (
final String token
) {
if (token.equals("-hideOutput")) {
return(new Boolean(false));
}
else if (token.equals("-showOutput")) {
return(new Boolean(true));
}
else {
return(null);
}
} /* end getInteractive */
/*------------------------------------------------------------------*/
private int getPyramidDepth (
int sw,
int sh,
int tw,
int th
) {
int pyramidDepth = 1;
while (((2 * turboRegDialog.MIN_SIZE) <= sw)
&& ((2 * turboRegDialog.MIN_SIZE) <= sh)
&& ((2 * turboRegDialog.MIN_SIZE) <= tw)
&& ((2 * turboRegDialog.MIN_SIZE) <= th)) {
sw /= 2;
sh /= 2;
tw /= 2;
th /= 2;
pyramidDepth++;
}
return(pyramidDepth);
} /* end getPyramidDepth */
/*------------------------------------------------------------------*/
private String[] getTokens (
String options
) {
final String fileSeparator = System.getProperty("file.separator");
if (fileSeparator.equals("\\")) {
options = options.replaceAll("\\\\", "/");
}
else {
options = options.replaceAll(fileSeparator, "/");
}
String[] token = new String[0];
final StringReader sr = new StringReader(options);
final StreamTokenizer st = new StreamTokenizer(sr);
st.resetSyntax();
st.whitespaceChars(0, ' ');
st.wordChars('!', 255);
st.quoteChar('\"');
final Vector<String> v = new Vector<String>();
try {
while (st.nextToken() != StreamTokenizer.TT_EOF) {
v.add(new String(st.sval));
}
} catch (IOException e) {
IJ.log(
"IOException exception " + e.getMessage());
return(token);
}
token = v.toArray(token);
return(token);
} /* end getTokens */
/*------------------------------------------------------------------*/
private int getTransformation (
final String token
) {
if (token.equals("-translation")) {
return(turboRegDialog.TRANSLATION);
}
else if (token.equals("-rigidBody")) {
return(turboRegDialog.RIGID_BODY);
}
else if (token.equals("-scaledRotation")) {
return(turboRegDialog.SCALED_ROTATION);
}
else if (token.equals("-affine")) {
return(turboRegDialog.AFFINE);
}
else if (token.equals("-bilinear")) {
return(turboRegDialog.BILINEAR);
}
else {
return(turboRegDialog.GENERIC_TRANSFORMATION);
}
} /* end getTransformation */
/*------------------------------------------------------------------*/
private ImagePlus transformImage (
final ImagePlus source,
final int width,
final int height,
final int transformation,
final boolean interactive
) {
if ((source.getType() != ImagePlus.GRAY16)
&& (source.getType() != ImagePlus.GRAY32)
&& ((source.getType() != ImagePlus.GRAY8)
|| source.getStack().isRGB() || source.getStack().isHSB())) {
ExceptionHandler.addError(Thread.currentThread(),
source.getTitle() + " should be grayscale (8, 16, or 32 bit)");
return(null);
}
source.setSlice(1);
final turboRegImage sourceImg = new turboRegImage(source,
turboRegDialog.GENERIC_TRANSFORMATION, false);
sourceImg.getThread().start();
if (2 <= source.getStackSize()) {
source.setSlice(2);
}
final turboRegMask sourceMsk = new turboRegMask(source);
source.setSlice(1);
if (source.getStackSize() < 2) {
sourceMsk.clearMask();
}
final turboRegPointHandler sourcePh = new turboRegPointHandler(
sourcePoints, transformation);
final turboRegPointHandler targetPh = new turboRegPointHandler(
targetPoints, transformation);
try {
sourceImg.getThread().join();
} catch (InterruptedException e) {
IJ.log(
"Unexpected interruption exception " + e.getMessage());
}
final turboRegTransform regTransform = new turboRegTransform(
sourceImg, sourceMsk, sourcePh,
null, null, targetPh, transformation, false, false);
final ImagePlus transformedImage = regTransform.doFinalTransform(
width, height);
if (interactive) {
transformedImage.setSlice(1);
transformedImage.getProcessor().resetMinAndMax();
transformedImage.show();
transformedImage.updateAndDraw();
}
return(transformedImage);
} /* end transformImage */
} /* end class TurboReg_ */
/*====================================================================
| turboRegCredits
\===================================================================*/
/*********************************************************************
This class creates the credits dialog.
********************************************************************/
class turboRegCredits
extends
Dialog
{ /* class turboRegCredits */
/*....................................................................
private variables
....................................................................*/
private static final long serialVersionUID = 1L;
/*....................................................................
Container methods
....................................................................*/
/*********************************************************************
Return some additional margin to the dialog, for aesthetic purposes.
Necessary for the current MacOS X Java version, lest the first item
disappears from the frame.
********************************************************************/
public Insets getInsets (
) {
return(new Insets(0, 20, 20, 20));
} /* end getInsets */
/*....................................................................
constructors
....................................................................*/
/*********************************************************************
This constructor prepares the dialog box.
@param parentWindow Parent window.
********************************************************************/
public turboRegCredits (
final Frame parentWindow
) {
super(parentWindow, "TurboReg", true);
setLayout(new BorderLayout(0, 20));
final Label separation = new Label("");
final Panel buttonPanel = new Panel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
final Button doneButton = new Button("Done");
doneButton.addActionListener(
new ActionListener (
) {
public void actionPerformed (
final ActionEvent ae
) {
if (ae.getActionCommand().equals("Done")) {
dispose();
}
}
}
);
buttonPanel.add(doneButton);
final TextArea text = new TextArea(26, 72);
text.setEditable(false);
text.append(
" \n");
text.append(
" This TurboReg version is dated July 7, 2011\n");
text.append(
" \n");
text.append(
" ###\n");
text.append(
" \n");
text.append(
" This work is based on the following paper:\n");
text.append(
"\n");
text.append(
" P. Th\u00E9venaz, U.E. Ruttimann, M. Unser\n");
text.append(
" A Pyramid Approach to Subpixel Registration Based on Intensity\n");
text.append(
" IEEE Transactions on Image Processing\n");
text.append(
" vol. 7, no. 1, pp. 27-41, January 1998.\n");
text.append(
"\n");
text.append(
" This paper is available on-line at\n");
text.append(
" http://bigwww.epfl.ch/publications/thevenaz9801.html\n");
text.append(
"\n");
text.append(
" Other relevant on-line publications are available at\n");
text.append(
" http://bigwww.epfl.ch/publications/\n");
text.append(
"\n");
text.append(
" Additional help available at\n");
text.append(
" http://bigwww.epfl.ch/thevenaz/turboreg/\n");
text.append(
"\n");
text.append(
" You'll be free to use this software for research purposes, but\n");
text.append(
" you should not redistribute it without our consent. In addition,\n");
text.append(
" we expect you to include a citation or acknowledgment whenever\n");
text.append(
" you present or publish results that are based on it.\n");
add("North", separation);
add("Center", text);
add("South", buttonPanel);
pack();
} /* end turboRegCredits */
} /* end class turboRegCredits */
/*====================================================================
| turboRegDialog
\===================================================================*/
/*********************************************************************
This class creates the main dialog.
********************************************************************/
class turboRegDialog
extends
Dialog
implements
ActionListener
{ /* class turboRegDialog */
/*....................................................................
public variables
....................................................................*/
/*********************************************************************
Three points generate an affine transformation, which is any
combination of translation, rotation, isotropic scaling, anisotropic
scaling, shearing, and skewing. An affine transformation maps
parallel lines onto parallel lines and is determined by 6 parameters.
********************************************************************/
public static final int AFFINE = 6;
/*********************************************************************
Generic geometric transformation.
********************************************************************/
public static final int GENERIC_TRANSFORMATION = -1;
/*********************************************************************
Four points describe a bilinear transformation, where a point of
coordinates (x, y) is mapped on a point of coordinates (u, v) such
that u = p0 + p1 x + p2 y + p3 x y and v = q0 + q1 x + q2 y + q3 x y.
Thus, u and v are both linear in x, and in y as well. The bilinear
transformation is determined by 8 parameters.
********************************************************************/
public static final int BILINEAR = 8;
/*********************************************************************
Blue slice.
********************************************************************/
public static final int BLUE = 3;
/*********************************************************************
Graylevel slice.
********************************************************************/
public static final int BLACK = 0;
/*********************************************************************
Green slice.
********************************************************************/
public static final int GREEN = 2;
/*********************************************************************
Minimal linear dimension of an image in the multiresolution pyramid.
********************************************************************/
public static final int MIN_SIZE = 12;
/*********************************************************************
Red slice.
********************************************************************/
public static final int RED = 1;
/*********************************************************************
A single points determines the translation component of a rigid-body
transformation. As the rotation is given by a scalar number, it is
not natural to represent this number by coordinates of a point. The
rigid-body transformation is determined by 3 parameters.
********************************************************************/
public static final int RIGID_BODY = 3;
/*********************************************************************
A pair of points determines the combination of a translation, of
a rotation, and of an isotropic scaling. Angles are conserved. A
scaled rotation is determined by 4 parameters.
********************************************************************/
public static final int SCALED_ROTATION = 4;
/*********************************************************************
A translation is described by a single point. It keeps area, angle,
and orientation. A translation is determined by 2 parameters.
********************************************************************/
public static final int TRANSLATION = 2;
/*....................................................................
private variables
....................................................................*/
/*********************************************************************
Admissible values are {<code>TRANSLATION</code>, <code>RIGID_BODY</code>,
<code>SCALED_ROTATION</code>, <code>AFFINE</code>, <code>BILINEAR<code>}.
********************************************************************/
private ImagePlus[] admissibleImageList;
private ImageCanvas sourceIc;
private ImageCanvas targetIc;
private ImagePlus sourceImp;
private ImagePlus targetImp;
private Scrollbar sourceScrollbar;
private Scrollbar targetScrollbar;
private static boolean saveOnExit = false;
private static boolean accelerated = true;
private static final long serialVersionUID = 1L;
private static int transformation = RIGID_BODY;
private static int sourceColorPlane = BLACK;
private static int targetColorPlane = BLACK;
private final Button automaticButton = new Button("Automatic");
private final Button batchButton = new Button("Batch");
private final CheckboxGroup sourceKrgbGroup = new CheckboxGroup();
private final Checkbox sourceBlack = new Checkbox(
"K", sourceKrgbGroup, sourceColorPlane == BLACK);
private final Checkbox sourceRed = new Checkbox(
"R", sourceKrgbGroup, sourceColorPlane == RED);
private final Checkbox sourceGreen = new Checkbox(
"G", sourceKrgbGroup, sourceColorPlane == GREEN);
private final Checkbox sourceBlue = new Checkbox(
"B", sourceKrgbGroup, sourceColorPlane == BLUE);
private final CheckboxGroup targetKrgbGroup = new CheckboxGroup();
private final Checkbox targetBlack = new Checkbox(
"K", targetKrgbGroup, targetColorPlane == BLACK);
private final Checkbox targetRed = new Checkbox(
"R", targetKrgbGroup, targetColorPlane == RED);
private final Checkbox targetGreen = new Checkbox(
"G", targetKrgbGroup, targetColorPlane == GREEN);
private final Checkbox targetBlue = new Checkbox(
"B", targetKrgbGroup, targetColorPlane == BLUE);
private final CheckboxGroup transformationGroup = new CheckboxGroup();
private final Checkbox translation = new Checkbox(
"Translation", transformationGroup, transformation == TRANSLATION);
private final Checkbox rigidBody = new Checkbox(
"Rigid Body", transformationGroup, transformation == RIGID_BODY);
private final Checkbox scaledRotation = new Checkbox(
"Scaled Rotation", transformationGroup, transformation == SCALED_ROTATION);
private final Checkbox affine = new Checkbox(
"Affine", transformationGroup, transformation == AFFINE);
private final Checkbox bilinear = new Checkbox(
"Bilinear", transformationGroup, transformation == BILINEAR);
private final turboRegFinalAction finalAction = new turboRegFinalAction(this);
private final turboRegPointToolbar tb = new turboRegPointToolbar(
Toolbar.getInstance());
private int sourceChoiceIndex = 0;
private int targetChoiceIndex = 1;
private int pyramidDepth;
private turboRegImage sourceImg;
private turboRegImage targetImg;
private turboRegMask sourceMsk;
private turboRegMask targetMsk;
private turboRegPointAction sourcePa;
private turboRegPointAction targetPa;
private turboRegPointHandler sourcePh;
private turboRegPointHandler targetPh;
/*....................................................................
ActionListener methods
....................................................................*/
/*********************************************************************
This method processes the button actions.
@param ae The expected actions are as follows:
<ul><li><code>Load...</code>: Load landmarks from a file;</li>
<li><code>Save Now...</code>: Save landmarks into a file;</li>
<li><code>Cancel</code>: Restore the progress bar and the toolbar,
reset the ROI's, and then quit;</li>
<li><code>Manual</code>: Create an output image that is distorted in
such a way that the landmarks of the source are made to coincide
with those of the target;</li>
<li><code>Automatic</code>: Refine the landmarks of the source image
in such a way that the least-squares error between the transformed
source image and the target is minimized.</li></ul>
********************************************************************/
public void actionPerformed (
final ActionEvent ae
) {
if (ae.getActionCommand().equals("Load...")) {
if (!loadLandmarks()) {
ExceptionHandler.addError(Thread.currentThread(),
"Invalid Landmarks");
}
}
else if (ae.getActionCommand().equals("Save Now...")) {
final turboRegTransform tt = new turboRegTransform(
sourceImg, sourceMsk, sourcePh,
targetImg, targetMsk, targetPh, transformation, accelerated, true);
tt.saveTransformation(null);
}
else if (ae.getActionCommand().equals("Cancel")) {
dispose();
restoreAll();
}
else if (ae.getActionCommand().equals("Manual")) {
dispose();
if (sourceImp.getStack().isRGB()) {
finalAction.setup(
sourceImp, sourceImg, sourceMsk, sourcePh, sourceColorPlane,
targetImg, targetMsk, targetPh, transformation, accelerated,
saveOnExit, turboRegFinalAction.MANUAL);
}
else {
finalAction.setup(sourceImg, sourceMsk, sourcePh,
targetImg, targetMsk, targetPh, transformation, accelerated,
saveOnExit, turboRegFinalAction.MANUAL);
}
finalAction.getThread().start();
}
else if (ae.getActionCommand().equals("Automatic")) {
dispose();
if (sourceImp.getStack().isRGB()) {
finalAction.setup(
sourceImp, sourceImg, sourceMsk, sourcePh, sourceColorPlane,
targetImg, targetMsk, targetPh, transformation, accelerated,
saveOnExit, turboRegFinalAction.AUTOMATIC);
}
else {
finalAction.setup(sourceImg, sourceMsk, sourcePh,
targetImg, targetMsk, targetPh, transformation, accelerated,
saveOnExit, turboRegFinalAction.AUTOMATIC);
}
finalAction.getThread().start();
}
else if (ae.getActionCommand().equals("Batch")) {
dispose();
finalAction.setup(sourceImp, sourceImg, sourcePh,
targetImp, targetImg, targetMsk, targetPh,
transformation, accelerated, saveOnExit, pyramidDepth);
finalAction.getThread().start();
}
else if (ae.getActionCommand().equals("Credits...")) {
final turboRegCredits dialog = new turboRegCredits(IJ.getInstance());
GUI.center(dialog);
dialog.setVisible(true);
}
} /* end actionPerformed */
/*....................................................................
Container methods
....................................................................*/
/*********************************************************************
Return some additional margin to the dialog, for aesthetic purposes.
Necessary for the current MacOS X Java version, lest the first item
disappears from the frame.
********************************************************************/
public Insets getInsets (
) {
return(new Insets(0, 20, 20, 20));
} /* end getInsets */
/*....................................................................
constructors
....................................................................*/
/*********************************************************************
This constructor prepares the dialog box and starts the first
computational threads. The threads will need to be killed and
restarted upon need. This constructor must be called when at least
two images are available.
@param parentWindow Parent window.
@param admissibleImageList Array of <code>ImagePlus</code> images
that are candidate to registration.
********************************************************************/
public turboRegDialog (
final Frame parentWindow,
final ImagePlus[] admissibleImageList
) {
super(parentWindow, "TurboReg", false);
this.admissibleImageList = admissibleImageList;
defaultSourceColorPlane();
defaultTargetColorPlane();
createImages();
startThreads();
setLayout(new GridLayout(0, 1));
final Choice sourceChoice = new Choice();
for (int k = 0; (k < admissibleImageList.length); k++) {
sourceChoice.add(admissibleImageList[k].getTitle());
}
sourceChoice.select(sourceChoiceIndex);
final Choice targetChoice = new Choice();
for (int k = 0; (k < admissibleImageList.length); k++) {
targetChoice.add(admissibleImageList[k].getTitle());
}
targetChoice.select(targetChoiceIndex);
final Panel sourcePanel = new Panel();
sourcePanel.setLayout(new FlowLayout(FlowLayout.CENTER));
sourceChoice.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
final int newChoiceIndex = sourceChoice.getSelectedIndex();
if (sourceChoiceIndex != newChoiceIndex) {
if (targetChoiceIndex != newChoiceIndex) {
sourceChoiceIndex = newChoiceIndex;
cancelSource();
defaultSourceColorPlane();
createSourceImages();
startSourceThreads();
}
else {
targetChoiceIndex = sourceChoiceIndex;
sourceChoiceIndex = newChoiceIndex;
targetChoice.select(targetChoiceIndex);
permuteImages();
startThreads();
}
sourcePa.setSecondaryPointHandler(targetImp, targetPh);
targetPa.setSecondaryPointHandler(sourceImp, sourcePh);
batchButton.setEnabled((1 < sourceImp.getStackSize())
&& !(sourceImp.getStack().isRGB()
|| targetImp.getStack().isRGB()));
}
repaint();
}
}
);
sourceRed.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (sourceKrgbGroup.getSelectedCheckbox().getLabel().equals("R")
&& (sourceColorPlane != RED)) {
sourceKrgbGroup.setSelectedCheckbox(sourceRed);
stopSourceThreads();
setSourceColorPlane(RED);
startSourceThreads();
}
repaint();
}
}
);
sourceGreen.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (sourceKrgbGroup.getSelectedCheckbox().getLabel().equals("G")
&& (sourceColorPlane != GREEN)) {
sourceKrgbGroup.setSelectedCheckbox(sourceGreen);
stopSourceThreads();
setSourceColorPlane(GREEN);
startSourceThreads();
}
repaint();
}
}
);
sourceBlue.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (sourceKrgbGroup.getSelectedCheckbox().getLabel().equals("B")
&& (sourceColorPlane != BLUE)) {
sourceKrgbGroup.setSelectedCheckbox(sourceBlue);
stopSourceThreads();
setSourceColorPlane(BLUE);
startSourceThreads();
}
repaint();
}
}
);
final Label sourceLabel = new Label("Source: ");
sourcePanel.add(sourceLabel);
sourcePanel.add(sourceChoice);
sourcePanel.add(sourceRed);
sourcePanel.add(sourceGreen);
sourcePanel.add(sourceBlue);
sourcePanel.add(sourceBlack);
final Panel targetPanel = new Panel();
targetPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
targetChoice.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
final int newChoiceIndex = targetChoice.getSelectedIndex();
if (targetChoiceIndex != newChoiceIndex) {
if (sourceChoiceIndex != newChoiceIndex) {
targetChoiceIndex = newChoiceIndex;
cancelTarget();
defaultTargetColorPlane();
createTargetImages();
startTargetThreads();
}
else {
sourceChoiceIndex = targetChoiceIndex;
targetChoiceIndex = newChoiceIndex;
sourceChoice.select(sourceChoiceIndex);
permuteImages();
startThreads();
}
sourcePa.setSecondaryPointHandler(targetImp, targetPh);
targetPa.setSecondaryPointHandler(sourceImp, sourcePh);
batchButton.setEnabled((1 < sourceImp.getStackSize())
&& !(sourceImp.getStack().isRGB()
|| targetImp.getStack().isRGB()));
}
repaint();
}
}
);
targetRed.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (targetKrgbGroup.getSelectedCheckbox().getLabel().equals("R")
&& (targetColorPlane != RED)) {
targetKrgbGroup.setSelectedCheckbox(targetRed);
stopTargetThreads();
setTargetColorPlane(RED);
startTargetThreads();
}
repaint();
}
}
);
targetGreen.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (targetKrgbGroup.getSelectedCheckbox().getLabel().equals("G")
&& (targetColorPlane != GREEN)) {
targetKrgbGroup.setSelectedCheckbox(targetGreen);
stopTargetThreads();
setTargetColorPlane(GREEN);
startTargetThreads();
}
repaint();
}
}
);
targetBlue.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (targetKrgbGroup.getSelectedCheckbox().getLabel().equals("B")
&& (targetColorPlane != BLUE)) {
targetKrgbGroup.setSelectedCheckbox(targetBlue);
stopTargetThreads();
setTargetColorPlane(BLUE);
startTargetThreads();
}
repaint();
}
}
);
final Label targetLabel = new Label("Target: ");
targetPanel.add(targetLabel);
targetPanel.add(targetChoice);
targetPanel.add(targetRed);
targetPanel.add(targetGreen);
targetPanel.add(targetBlue);
targetPanel.add(targetBlack);
final Panel transformationPanel = new Panel();
transformationPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
translation.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (transformationGroup.getSelectedCheckbox().getLabel().equals(
"Translation") && (transformation != TRANSLATION)) {
if (transformation == BILINEAR) {
transformation = TRANSLATION;
cancelImages();
createImages();
startThreads();
}
else {
transformation = TRANSLATION;
setTransformation();
}
}
repaint();
}
}
);
rigidBody.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (transformationGroup.getSelectedCheckbox().getLabel().equals(
"Rigid Body") && (transformation != RIGID_BODY)) {
if (transformation == BILINEAR) {
transformation = RIGID_BODY;
cancelImages();
createImages();
startThreads();
}
else {
transformation = RIGID_BODY;
setTransformation();
}
}
repaint();
}
}
);
scaledRotation.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (transformationGroup.getSelectedCheckbox().getLabel().equals(
"Scaled Rotation") && (transformation != SCALED_ROTATION)) {
if (transformation == BILINEAR) {
transformation = SCALED_ROTATION;
cancelImages();
createImages();
startThreads();
}
else {
transformation = SCALED_ROTATION;
setTransformation();
}
}
repaint();
}
}
);
affine.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (transformationGroup.getSelectedCheckbox().getLabel().equals(
"Affine") && (transformation != AFFINE)) {
if (transformation == BILINEAR) {
transformation = AFFINE;
cancelImages();
createImages();
startThreads();
}
else {
transformation = AFFINE;
setTransformation();
}
}
repaint();
}
}
);
bilinear.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (transformationGroup.getSelectedCheckbox().getLabel().equals(
"Bilinear") && (transformation != BILINEAR)) {
transformation = BILINEAR;
cancelImages();
createImages();
startThreads();
}
repaint();
}
}
);
transformationPanel.add(translation);
transformationPanel.add(rigidBody);
transformationPanel.add(scaledRotation);
transformationPanel.add(affine);
transformationPanel.add(bilinear);
final Panel pointPanel = new Panel();
pointPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
final Label pointLabel = new Label("Landmarks: ");
final Button loadButton = new Button("Load...");
loadButton.addActionListener(this);
final Button saveButton = new Button("Save Now...");
saveButton.addActionListener(this);
final Checkbox saveCheck = new Checkbox("Save on Exit", saveOnExit);
saveCheck.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
saveOnExit = saveCheck.getState();
repaint();
}
}
);
pointPanel.add(pointLabel);
pointPanel.add(loadButton);
pointPanel.add(saveButton);
pointPanel.add(saveCheck);
final Panel accelerationPanel = new Panel();
accelerationPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
final Label acceleratedLabel = new Label("Quality: ");
final CheckboxGroup accelerationGroup = new CheckboxGroup();
final Checkbox fast = new Checkbox(
"Fast", accelerationGroup, accelerated);
final Checkbox accurate = new Checkbox(
"Accurate", accelerationGroup, !accelerated);
fast.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (accelerationGroup.getSelectedCheckbox().getLabel().equals(
"Fast")) {
accelerated = true;
}
automaticButton.setEnabled((!accelerated)
|| (1 < pyramidDepth));
repaint();
}
}
);
accurate.addItemListener(
new ItemListener (
) {
public void itemStateChanged (
final ItemEvent ie
) {
if (accelerationGroup.getSelectedCheckbox().getLabel().equals(
"Accurate")) {
accelerated = false;
}
automaticButton.setEnabled((!accelerated)
|| (1 < pyramidDepth));
repaint();
}
}
);
accelerationPanel.add(acceleratedLabel);
accelerationPanel.add(fast);
accelerationPanel.add(accurate);
final Panel creditsPanel = new Panel();
creditsPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
final Button creditsButton = new Button("Credits...");
creditsButton.addActionListener(this);
creditsPanel.add(creditsButton);
final Panel buttonPanel = new Panel();
buttonPanel.setLayout(new FlowLayout(FlowLayout.CENTER));
final Button cancelButton = new Button("Cancel");
cancelButton.addActionListener(this);
final Button manualButton = new Button("Manual");
manualButton.addActionListener(this);
automaticButton.addActionListener(this);
batchButton.setEnabled((1 < sourceImp.getStackSize())
&& !(sourceImp.getStack().isRGB() || targetImp.getStack().isRGB()));
batchButton.addActionListener(this);
buttonPanel.add(cancelButton);
buttonPanel.add(manualButton);
buttonPanel.add(automaticButton);
buttonPanel.add(batchButton);
final Label separation1 = new Label("");
final Label separation2 = new Label("");
add(separation1);
add(sourcePanel);
add(targetPanel);
add(transformationPanel);
add(pointPanel);
add(accelerationPanel);
add(separation2);
add(buttonPanel);
add(creditsPanel);
pack();
} /* end turboRegDialog */
/*....................................................................
public methods
....................................................................*/
/*********************************************************************
Wait until the threads that compute spline coefficients, image and
mask pyramids are done.
********************************************************************/
public void joinThreads (
) {
try {
sourceImg.getThread().join();
sourceMsk.getThread().join();
targetImg.getThread().join();
targetMsk.getThread().join();
} catch (InterruptedException e) {
IJ.log(
"Unexpected interruption exception " + e.getMessage());
}
} /* end joinThreads */
/*********************************************************************
Restore the regular listener interfaces, restore the regular ImageJ
toolbar, stop the progress bar, and ask for garbage collection.
@see turboRegDialog#cancelImages()
********************************************************************/
public void restoreAll (
) {
cancelImages();
tb.restorePreviousToolbar();
Toolbar.getInstance().repaint();
turboRegProgressBar.resetProgressBar();
Runtime.getRuntime().gc();
} /* end restoreAll */
/*********************************************************************
Interrupt the two preprocessing threads.
********************************************************************/
public void stopThreads (
) {
stopSourceThreads();
stopTargetThreads();
} /* end stopThreads */
/*....................................................................
private methods
....................................................................*/
/*------------------------------------------------------------------*/
private void cancelImages (
) {
cancelSource();
cancelTarget();
} /* end cancelImages */
/*------------------------------------------------------------------*/
private void cancelSource (
) {
cancelSource(sourcePh);
this.sourcePh = null;
Runtime.getRuntime().gc();
} /* end cancelSource */
/*------------------------------------------------------------------*/
private double[][] cancelSource (
final turboRegPointHandler sourcePh
) {
stopSourceThreads();
if (sourceScrollbar != null) {
sourceScrollbar.removeAdjustmentListener(sourcePa);
sourceScrollbar = null;
}
final ImageWindow iw = sourceImp.getWindow();
iw.removeKeyListener(sourcePa);
sourceIc.removeKeyListener(sourcePa);
sourceIc.removeMouseMotionListener(sourcePa);
sourceIc.removeMouseListener(sourcePa);
sourceIc.addMouseListener(sourceIc);
sourceIc.addMouseMotionListener(sourceIc);
sourceIc.addKeyListener(IJ.getInstance());
iw.addKeyListener(IJ.getInstance());
sourceIc = null;
sourceImp.killRoi();
sourceImp.updateAndDraw();
sourceImp = null;
sourceImg = null;
sourceMsk = null;
sourcePa = null;
sourceScrollbar = null;
return(sourcePh.getPoints());
} /* end cancelSource */
/*------------------------------------------------------------------*/
private void cancelTarget (
) {
cancelTarget(targetPh);
this.targetPh = null;
Runtime.getRuntime().gc();
} /* end cancelTarget */
/*------------------------------------------------------------------*/
private double[][] cancelTarget (
final turboRegPointHandler targetPh
) {
stopTargetThreads();
if (targetScrollbar != null) {
targetScrollbar.removeAdjustmentListener(targetPa);
targetScrollbar = null;
}
final ImageWindow iw = targetImp.getWindow();
iw.removeKeyListener(targetPa);
targetIc.removeKeyListener(targetPa);
targetIc.removeMouseMotionListener(targetPa);
targetIc.removeMouseListener(targetPa);
targetIc.addMouseListener(targetIc);
targetIc.addMouseMotionListener(targetIc);
targetIc.addKeyListener(IJ.getInstance());
iw.addKeyListener(IJ.getInstance());
targetIc = null;
targetImp.killRoi();
targetImp.updateAndDraw();
targetImp = null;
targetImg = null;
targetMsk = null;
targetPa = null;
targetScrollbar = null;
return(targetPh.getPoints());
} /* end cancelTarget */
/*------------------------------------------------------------------*/
private void createImages (
) {
createSourceImages();
createTargetImages();
sourcePa.setSecondaryPointHandler(targetImp, targetPh);
targetPa.setSecondaryPointHandler(sourceImp, sourcePh);
getPyramidDepth();
sourceImg.setPyramidDepth(pyramidDepth);
sourceMsk.setPyramidDepth(pyramidDepth);
targetImg.setPyramidDepth(pyramidDepth);
targetMsk.setPyramidDepth(pyramidDepth);
} /* end createImages */
/*------------------------------------------------------------------*/
private void createSourceImages (
) {
sourceImp = admissibleImageList[sourceChoiceIndex];
if (sourceImp.getStack().isRGB()) {
sourceBlack.setEnabled(false);
sourceRed.setEnabled(true);
sourceGreen.setEnabled(true);
sourceBlue.setEnabled(true);
switch (sourceColorPlane) {
case RED: {
sourceKrgbGroup.setSelectedCheckbox(sourceRed);
break;
}
case GREEN: {
sourceKrgbGroup.setSelectedCheckbox(sourceGreen);
break;
}
case BLUE: {
sourceKrgbGroup.setSelectedCheckbox(sourceBlue);
break;
}
}
sourceImp.setSlice(sourceColorPlane);
sourceImg = new turboRegImage(sourceImp, transformation, false);
sourceMsk = new turboRegMask(sourceImp);
sourceMsk.clearMask();
}
else {
sourceBlack.setEnabled(true);
sourceRed.setEnabled(false);
sourceGreen.setEnabled(false);
sourceBlue.setEnabled(false);
sourceKrgbGroup.setSelectedCheckbox(sourceBlack);
sourceColorPlane = 0;
sourceImp.setSlice(1);
sourceImg = new turboRegImage(sourceImp, transformation, false);
if (2 <= sourceImp.getStackSize()) {
sourceImp.setSlice(2);
}
sourceMsk = new turboRegMask(sourceImp);
sourceImp.setSlice(1);
if (sourceImp.getStackSize() < 2) {
sourceMsk.clearMask();
}
}
final ImageWindow iw = sourceImp.getWindow();
sourceIc = iw.getCanvas();
iw.removeKeyListener(IJ.getInstance());
sourceIc.removeKeyListener(IJ.getInstance());
sourceIc.removeMouseMotionListener(sourceIc);
sourceIc.removeMouseListener(sourceIc);
sourcePh = new turboRegPointHandler(sourceImp, transformation);
sourcePa = new turboRegPointAction(sourceImp, sourcePh, tb);
sourceIc.addMouseListener(sourcePa);
sourceIc.addMouseMotionListener(sourcePa);
sourceIc.addKeyListener(sourcePa);
iw.addKeyListener(sourcePa);
if (sourceImp.getWindow() instanceof StackWindow) {
StackWindow sw = (StackWindow)sourceImp.getWindow();
final Component component[] = sw.getComponents();
for (int i = 0; (i < component.length); i++) {
if (component[i] instanceof Scrollbar) {
sourceScrollbar = (Scrollbar)component[i];
sourceScrollbar.addAdjustmentListener(sourcePa);
}
}
}
else {
sourceScrollbar = null;
}
sourceImp.updateAndDraw();
} /* end createSourceImages */
/*------------------------------------------------------------------*/
private void createTargetImages (
) {
targetImp = admissibleImageList[targetChoiceIndex];
if (targetImp.getStack().isRGB()) {
targetBlack.setEnabled(false);
targetRed.setEnabled(true);
targetGreen.setEnabled(true);
targetBlue.setEnabled(true);
switch (targetColorPlane) {
case RED: {
targetKrgbGroup.setSelectedCheckbox(targetRed);
break;
}
case GREEN: {
targetKrgbGroup.setSelectedCheckbox(targetGreen);
break;
}
case BLUE: {
targetKrgbGroup.setSelectedCheckbox(targetBlue);
break;
}
}
targetImp.setSlice(targetColorPlane);
targetImg = new turboRegImage(targetImp, transformation, true);
targetMsk = new turboRegMask(targetImp);
targetMsk.clearMask();
}
else {
targetBlack.setEnabled(true);
targetRed.setEnabled(false);
targetGreen.setEnabled(false);
targetBlue.setEnabled(false);
targetKrgbGroup.setSelectedCheckbox(targetBlack);
targetColorPlane = 0;
targetImp.setSlice(1);
targetImg = new turboRegImage(targetImp, transformation, true);
if (2 <= targetImp.getStackSize()) {
targetImp.setSlice(2);
}
targetMsk = new turboRegMask(targetImp);
targetImp.setSlice(1);
if (targetImp.getStackSize() < 2) {
targetMsk.clearMask();
}
}
final ImageWindow iw = targetImp.getWindow();
targetIc = iw.getCanvas();
iw.removeKeyListener(IJ.getInstance());
targetIc.removeKeyListener(IJ.getInstance());
targetIc.removeMouseMotionListener(targetIc);
targetIc.removeMouseListener(targetIc);
targetPh = new turboRegPointHandler(targetImp, transformation);
targetPa = new turboRegPointAction(targetImp, targetPh, tb);
targetIc.addMouseListener(targetPa);
targetIc.addMouseMotionListener(targetPa);
targetIc.addKeyListener(targetPa);
iw.addKeyListener(targetPa);
if (targetImp.getWindow() instanceof StackWindow) {
StackWindow sw = (StackWindow)targetImp.getWindow();
final Component component[] = sw.getComponents();
for (int i = 0; (i < component.length); i++) {
if (component[i] instanceof Scrollbar) {
targetScrollbar = (Scrollbar)component[i];
targetScrollbar.addAdjustmentListener(targetPa);
}
}
}
else {
targetScrollbar = null;
}
targetImp.updateAndDraw();
} /* end createTargetImages */
/*------------------------------------------------------------------*/
private void defaultSourceColorPlane (
) {
sourceImp = admissibleImageList[sourceChoiceIndex];
if (sourceImp.getStack().isRGB()) {
sourceColorPlane = sourceImp.getCurrentSlice();
}
else {
sourceColorPlane = 0;
}
} /* end defaultSourceColorPlane */
/*------------------------------------------------------------------*/
private void defaultTargetColorPlane (
) {
targetImp = admissibleImageList[targetChoiceIndex];
if (targetImp.getStack().isRGB()) {
targetColorPlane = targetImp.getCurrentSlice();
}
else {
targetColorPlane = 0;
}
} /* end defaultTargetColorPlane */
/*------------------------------------------------------------------*/
private void getPyramidDepth (
) {
int sw = sourceImp.getWidth();
int sh = sourceImp.getHeight();
int tw = targetImp.getWidth();
int th = targetImp.getHeight();
pyramidDepth = 1;
while (((2 * MIN_SIZE) <= sw) && ((2 * MIN_SIZE) <= sh)
&& ((2 * MIN_SIZE) <= tw) && ((2 * MIN_SIZE) <= th)) {
sw /= 2;
sh /= 2;
tw /= 2;
th /= 2;
pyramidDepth++;
}
automaticButton.setEnabled((!accelerated) || (1 < pyramidDepth));
} /* end getPyramidDepth */
/*------------------------------------------------------------------*/
@SuppressWarnings("resource")
private boolean loadLandmarks (
) {
final Frame f = new Frame();
final FileDialog fd = new FileDialog(f, "Landmarks", FileDialog.LOAD);
fd.setVisible(true);
String path = fd.getDirectory();
String filename = fd.getFile();
if ((path == null) || (filename == null)) {
return(true);
}
final double[][] targetPoint =
new double[turboRegPointHandler.NUM_POINTS][2];
final double[][] sourcePoint =
new double[turboRegPointHandler.NUM_POINTS][2];
int transformation;
try {
final FileReader fr = new FileReader(path + filename);
final BufferedReader br = new BufferedReader(fr);
String line;
String xString;
String yString;
int separatorIndex;
int k = 1;
if (!(line = br.readLine()).equals("Transformation")) {
fr.close();
IJ.log("Line " + k + ": 'Transformation'");
return(false);
}
++k;
line = br.readLine();
if (line.equals("TRANSLATION")) {
transformation = TRANSLATION;
}
else if (line.equals("RIGID_BODY")) {
transformation = RIGID_BODY;
}
else if (line.equals("SCALED_ROTATION")) {
transformation = SCALED_ROTATION;
}
else if (line.equals("AFFINE")) {
transformation = AFFINE;
}
else if (line.equals("BILINEAR")) {
transformation = BILINEAR;
}
else {
fr.close();
IJ.log("Line " + k
+ ": 'TRANSLATION' "
+ "| 'RIGID_BODY' "
+ "| 'SCALED_ROTATION' "
+ "| 'AFFINE' "
+ "| 'BILINEAR'");
return(false);
}
++k;
if (!(line = br.readLine()).equals("")) {
fr.close();
IJ.log("Line " + k + ": ''");
return(false);
}
++k;
if (!(line = br.readLine()).equals("Source size")) {
fr.close();
IJ.log("Line " + k + ": 'Source size'");
return(false);
}
++k;
if ((line = br.readLine()) == null) {
fr.close();
IJ.log("Line " + k + ": #sourceWidth# <tab> #sourceHeight#");
return(false);
}
line = line.trim();
separatorIndex = line.indexOf('\t');
if (separatorIndex == -1) {
fr.close();
IJ.log("Line " + k + ": #sourceWidth# <tab> #sourceHeight#");
return(false);
}
xString = line.substring(0, separatorIndex);
yString = line.substring(separatorIndex);
xString = xString.trim();
yString = yString.trim();
if (Integer.parseInt(xString) != sourceImp.getWidth()) {
fr.close();
IJ.log("Line " + k + ": The source width"
+ " should not differ from that in the landmarks file");
return(false);
}
if (Integer.parseInt(yString) != sourceImp.getHeight()) {
fr.close();
IJ.log("Line " + k + ": The source height"
+ " should not differ from that in the landmarks file");
return(false);
}
++k;
if (!(line = br.readLine()).equals("")) {
fr.close();
IJ.log("Line " + k + ": ''");
return(false);
}
++k;
if (!(line = br.readLine()).equals("Target size")) {
fr.close();
IJ.log("Line " + k + ": 'Target size'");
return(false);
}
++k;
if ((line = br.readLine()) == null) {
fr.close();
IJ.log("Line " + k + ": #targetWidth# <tab> #targetHeight#");
return(false);
}
line = line.trim();
separatorIndex = line.indexOf('\t');
if (separatorIndex == -1) {
fr.close();
IJ.log("Line " + k + ": #targetWidth# <tab> #targetHeight#");
return(false);
}
xString = line.substring(0, separatorIndex);
yString = line.substring(separatorIndex);
xString = xString.trim();
yString = yString.trim();
if (Integer.parseInt(xString) != targetImp.getWidth()) {
fr.close();
IJ.log("Line " + k + ": The target width"
+ " should not differ from that in the landmarks file");
return(false);
}
if (Integer.parseInt(yString) != targetImp.getHeight()) {
fr.close();
IJ.log("Line " + k + ": The target height"
+ " should not differ from that in the landmarks file");
return(false);
}
++k;
if (!(line = br.readLine()).equals("")) {
fr.close();
IJ.log("Line " + k + ": ''");
return(false);
}
++k;
if (!(line = br.readLine()).equals("Refined source landmarks")) {
fr.close();
IJ.log("Line " + k + ": 'Refined source landmarks'");
return(false);
}
if (transformation == RIGID_BODY) {
for (int i = 0; (i < transformation); i++) {
++k;
if ((line = br.readLine()) == null) {
fr.close();
IJ.log("Line " + k
+ ": #xSourcePoint# <tab> #ySourcePoint#");
return(false);
}
line = line.trim();
separatorIndex = line.indexOf('\t');
if (separatorIndex == -1) {
fr.close();
IJ.log("Line " + k
+ ": #xSourcePoint# <tab> #ySourcePoint#");
return(false);
}
xString = line.substring(0, separatorIndex);
yString = line.substring(separatorIndex);
xString = xString.trim();
yString = yString.trim();
sourcePoint[i][0] = (new Double(xString)).doubleValue();
sourcePoint[i][1] = (new Double(yString)).doubleValue();
}
}
else {
for (int i = 0; (i < (transformation / 2)); i++) {
++k;
if ((line = br.readLine()) == null) {
fr.close();
IJ.log("Line " + k
+ ": #xSourcePoint# <tab> #ySourcePoint#");
return(false);
}
line = line.trim();
separatorIndex = line.indexOf('\t');
if (separatorIndex == -1) {
fr.close();
IJ.log("Line " + k
+ ": #xSourcePoint# <tab> #ySourcePoint#");
return(false);
}
xString = line.substring(0, separatorIndex);
yString = line.substring(separatorIndex);
xString = xString.trim();
yString = yString.trim();
sourcePoint[i][0] = (new Double(xString)).doubleValue();
sourcePoint[i][1] = (new Double(yString)).doubleValue();
}
}
++k;
if (!(line = br.readLine()).equals("")) {
fr.close();
IJ.log("Line " + k + ": ''");
return(false);
}
++k;
if (!(line = br.readLine()).equals("Target landmarks")) {
fr.close();
IJ.log("Line " + k + ": 'Target landmarks'");
return(false);
}
if (transformation == RIGID_BODY) {
for (int i = 0; (i < transformation); i++) {
++k;
if ((line = br.readLine()) == null) {
fr.close();
IJ.log("Line " + k
+ ": #xTargetPoint# <tab> #yTargetPoint#");
return(false);
}
line = line.trim();
separatorIndex = line.indexOf('\t');
if (separatorIndex == -1) {
fr.close();
IJ.log("Line " + k
+ ": #xTargetPoint# <tab> #yTargetPoint#");
return(false);
}
xString = line.substring(0, separatorIndex);
yString = line.substring(separatorIndex);
xString = xString.trim();
yString = yString.trim();
targetPoint[i][0] = (new Double(xString)).doubleValue();
targetPoint[i][1] = (new Double(yString)).doubleValue();
}
}
else {
for (int i = 0; (i < (transformation / 2)); i++) {
++k;
if ((line = br.readLine()) == null) {
fr.close();
IJ.log("Line " + k
+ ": #xTargetPoint# <tab> #yTargetPoint#");
return(false);
}
line = line.trim();
separatorIndex = line.indexOf('\t');
if (separatorIndex == -1) {
fr.close();
IJ.log("Line " + k
+ ": #xTargetPoint# <tab> #yTargetPoint#");
return(false);
}
xString = line.substring(0, separatorIndex);
yString = line.substring(separatorIndex);
xString = xString.trim();
yString = yString.trim();
targetPoint[i][0] = (new Double(xString)).doubleValue();
targetPoint[i][1] = (new Double(yString)).doubleValue();
}
}
fr.close();
} catch (FileNotFoundException e) {
IJ.log(
"File not found exception " + e.getMessage());
return(false);
} catch (IOException e) {
IJ.log(
"IOException exception " + e.getMessage());
return(false);
} catch (NumberFormatException e) {
IJ.log(
"Number format exception " + e.getMessage());
return(false);
}
if (transformation != turboRegDialog.transformation) {
if ((transformation == BILINEAR)
|| (turboRegDialog.transformation == BILINEAR)) {
cancelImages();
createImages();
startThreads();
}
turboRegDialog.transformation = transformation;
setTransformation();
}
sourcePh.setPoints(sourcePoint);
targetPh.setPoints(targetPoint);
switch (transformation) {
case TRANSLATION: {
transformationGroup.setSelectedCheckbox(translation);
break;
}
case RIGID_BODY: {
transformationGroup.setSelectedCheckbox(rigidBody);
break;
}
case AFFINE: {
transformationGroup.setSelectedCheckbox(affine);
break;
}
case SCALED_ROTATION: {
transformationGroup.setSelectedCheckbox(scaledRotation);
break;
}
case BILINEAR: {
transformationGroup.setSelectedCheckbox(bilinear);
break;
}
}
sourceImp.updateAndDraw();
targetImp.updateAndDraw();
return(true);
} /* end loadLandmarks */
/*------------------------------------------------------------------*/
private void permuteImages (
) {
final int rescuedSourceColorPlane = sourceColorPlane;
final int rescuedTargetColorPlane = targetColorPlane;
final double[][] rescuedSourcePoints = cancelSource(sourcePh);
final double[][] rescuedTargetPoints = cancelTarget(targetPh);
sourceColorPlane = rescuedTargetColorPlane;
targetColorPlane = rescuedSourceColorPlane;
createSourceImages();
sourcePh.setPoints(rescuedTargetPoints);
createTargetImages();
targetPh.setPoints(rescuedSourcePoints);
sourceImp.updateAndDraw();
targetImp.updateAndDraw();
} /* end permuteImages */
/*------------------------------------------------------------------*/
private void setSourceColorPlane (
final int colorPlane
) {
sourceColorPlane = colorPlane;
switch (sourceColorPlane) {
case RED: {
sourceKrgbGroup.setSelectedCheckbox(sourceRed);
break;
}
case GREEN: {
sourceKrgbGroup.setSelectedCheckbox(sourceGreen);
break;
}
case BLUE: {
sourceKrgbGroup.setSelectedCheckbox(sourceBlue);
break;
}
}
sourceImp.setSlice(sourceColorPlane);
sourceImg = new turboRegImage(sourceImp, transformation, false);
sourceMsk = new turboRegMask(sourceImp);
sourceMsk.clearMask();
} /* end setSourceColorPlane */
/*------------------------------------------------------------------*/
private void setTargetColorPlane (
final int colorPlane
) {
targetColorPlane = colorPlane;
switch (targetColorPlane) {
case RED: {
targetKrgbGroup.setSelectedCheckbox(targetRed);
break;
}
case GREEN: {
targetKrgbGroup.setSelectedCheckbox(targetGreen);
break;
}
case BLUE: {
targetKrgbGroup.setSelectedCheckbox(targetBlue);
break;
}
}
targetImp.setSlice(targetColorPlane);
targetImg = new turboRegImage(targetImp, transformation, true);
targetMsk = new turboRegMask(targetImp);
targetMsk.clearMask();
} /* end setTargetColorPlane */
/*------------------------------------------------------------------*/
private void setTransformation (
) {
sourceImg.setTransformation(transformation);
sourcePh.setTransformation(transformation);
targetImg.setTransformation(transformation);
targetPh.setTransformation(transformation);
} /* end setTransformation */
/*------------------------------------------------------------------*/
private void startSourceThreads (
) {
getPyramidDepth();
sourceImg.setPyramidDepth(pyramidDepth);
sourceMsk.setPyramidDepth(pyramidDepth);
if (pyramidDepth != targetImg.getPyramidDepth()) {
ImagePlus imp = targetImp;
double[][] points = cancelTarget(targetPh);
targetImp = imp;
createTargetImages();
targetPh.setPoints(points);
targetImp.updateAndDraw();
targetImg.setPyramidDepth(pyramidDepth);
targetMsk.setPyramidDepth(pyramidDepth);
startTargetThreads();
}
sourceImg.getThread().start();
sourceMsk.getThread().start();
} /* end startSourceThreads */
/*------------------------------------------------------------------*/
private void startTargetThreads (
) {
getPyramidDepth();
targetImg.setPyramidDepth(pyramidDepth);
targetMsk.setPyramidDepth(pyramidDepth);
if (pyramidDepth != sourceImg.getPyramidDepth()) {
ImagePlus imp = sourceImp;
double points[][] = cancelSource(sourcePh);
sourceImp = imp;
createSourceImages();
sourcePh.setPoints(points);
sourceImp.updateAndDraw();
sourceImg.setPyramidDepth(pyramidDepth);
sourceMsk.setPyramidDepth(pyramidDepth);
startSourceThreads();
}
targetImg.getThread().start();
targetMsk.getThread().start();
} /* end startTargetThreads */
/*------------------------------------------------------------------*/
private void startThreads (
) {
getPyramidDepth();
sourceImg.setPyramidDepth(pyramidDepth);
sourceMsk.setPyramidDepth(pyramidDepth);
sourceImg.getThread().start();
sourceMsk.getThread().start();
targetImg.setPyramidDepth(pyramidDepth);
targetMsk.setPyramidDepth(pyramidDepth);
targetImg.getThread().start();
targetMsk.getThread().start();
} /* end startThreads */
/*------------------------------------------------------------------*/
@SuppressWarnings("static-access")
private void stopSourceThreads (
) {
while (sourceImg.getThread().isAlive()) {
sourceImg.getThread().interrupt();
}
sourceImg.getThread().interrupted();
while (sourceMsk.getThread().isAlive()) {
sourceMsk.getThread().interrupt();
}
sourceMsk.getThread().interrupted();
} /* end stopSourceThreads */
/*------------------------------------------------------------------*/
@SuppressWarnings("static-access")
private void stopTargetThreads (
) {
while (targetImg.getThread().isAlive()) {
targetImg.getThread().interrupt();
}
targetImg.getThread().interrupted();
while (targetMsk.getThread().isAlive()) {
targetMsk.getThread().interrupt();
}
targetMsk.getThread().interrupted();
} /* end stopTargetThreads */
} /* end class turboRegDialog */
/*====================================================================
| turboRegFinalAction
\===================================================================*/
/*********************************************************************
The purpose of this class is to allow access to the progress bar,
since it is denied to the <code>turboRegDialog</code> class.
It proceeds by wrapping <code>turboRegDialog</code> inside a thread
that is under the main event loop control.
********************************************************************/
class turboRegFinalAction
implements
Runnable
{ /* class turboRegFinalAction */
/*....................................................................
public variables
....................................................................*/
/*********************************************************************
Automatic registration: the initial source landmarks are
refined to minimize the mean-square error.
********************************************************************/
public static final int AUTOMATIC = 1;
/*********************************************************************
Manual registration: the initial source landmarks are used
<i>as is</i> to produce the output image.
********************************************************************/
public static final int MANUAL = 2;
/*********************************************************************
Batch registration: each slice of the source image is registered
to the target image.
********************************************************************/
public static final int BATCH = 3;
/*....................................................................
private variables
....................................................................*/
private Thread t;
private turboRegDialog td;
private volatile ImagePlus sourceImp;
private volatile ImagePlus targetImp;
private volatile turboRegImage sourceImg;
private volatile turboRegImage targetImg;
private volatile turboRegMask sourceMsk;
private volatile turboRegMask targetMsk;
private volatile turboRegPointHandler sourcePh;
private volatile turboRegPointHandler targetPh;
private volatile int operation;
private volatile int pyramidDepth;
private volatile int sourceColorPlane;
private volatile int transformation;
private volatile boolean accelerated;
private volatile boolean saveOnExit;
private volatile boolean colorOutput;
/*....................................................................
Runnable methods
....................................................................*/
/*********************************************************************
Start under the control of the main event loop, pause as long as
the dialog event loop is active, and resume processing when
<code>turboRegDialog</code> finally dies.
********************************************************************/
public void run (
) {
double[][] sourcePoints = null;
double[][] targetPoints = null;
turboRegTransform tt = null;
ImageStack outputStack = null;
ImagePlus outputImp = null;
switch (operation) {
case AUTOMATIC:
case MANUAL: {
if (td != null) {
if ((operation == MANUAL) && accelerated) {
td.stopThreads();
}
else {
td.joinThreads();
}
}
tt = new turboRegTransform(sourceImg, sourceMsk, sourcePh,
targetImg, targetMsk, targetPh, transformation, accelerated,
(td != null));
if (operation == AUTOMATIC) {
tt.doRegistration();
}
if (colorOutput) {
outputStack = new ImageStack(
targetImg.getWidth(), targetImg.getHeight());
FloatProcessor fp;
fp = new FloatProcessor(
targetImg.getWidth(), targetImg.getHeight());
fp.setMinAndMax(0.0, 255.0);
outputStack.addSlice("Red", fp);
fp = new FloatProcessor(
targetImg.getWidth(), targetImg.getHeight());
fp.setMinAndMax(0.0, 255.0);
outputStack.addSlice("Green", fp);
fp = new FloatProcessor(
targetImg.getWidth(), targetImg.getHeight());
fp.setMinAndMax(0.0, 255.0);
outputStack.addSlice("Blue", fp);
outputImp = new ImagePlus("Registered", outputStack);
outputStack.setPixels(tt.doFinalTransform(sourceImg, sourcePh,
targetImg, targetPh, transformation, accelerated),
sourceColorPlane);
for (int c = turboRegDialog.RED; (c <= turboRegDialog.BLUE);
c++) {
if (c == sourceColorPlane) {
continue;
}
sourceImp.setSlice(c);
sourceImg = new turboRegImage(sourceImp,
turboRegDialog.GENERIC_TRANSFORMATION, false);
sourceImg.setPyramidDepth(1);
sourceImg.getThread().start();
try {
sourceImg.getThread().join();
} catch (InterruptedException e) {
IJ.log(
"Unexpected interruption exception "
+ e.getMessage());
}
sourceImg.setTransformation(transformation);
outputStack.setPixels(tt.doFinalTransform(
sourceImg, sourcePh, targetImg, targetPh,
transformation, accelerated), c);
}
final StackConverter scnv = new StackConverter(outputImp);
scnv.convertToGray8();
final ImageConverter icnv = new ImageConverter(outputImp);
ImageConverter.setDoScaling(false);
icnv.convertRGBStackToRGB();
if (td != null) {
outputImp.show();
}
}
else {
outputImp = tt.doFinalTransform(
targetImg.getWidth(), targetImg.getHeight());
}
if (saveOnExit) {
tt.saveTransformation(null);
}
if (td != null) {
td.restoreAll();
}
break;
}
case BATCH: {
outputStack = new ImageStack(targetImg.getWidth(),
targetImg.getHeight());
for (int i = 0; (i < sourceImp.getStackSize()); i++) {
outputStack.addSlice("", new FloatProcessor(
targetImg.getWidth(), targetImg.getHeight()));
}
outputImp = new ImagePlus("Registered", outputStack);
if (transformation == turboRegDialog.RIGID_BODY) {
targetPoints = new double[transformation][2];
sourcePoints = new double[transformation][2];
for (int k = 0; (k < transformation); k++) {
sourcePoints[k][0] = sourcePh.getPoints()[k][0];
sourcePoints[k][1] = sourcePh.getPoints()[k][1];
targetPoints[k][0] = targetPh.getPoints()[k][0];
targetPoints[k][1] = targetPh.getPoints()[k][1];
}
}
else {
targetPoints = new double[transformation / 2][2];
sourcePoints = new double[transformation / 2][2];
for (int k = 0; (k < (transformation / 2)); k++) {
sourcePoints[k][0] = sourcePh.getPoints()[k][0];
sourcePoints[k][1] = sourcePh.getPoints()[k][1];
targetPoints[k][0] = targetPh.getPoints()[k][0];
targetPoints[k][1] = targetPh.getPoints()[k][1];
}
}
if (td != null) {
td.joinThreads();
}
tt = new turboRegTransform(sourceImg, null, sourcePh,
targetImg, targetMsk, targetPh, transformation, accelerated,
(td != null));
if (2 <= sourceImp.getStackSize()) {
sourceImp.setSlice(2);
sourceImg = new turboRegImage(sourceImp, transformation, false);
sourceImg.setPyramidDepth(pyramidDepth);
sourceImg.getThread().start();
}
tt.doRegistration();
String pathAndFilename = "";
if (saveOnExit) {
pathAndFilename = tt.saveTransformation(null);
}
tt.doBatchFinalTransform(
(float[])outputStack.getProcessor(1).getPixels());
outputImp.setSlice(1);
outputImp.getProcessor().resetMinAndMax();
if (td != null) {
outputImp.show();
}
Runtime.getRuntime().gc();
for (int i = 2; (i <= sourceImp.getStackSize()); i++) {
targetPh.setPoints(targetPoints);
sourcePh = new turboRegPointHandler(sourceImp, transformation);
sourcePh.setPoints(sourcePoints);
try {
sourceImg.getThread().join();
} catch (InterruptedException e) {
IJ.log(
"Unexpected interruption exception " + e.getMessage());
}
tt = new turboRegTransform(sourceImg, null, sourcePh,
targetImg, targetMsk, targetPh, transformation, accelerated,
(td != null));
if (i < sourceImp.getStackSize()) {
sourceImp.setSlice(i + 1);
sourceImg = new turboRegImage(sourceImp, transformation,
false);
sourceImg.setPyramidDepth(pyramidDepth);
sourceImg.getThread().start();
}
tt.doRegistration();
if (saveOnExit) {
tt.appendTransformation(pathAndFilename);
}
tt.doBatchFinalTransform(
(float[])outputStack.getProcessor(i).getPixels());
outputImp.setSlice(i);
outputImp.getProcessor().resetMinAndMax();
Runtime.getRuntime().gc();
}
sourceImp.killRoi();
targetImp.killRoi();
outputImp.setSlice(1);
outputImp.getProcessor().resetMinAndMax();
if (td != null) {
td.restoreAll();
}
break;
}
}
} /* end run */
/*....................................................................
constructors
....................................................................*/
/*********************************************************************
Start a thread under the control of the main event loop. This thread
has access to the progress bar, while methods called directly from
within <code>turboRegDialog</code> do not because they are under the
control of its own event loop.
@param dialog Gives access to some utility methods within
<code>turboRegDialog</code>.
********************************************************************/
public turboRegFinalAction (
final turboRegDialog dialog
) {
td = dialog;
t = new Thread(this);
} /* end turboRegFinalAction */
/*********************************************************************
Start a thread under the control of the main event loop.
********************************************************************/
public turboRegFinalAction (
final turboRegImage sourceImg,
final turboRegMask sourceMsk,
final turboRegPointHandler sourcePh,
final turboRegImage targetImg,
final turboRegMask targetMsk,
final turboRegPointHandler targetPh,
final int transformation
) {
this.sourceImg = sourceImg;
this.sourceMsk = sourceMsk;
this.sourcePh = sourcePh;
this.targetImg = targetImg;
this.targetMsk = targetMsk;
this.targetPh = targetPh;
this.transformation = transformation;
accelerated = false;
saveOnExit = false;
operation = AUTOMATIC;
colorOutput = false;
td = null;
t = new Thread(this);
} /* end turboRegFinalAction */
/*....................................................................
public methods
....................................................................*/
/*********************************************************************
Return the thread associated with this <code>turboRegFinalAction</code>
object.
********************************************************************/
public Thread getThread (
) {
return(t);
} /* end getThread */
/*********************************************************************
Pass parameter from <code>turboRegDialog</code> to
<code>turboRegFinalAction</code>.
********************************************************************/
public void setup (
final turboRegImage sourceImg,
final turboRegMask sourceMsk,
final turboRegPointHandler sourcePh,
final turboRegImage targetImg,
final turboRegMask targetMsk,
final turboRegPointHandler targetPh,
final int transformation,
final boolean accelerated,
final boolean saveOnExit,
final int operation
) {
this.sourceImg = sourceImg;
this.sourceMsk = sourceMsk;
this.sourcePh = sourcePh;
this.targetImg = targetImg;
this.targetMsk = targetMsk;
this.targetPh = targetPh;
this.transformation = transformation;
this.accelerated = accelerated;
this.saveOnExit = saveOnExit;
this.operation = operation;
colorOutput = false;
} /* end setup */
/*********************************************************************
Pass parameter from <code>turboRegDialog</code> to
<code>turboRegFinalAction</code>.
********************************************************************/
public void setup (
final ImagePlus sourceImp,
final turboRegImage sourceImg,
final turboRegMask sourceMsk,
final turboRegPointHandler sourcePh,
final int sourceColorPlane,
final turboRegImage targetImg,
final turboRegMask targetMsk,
final turboRegPointHandler targetPh,
final int transformation,
final boolean accelerated,
final boolean saveOnExit,
final int operation
) {
this.sourceImp = sourceImp;
this.sourceImg = sourceImg;
this.sourceMsk = sourceMsk;
this.sourcePh = sourcePh;
this.sourceColorPlane = sourceColorPlane;
this.targetImg = targetImg;
this.targetMsk = targetMsk;
this.targetPh = targetPh;
this.transformation = transformation;
this.accelerated = accelerated;
this.saveOnExit = saveOnExit;
this.operation = operation;
colorOutput = true;
} /* end setup */
/*********************************************************************
Pass parameter from <code>turboRegDialog</code> to
<code>turboRegFinalAction</code>.
********************************************************************/
public void setup (
final ImagePlus sourceImp,
final turboRegImage sourceImg,
final turboRegPointHandler sourcePh,
final ImagePlus targetImp,
final turboRegImage targetImg,
final turboRegMask targetMsk,
final turboRegPointHandler targetPh,
final int transformation,
final boolean accelerated,
final boolean saveOnExit,
final int pyramidDepth
) {
this.sourceImp = sourceImp;
this.sourceImg = sourceImg;
this.sourcePh = sourcePh;
this.targetImp = targetImp;
this.targetImg = targetImg;
this.targetMsk = targetMsk;
this.targetPh = targetPh;
this.transformation = transformation;
this.accelerated = accelerated;
this.saveOnExit = saveOnExit;
this.pyramidDepth = pyramidDepth;
operation = BATCH;
} /* end setup */
} /* end class turboRegFinalAction */
/*====================================================================
| turboRegImage
\===================================================================*/
/*********************************************************************
This class is responsible for the image preprocessing that takes
place concurrently with user-interface events. It contains methods
to compute B-spline coefficients and their pyramids, image pyramids,
gradients, and gradient pyramids.
********************************************************************/
class turboRegImage
implements
Runnable
{ /* class turboRegImage */
/*....................................................................
private variables
....................................................................*/
private final Stack<Object> pyramid = new Stack<Object>();
private Thread t;
private float[] image;
private float[] coefficient;
private float[] xGradient;
private float[] yGradient;
private int width;
private int height;
private int pyramidDepth;
private int transformation;
private boolean isTarget;
/*....................................................................
Runnable methods
....................................................................*/
/*********************************************************************
Start the image precomputations. The computation of the B-spline
coefficients of the full-size image is not interruptible; all other
methods are.
********************************************************************/
public void run (
) {
coefficient = getBasicFromCardinal2D();
switch (transformation) {
case turboRegDialog.GENERIC_TRANSFORMATION: {
break;
}
case turboRegDialog.TRANSLATION:
case turboRegDialog.RIGID_BODY:
case turboRegDialog.SCALED_ROTATION:
case turboRegDialog.AFFINE: {
if (isTarget) {
buildCoefficientPyramid();
}
else {
imageToXYGradient2D();
buildImageAndGradientPyramid();
}
break;
}
case turboRegDialog.BILINEAR: {
if (isTarget) {
buildImagePyramid();
}
else {
buildCoefficientPyramid();
}
break;
}
}
} /* end run */
/*....................................................................
constructors
....................................................................*/
/*********************************************************************
Converts the pixel array of the incoming <code>ImagePlus</code>
object into a local <code>float</code> array.
@param imp <code>ImagePlus</code> object to preprocess.
@param transformation Transformation code.
@param isTarget Tags the current object as a target or source image.
********************************************************************/
public turboRegImage (
final ImagePlus imp,
final int transformation,
final boolean isTarget
) {
t = new Thread(this);
t.setDaemon(true);
this.transformation = transformation;
this.isTarget = isTarget;
width = imp.getWidth();
height = imp.getHeight();
int k = 0;
turboRegProgressBar.addWorkload(height);
if (imp.getType() == ImagePlus.GRAY8) {
image = new float[width * height];
final byte[] pixels = (byte[])imp.getProcessor().getPixels();
for (int y = 0; (y < height); y++) {
for (int x = 0; (x < width); x++, k++) {
image[k] = (float)(pixels[k] & 0xFF);
}
turboRegProgressBar.stepProgressBar();
}
}
else if (imp.getType() == ImagePlus.GRAY16) {
image = new float[width * height];
final short[] pixels = (short[])imp.getProcessor().getPixels();
for (int y = 0; (y < height); y++) {
for (int x = 0; (x < width); x++, k++) {
if (pixels[k] < (short)0) {
image[k] = (float)pixels[k] + 65536.0F;
}
else {
image[k] = (float)pixels[k];
}
}
turboRegProgressBar.stepProgressBar();
}
}
else if (imp.getType() == ImagePlus.GRAY32) {
image = (float[])imp.getProcessor().getPixels();
}
turboRegProgressBar.workloadDone(height);
} /* end turboRegImage */
/*....................................................................
public methods
....................................................................*/
/*********************************************************************
Return the B-spline coefficients of the full-size image.
********************************************************************/
public float[] getCoefficient (
) {
return(coefficient);
} /* end getCoefficient */
/*********************************************************************
Return the full-size image height.
********************************************************************/
public int getHeight (
) {
return(height);
} /* end getHeight */
/*********************************************************************
Return the full-size image array.
********************************************************************/
public float[] getImage (
) {
return(image);
} /* end getImage */
/*********************************************************************
Return the image pyramid as a <code>Stack</code> object. The organization
of the stack depends on whether the <code>turboRegImage</code>
object corresponds to the target or the source image, and on the
transformation (ML* = {<code>TRANSLATION</code>,<code>RIGID_BODY</code>,
<code>SCALED_ROTATION</code>, <code>AFFINE</code>} vs.
ML = {<code>BILINEAR<code>}). A single pyramid level consists of
<p>
<table border="1">
<tr><th><code>isTarget</code></th>
<th>ML*</th>
<th>ML</th></tr>
<tr><td>true</td>
<td>width<br>height<br>B-spline coefficients</td>
<td>width<br>height<br>samples</td></tr>
<tr><td>false</td>
<td>width<br>height<br>samples<br>horizontal gradients<br>
vertical gradients</td>
<td>width<br>height<br>B-spline coefficients</td></tr>
</table>
********************************************************************/
public Stack<Object> getPyramid (
) {
return(pyramid);
} /* end getPyramid */
/*********************************************************************
Return the depth of the image pyramid. A depth <code>1</code> means
that one coarse resolution level is present in the stack. The
full-size level is not placed on the stack.
********************************************************************/
public int getPyramidDepth (
) {
return(pyramidDepth);
} /* end getPyramidDepth */
/*********************************************************************
Return the thread associated with this <code>turboRegImage</code>
object.
********************************************************************/
public Thread getThread (
) {
return(t);
} /* end getThread */
/*********************************************************************
Return the full-size image width.
********************************************************************/
public int getWidth (
) {
return(width);
} /* end getWidth */
/*********************************************************************
Return the full-size horizontal gradient of the image, if available.
@see turboRegImage#getPyramid()
********************************************************************/
public float[] getXGradient (
) {
return(xGradient);
} /* end getXGradient */
/*********************************************************************
Return the full-size vertical gradient of the image, if available.
@see turboRegImage#getImage()
********************************************************************/
public float[] getYGradient (
) {
return(yGradient);
} /* end getYGradient */
/*********************************************************************
Sets the depth up to which the pyramids should be computed.
@see turboRegImage#getImage()
********************************************************************/
public void setPyramidDepth (
final int pyramidDepth
) {
this.pyramidDepth = pyramidDepth;
} /* end setPyramidDepth */
/*********************************************************************
Set or modify the transformation.
********************************************************************/
public void setTransformation (
final int transformation
) {
this.transformation = transformation;
} /* end setTransformation */
/*....................................................................
private methods
....................................................................*/
/*------------------------------------------------------------------*/
private void antiSymmetricFirMirrorOffBounds1D (
final double[] h,
final double[] c,
final double[] s
) {
if (2 <= c.length) {
s[0] = h[1] * (c[1] - c[0]);
for (int i = 1; (i < (s.length - 1)); i++) {
s[i] = h[1] * (c[i + 1] - c[i - 1]);
}
s[s.length - 1] = h[1] * (c[c.length - 1] - c[c.length - 2]);
}
else {
s[0] = 0.0;
}
} /* end antiSymmetricFirMirrorOffBounds1D */
/*------------------------------------------------------------------*/
private void basicToCardinal2D (
final float[] basic,
final float[] cardinal,
final int width,
final int height,
final int degree
) {
final double[] hLine = new double[width];
final double[] vLine = new double[height];
final double[] hData = new double[width];
final double[] vData = new double[height];
double[] h = null;
switch (degree) {
case 3: {
h = new double[2];
h[0] = 2.0 / 3.0;
h[1] = 1.0 / 6.0;
break;
}
case 7: {
h = new double[4];
h[0] = 151.0 / 315.0;
h[1] = 397.0 / 1680.0;
h[2] = 1.0 / 42.0;
h[3] = 1.0 / 5040.0;
break;
}
default: {
h = new double[1];
h[0] = 1.0;
}
}
int workload = width + height;
turboRegProgressBar.addWorkload(workload);
for (int y = 0; ((y < height) && (!t.isInterrupted())); y++) {
extractRow(basic, y, hLine);
symmetricFirMirrorOffBounds1D(h, hLine, hData);
putRow(cardinal, y, hData);
turboRegProgressBar.stepProgressBar();
workload--;
}
for (int x = 0; ((x < width) && (!t.isInterrupted())); x++) {
extractColumn(cardinal, width, x, vLine);
symmetricFirMirrorOffBounds1D(h, vLine, vData);
putColumn(cardinal, width, x, vData);
turboRegProgressBar.stepProgressBar();
workload--;
}
turboRegProgressBar.skipProgressBar(workload);
turboRegProgressBar.workloadDone(width + height);
} /* end basicToCardinal2D */
/*------------------------------------------------------------------*/
private void buildCoefficientPyramid (
) {
int fullWidth;
int fullHeight;
float[] fullDual = new float[width * height];
int halfWidth = width;
int halfHeight = height;
if (1 < pyramidDepth) {
basicToCardinal2D(coefficient, fullDual, width, height, 7);
}
for (int depth = 1; ((depth < pyramidDepth) && (!t.isInterrupted()));
depth++) {
fullWidth = halfWidth;
fullHeight = halfHeight;
halfWidth /= 2;
halfHeight /= 2;
final float[] halfDual = getHalfDual2D(fullDual, fullWidth, fullHeight);
final float[] halfCoefficient = getBasicFromCardinal2D(
halfDual, halfWidth, halfHeight, 7);
pyramid.push(halfCoefficient);
pyramid.push(new Integer(halfHeight));
pyramid.push(new Integer(halfWidth));
fullDual = halfDual;
}
} /* end buildCoefficientPyramid */
/*------------------------------------------------------------------*/
private void buildImageAndGradientPyramid (
) {
int fullWidth;
int fullHeight;
float[] fullDual = new float[width * height];
int halfWidth = width;
int halfHeight = height;
if (1 < pyramidDepth) {
cardinalToDual2D(image, fullDual, width, height, 3);
}
for (int depth = 1; ((depth < pyramidDepth) && (!t.isInterrupted()));
depth++) {
fullWidth = halfWidth;
fullHeight = halfHeight;
halfWidth /= 2;
halfHeight /= 2;
final float[] halfDual = getHalfDual2D(fullDual, fullWidth, fullHeight);
final float[] halfImage = getBasicFromCardinal2D(
halfDual, halfWidth, halfHeight, 7);
final float[] halfXGradient = new float[halfWidth * halfHeight];
final float[] halfYGradient = new float[halfWidth * halfHeight];
coefficientToXYGradient2D(halfImage, halfXGradient, halfYGradient,
halfWidth, halfHeight);
basicToCardinal2D(halfImage, halfImage, halfWidth, halfHeight, 3);
pyramid.push(halfYGradient);
pyramid.push(halfXGradient);
pyramid.push(halfImage);
pyramid.push(new Integer(halfHeight));
pyramid.push(new Integer(halfWidth));
fullDual = halfDual;
}
} /* end buildImageAndGradientPyramid */
/*------------------------------------------------------------------*/
private void buildImagePyramid (
) {
int fullWidth;
int fullHeight;
float[] fullDual = new float[width * height];
int halfWidth = width;
int halfHeight = height;
if (1 < pyramidDepth) {
cardinalToDual2D(image, fullDual, width, height, 3);
}
for (int depth = 1; ((depth < pyramidDepth) && (!t.isInterrupted()));
depth++) {
fullWidth = halfWidth;
fullHeight = halfHeight;
halfWidth /= 2;
halfHeight /= 2;
final float[] halfDual = getHalfDual2D(fullDual, fullWidth, fullHeight);
final float[] halfImage = new float[halfWidth * halfHeight];
dualToCardinal2D(halfDual, halfImage, halfWidth, halfHeight, 3);
pyramid.push(halfImage);
pyramid.push(new Integer(halfHeight));
pyramid.push(new Integer(halfWidth));
fullDual = halfDual;
}
} /* end buildImagePyramid */
/*------------------------------------------------------------------*/
private void cardinalToDual2D (
final float[] cardinal,
final float[] dual,
final int width,
final int height,
final int degree
) {
basicToCardinal2D(getBasicFromCardinal2D(cardinal, width, height, degree),
dual, width, height, 2 * degree + 1);
} /* end cardinalToDual2D */
/*------------------------------------------------------------------*/
private void coefficientToGradient1D (
final double[] c
) {
final double[] h = {0.0, 1.0 / 2.0};
final double[] s = new double[c.length];
antiSymmetricFirMirrorOffBounds1D(h, c, s);
System.arraycopy(s, 0, c, 0, s.length);
} /* end coefficientToGradient1D */
/*------------------------------------------------------------------*/
private void coefficientToSamples1D (
final double[] c
) {
final double[] h = {2.0 / 3.0, 1.0 / 6.0};
final double[] s = new double[c.length];
symmetricFirMirrorOffBounds1D(h, c, s);
System.arraycopy(s, 0, c, 0, s.length);
} /* end coefficientToSamples1D */
/*------------------------------------------------------------------*/
private void coefficientToXYGradient2D (
final float[] basic,
final float[] xGradient,
final float[] yGradient,
final int width,
final int height
) {
final double[] hLine = new double[width];
final double[] hData = new double[width];
final double[] vLine = new double[height];
int workload = 2 * (width + height);
turboRegProgressBar.addWorkload(workload);
for (int y = 0; ((y < height) && (!t.isInterrupted())); y++) {
extractRow(basic, y, hLine);
System.arraycopy(hLine, 0, hData, 0, width);
coefficientToGradient1D(hLine);
turboRegProgressBar.stepProgressBar();
workload--;
coefficientToSamples1D(hData);
putRow(xGradient, y, hLine);
putRow(yGradient, y, hData);
turboRegProgressBar.stepProgressBar();
workload--;
}
for (int x = 0; ((x < width) && (!t.isInterrupted())); x++) {
extractColumn(xGradient, width, x, vLine);
coefficientToSamples1D(vLine);
putColumn(xGradient, width, x, vLine);
turboRegProgressBar.stepProgressBar();
workload--;
extractColumn(yGradient, width, x, vLine);
coefficientToGradient1D(vLine);
putColumn(yGradient, width, x, vLine);
turboRegProgressBar.stepProgressBar();
workload--;
}
turboRegProgressBar.skipProgressBar(workload);
turboRegProgressBar.workloadDone(2 * (width + height));
} /* end coefficientToXYGradient2D */
/*------------------------------------------------------------------*/
private void dualToCardinal2D (
final float[] dual,
final float[] cardinal,
final int width,
final int height,
final int degree
) {
basicToCardinal2D(getBasicFromCardinal2D(dual, width, height,
2 * degree + 1), cardinal, width, height, degree);
} /* end dualToCardinal2D */
/*------------------------------------------------------------------*/
private void extractColumn (
final float[] array,
final int width,
int x,
final double[] column
) {
for (int i = 0; (i < column.length); i++) {
column[i] = (double)array[x];
x += width;
}
} /* end extractColumn */
/*------------------------------------------------------------------*/
private void extractRow (
final float[] array,
int y,
final double[] row
) {
y *= row.length;
for (int i = 0; (i < row.length); i++) {
row[i] = (double)array[y++];
}
} /* end extractRow */
/*------------------------------------------------------------------*/
private float[] getBasicFromCardinal2D (
) {
final float[] basic = new float[width * height];
final double[] hLine = new double[width];
final double[] vLine = new double[height];
turboRegProgressBar.addWorkload(width + height);
for (int y = 0; (y < height); y++) {
extractRow(image, y, hLine);
samplesToInterpolationCoefficient1D(hLine, 3, 0.0);
putRow(basic, y, hLine);
turboRegProgressBar.stepProgressBar();
}
for (int x = 0; (x < width); x++) {
extractColumn(basic, width, x, vLine);
samplesToInterpolationCoefficient1D(vLine, 3, 0.0);
putColumn(basic, width, x, vLine);
turboRegProgressBar.stepProgressBar();
}
turboRegProgressBar.workloadDone(width + height);
return(basic);
} /* end getBasicFromCardinal2D */
/*------------------------------------------------------------------*/
private float[] getBasicFromCardinal2D (
final float[] cardinal,
final int width,
final int height,
final int degree
) {
final float[] basic = new float[width * height];
final double[] hLine = new double[width];
final double[] vLine = new double[height];
int workload = width + height;
turboRegProgressBar.addWorkload(workload);
for (int y = 0; ((y < height) && (!t.isInterrupted())); y++) {
extractRow(cardinal, y, hLine);
samplesToInterpolationCoefficient1D(hLine, degree, 0.0);
putRow(basic, y, hLine);
turboRegProgressBar.stepProgressBar();
workload--;
}
for (int x = 0; ((x < width) && (!t.isInterrupted())); x++) {
extractColumn(basic, width, x, vLine);
samplesToInterpolationCoefficient1D(vLine, degree, 0.0);
putColumn(basic, width, x, vLine);
turboRegProgressBar.stepProgressBar();
workload--;
}
turboRegProgressBar.skipProgressBar(workload);
turboRegProgressBar.workloadDone(width + height);
return(basic);
} /* end getBasicFromCardinal2D */
/*------------------------------------------------------------------*/
private float[] getHalfDual2D (
final float[] fullDual,
final int fullWidth,
final int fullHeight
) {
final int halfWidth = fullWidth / 2;
final int halfHeight = fullHeight / 2;
final double[] hLine = new double[fullWidth];
final double[] hData = new double[halfWidth];
final double[] vLine = new double[fullHeight];
final double[] vData = new double[halfHeight];
final float[] demiDual = new float[halfWidth * fullHeight];
final float[] halfDual = new float[halfWidth * halfHeight];
int workload = halfWidth + fullHeight;
turboRegProgressBar.addWorkload(workload);
for (int y = 0; ((y < fullHeight) && (!t.isInterrupted())); y++) {
extractRow(fullDual, y, hLine);
reduceDual1D(hLine, hData);
putRow(demiDual, y, hData);
turboRegProgressBar.stepProgressBar();
workload--;
}
for (int x = 0; ((x < halfWidth) && (!t.isInterrupted())); x++) {
extractColumn(demiDual, halfWidth, x, vLine);
reduceDual1D(vLine, vData);
putColumn(halfDual, halfWidth, x, vData);
turboRegProgressBar.stepProgressBar();
workload--;
}
turboRegProgressBar.skipProgressBar(workload);
turboRegProgressBar.workloadDone(halfWidth + fullHeight);
return(halfDual);
} /* end getHalfDual2D */
/*------------------------------------------------------------------*/
private double getInitialAntiCausalCoefficientMirrorOffBounds (
final double[] c,
final double z,
final double tolerance
) {
return(z * c[c.length - 1] / (z - 1.0));
} /* end getInitialAntiCausalCoefficientMirrorOffBounds */
/*------------------------------------------------------------------*/
private double getInitialCausalCoefficientMirrorOffBounds (
final double[] c,
final double z,
final double tolerance
) {
double z1 = z;
double zn = Math.pow(z, c.length);
double sum = (1.0 + z) * (c[0] + zn * c[c.length - 1]);
int horizon = c.length;
if (0.0 < tolerance) {
horizon = 2 + (int)(Math.log(tolerance) / Math.log(Math.abs(z)));
horizon = (horizon < c.length) ? (horizon) : (c.length);
}
zn = zn * zn;
for (int n = 1; (n < (horizon - 1)); n++) {
z1 = z1 * z;
zn = zn / z;
sum = sum + (z1 + zn) * c[n];
}
return(sum / (1.0 - Math.pow(z, 2 * c.length)));
} /* end getInitialCausalCoefficientMirrorOffBounds */
/*------------------------------------------------------------------*/
private void imageToXYGradient2D (
) {
final double[] hLine = new double[width];
final double[] vLine = new double[height];
xGradient = new float[width * height];
yGradient = new float[width * height];
int workload = width + height;
turboRegProgressBar.addWorkload(workload);
for (int y = 0; ((y < height) && (!t.isInterrupted())); y++) {
extractRow(image, y, hLine);
samplesToInterpolationCoefficient1D(hLine, 3, 0.0);
coefficientToGradient1D(hLine);
putRow(xGradient, y, hLine);
turboRegProgressBar.stepProgressBar();
workload--;
}
for (int x = 0; ((x < width) && (!t.isInterrupted())); x++) {
extractColumn(image, width, x, vLine);
samplesToInterpolationCoefficient1D(vLine, 3, 0.0);
coefficientToGradient1D(vLine);
putColumn(yGradient, width, x, vLine);
turboRegProgressBar.stepProgressBar();
workload--;
}
turboRegProgressBar.skipProgressBar(workload);
turboRegProgressBar.workloadDone(width + height);
} /* end imageToXYGradient2D */
/*------------------------------------------------------------------*/
private void putColumn (
final float[] array,
final int width,
int x,
final double[] column
) {
for (int i = 0; (i < column.length); i++) {
array[x] = (float)column[i];
x += width;
}
} /* end putColumn */
/*------------------------------------------------------------------*/
private void putRow (
final float[] array,
int y,
final double[] row
) {
y *= row.length;
for (int i = 0; (i < row.length); i++) {
array[y++] = (float)row[i];
}
} /* end putRow */
/*------------------------------------------------------------------*/
private void reduceDual1D (
final double[] c,
final double[] s
) {
final double h[] = {6.0 / 16.0, 4.0 / 16.0, 1.0 / 16.0};
if (2 <= s.length) {
s[0] = h[0] * c[0] + h[1] * (c[0] + c[1]) + h[2] * (c[1] + c[2]);
for (int i = 2, j = 1; (j < (s.length - 1)); i += 2, j++) {
s[j] = h[0] * c[i] + h[1] * (c[i - 1] + c[i + 1])
+ h[2] * (c[i - 2] + c[i + 2]);
}
if (c.length == (2 * s.length)) {
s[s.length - 1] = h[0] * c[c.length - 2]
+ h[1] * (c[c.length - 3] + c[c.length - 1])
+ h[2] * (c[c.length - 4] + c[c.length - 1]);
}
else {
s[s.length - 1] = h[0] * c[c.length - 3]
+ h[1] * (c[c.length - 4] + c[c.length - 2])
+ h[2] * (c[c.length - 5] + c[c.length - 1]);
}
}
else {
switch (c.length) {
case 3: {
s[0] = h[0] * c[0]
+ h[1] * (c[0] + c[1]) + h[2] * (c[1] + c[2]);
break;
}
case 2: {
s[0] = h[0] * c[0] + h[1] * (c[0] + c[1]) + 2.0 * h[2] * c[1];
break;
}
}
}
} /* end reduceDual1D */
/*------------------------------------------------------------------*/
private void samplesToInterpolationCoefficient1D (
final double[] c,
final int degree,
final double tolerance
) {
double[] z = new double[0];
double lambda = 1.0;
switch (degree) {
case 3: {
z = new double[1];
z[0] = Math.sqrt(3.0) - 2.0;
break;
}
case 7: {
z = new double[3];
z[0] =
-0.5352804307964381655424037816816460718339231523426924148812;
z[1] =
-0.122554615192326690515272264359357343605486549427295558490763;
z[2] =
-0.0091486948096082769285930216516478534156925639545994482648003;
break;
}
}
if (c.length == 1) {
return;
}
for (int k = 0; (k < z.length); k++) {
lambda *= (1.0 - z[k]) * (1.0 - 1.0 / z[k]);
}
for (int n = 0; (n < c.length); n++) {
c[n] = c[n] * lambda;
}
for (int k = 0; (k < z.length); k++) {
c[0] = getInitialCausalCoefficientMirrorOffBounds(c, z[k], tolerance);
for (int n = 1; (n < c.length); n++) {
c[n] = c[n] + z[k] * c[n - 1];
}
c[c.length - 1] = getInitialAntiCausalCoefficientMirrorOffBounds(
c, z[k], tolerance);
for (int n = c.length - 2; (0 <= n); n--) {
c[n] = z[k] * (c[n+1] - c[n]);
}
}
} /* end samplesToInterpolationCoefficient1D */
/*------------------------------------------------------------------*/
private void symmetricFirMirrorOffBounds1D (
final double[] h,
final double[] c,
final double[] s
) {
switch (h.length) {
case 2: {
if (2 <= c.length) {
s[0] = h[0] * c[0] + h[1] * (c[0] + c[1]);
for (int i = 1; (i < (s.length - 1)); i++) {
s[i] = h[0] * c[i] + h[1] * (c[i - 1] + c[i + 1]);
}
s[s.length - 1] = h[0] * c[c.length - 1]
+ h[1] * (c[c.length - 2] + c[c.length - 1]);
}
else {
s[0] = (h[0] + 2.0 * h[1]) * c[0];
}
break;
}
case 4: {
if (6 <= c.length) {
s[0] = h[0] * c[0] + h[1] * (c[0] + c[1]) + h[2] * (c[1] + c[2])
+ h[3] * (c[2] + c[3]);
s[1] = h[0] * c[1] + h[1] * (c[0] + c[2]) + h[2] * (c[0] + c[3])
+ h[3] * (c[1] + c[4]);
s[2] = h[0] * c[2] + h[1] * (c[1] + c[3]) + h[2] * (c[0] + c[4])
+ h[3] * (c[0] + c[5]);
for (int i = 3; (i < (s.length - 3)); i++) {
s[i] = h[0] * c[i] + h[1] * (c[i - 1] + c[i + 1])
+ h[2] * (c[i - 2] + c[i + 2])
+ h[3] * (c[i - 3] + c[i + 3]);
}
s[s.length - 3] = h[0] * c[c.length - 3]
+ h[1] * (c[c.length - 4] + c[c.length - 2])
+ h[2] * (c[c.length - 5] + c[c.length - 1])
+ h[3] * (c[c.length - 6] + c[c.length - 1]);
s[s.length - 2] = h[0] * c[c.length - 2]
+ h[1] * (c[c.length - 3] + c[c.length - 1])
+ h[2] * (c[c.length - 4] + c[c.length - 1])
+ h[3] * (c[c.length - 5] + c[c.length - 2]);
s[s.length - 1] = h[0] * c[c.length - 1]
+ h[1] * (c[c.length - 2] + c[c.length - 1])
+ h[2] * (c[c.length - 3] + c[c.length - 2])
+ h[3] * (c[c.length - 4] + c[c.length - 3]);
}
else {
switch (c.length) {
case 5: {
s[0] = h[0] * c[0] + h[1] * (c[0] + c[1])
+ h[2] * (c[1] + c[2]) + h[3] * (c[2] + c[3]);
s[1] = h[0] * c[1] + h[1] * (c[0] + c[2])
+ h[2] * (c[0] + c[3]) + h[3] * (c[1] + c[4]);
s[2] = h[0] * c[2] + h[1] * (c[1] + c[3])
+ (h[2] + h[3]) * (c[0] + c[4]);
s[3] = h[0] * c[3] + h[1] * (c[2] + c[4])
+ h[2] * (c[1] + c[4]) + h[3] * (c[0] + c[3]);
s[4] = h[0] * c[4] + h[1] * (c[3] + c[4])
+ h[2] * (c[2] + c[3]) + h[3] * (c[1] + c[2]);
break;
}
case 4: {
s[0] = h[0] * c[0] + h[1] * (c[0] + c[1])
+ h[2] * (c[1] + c[2]) + h[3] * (c[2] + c[3]);
s[1] = h[0] * c[1] + h[1] * (c[0] + c[2])
+ h[2] * (c[0] + c[3]) + h[3] * (c[1] + c[3]);
s[2] = h[0] * c[2] + h[1] * (c[1] + c[3])
+ h[2] * (c[0] + c[3]) + h[3] * (c[0] + c[2]);
s[3] = h[0] * c[3] + h[1] * (c[2] + c[3])
+ h[2] * (c[1] + c[2]) + h[3] * (c[0] + c[1]);
break;
}
case 3: {
s[0] = h[0] * c[0] + h[1] * (c[0] + c[1])
+ h[2] * (c[1] + c[2]) + 2.0 * h[3] * c[2];
s[1] = h[0] * c[1] + (h[1] + h[2]) * (c[0] + c[2])
+ 2.0 * h[3] * c[1];
s[2] = h[0] * c[2] + h[1] * (c[1] + c[2])
+ h[2] * (c[0] + c[1]) + 2.0 * h[3] * c[0];
break;
}
case 2: {
s[0] = (h[0] + h[1] + h[3]) * c[0]
+ (h[1] + 2.0 * h[2] + h[3]) * c[1];
s[1] = (h[0] + h[1] + h[3]) * c[1]
+ (h[1] + 2.0 * h[2] + h[3]) * c[0];
break;
}
case 1: {
s[0] = (h[0] + 2.0 * (h[1] + h[2] + h[3])) * c[0];
break;
}
}
}
break;
}
}
} /* end symmetricFirMirrorOffBounds1D */
} /* end class turboRegImage */
/*====================================================================
| turboRegMask
\===================================================================*/
/*********************************************************************
This class is responsible for the mask preprocessing that takes
place concurrently with user-interface events. It contains methods
to compute the mask pyramids.
********************************************************************/
class turboRegMask
implements
Runnable
{ /* class turboRegMask */
/*....................................................................
private variables
....................................................................*/
private final Stack<float[]> pyramid = new Stack<float[]>();
private Thread t;
private float[] mask;
private int width;
private int height;
private int pyramidDepth;
/*....................................................................
Runnable methods
....................................................................*/
/*********************************************************************
Start the mask precomputations, which are interruptible.
********************************************************************/
public void run (
) {
buildPyramid();
} /* end run */
/*....................................................................
constructors
....................................................................*/
/*********************************************************************
Converts the pixel array of the incoming <code>ImagePlus</code>
object into a local <code>boolean</code> array.
@param imp <code>ImagePlus</code> object to preprocess.
********************************************************************/
public turboRegMask (
final ImagePlus imp
) {
t = new Thread(this);
t.setDaemon(true);
width = imp.getWidth();
height = imp.getHeight();
int k = 0;
turboRegProgressBar.addWorkload(height);
mask = new float[width * height];
if (imp.getType() == ImagePlus.GRAY8) {
final byte[] pixels = (byte[])imp.getProcessor().getPixels();
for (int y = 0; (y < height); y++) {
for (int x = 0; (x < width); x++, k++) {
mask[k] = (float)pixels[k];
}
turboRegProgressBar.stepProgressBar();
}
}
else if (imp.getType() == ImagePlus.GRAY16) {
final short[] pixels = (short[])imp.getProcessor().getPixels();
for (int y = 0; (y < height); y++) {
for (int x = 0; (x < width); x++, k++) {
mask[k] = (float)pixels[k];
}
turboRegProgressBar.stepProgressBar();
}
}
else if (imp.getType() == ImagePlus.GRAY32) {
final float[] pixels = (float[])imp.getProcessor().getPixels();
for (int y = 0; (y < height); y++) {
for (int x = 0; (x < width); x++, k++) {
mask[k] = pixels[k];
}
turboRegProgressBar.stepProgressBar();
}
}
turboRegProgressBar.workloadDone(height);
} /* end turboRegMask */
/*....................................................................
public methods
....................................................................*/
/*********************************************************************
Set to <code>true</code> every pixel of the full-size mask.
********************************************************************/
public void clearMask (
) {
int k = 0;
turboRegProgressBar.addWorkload(height);
for (int y = 0; (y < height); y++) {
for (int x = 0; (x < width); x++) {
mask[k++] = 1.0F;
}
turboRegProgressBar.stepProgressBar();
}
turboRegProgressBar.workloadDone(height);
} /* end clearMask */
/*********************************************************************
Return the full-size mask array.
********************************************************************/
public float[] getMask (
) {
return(mask);
} /* end getMask */
/*********************************************************************
Return the pyramid as a <code>Stack</code> object. A single pyramid
level consists of
<p>
<table border="1">
<tr><th><code>isTarget</code></th>
<th>ML*</th>
<th>ML</th></tr>
<tr><td>true</td>
<td>mask samples</td>
<td>mask samples</td></tr>
<tr><td>false</td>
<td>mask samples</td>
<td>mask samples</td></tr>
</table>
@see turboRegImage#getPyramid()
********************************************************************/
public Stack<float[]> getPyramid (
) {
return(pyramid);
} /* end getPyramid */
/*********************************************************************
Return the thread associated with this <code>turboRegMask</code>
object.
********************************************************************/
public Thread getThread (
) {
return(t);
} /* end getThread */
/*********************************************************************
Set the depth up to which the pyramids should be computed.
@see turboRegMask#getPyramid()
********************************************************************/
public void setPyramidDepth (
final int pyramidDepth
) {
this.pyramidDepth = pyramidDepth;
} /* end setPyramidDepth */
/*....................................................................
private methods
....................................................................*/
/*------------------------------------------------------------------*/
private void buildPyramid (
) {
int fullWidth;
int fullHeight;
float[] fullMask = mask;
int halfWidth = width;
int halfHeight = height;
for (int depth = 1; ((depth < pyramidDepth) && (!t.isInterrupted()));
depth++) {
fullWidth = halfWidth;
fullHeight = halfHeight;
halfWidth /= 2;
halfHeight /= 2;
final float[] halfMask = getHalfMask2D(fullMask, fullWidth, fullHeight);
pyramid.push(halfMask);
fullMask = halfMask;
}
} /* end buildPyramid */
/*------------------------------------------------------------------*/
private float[] getHalfMask2D (
final float[] fullMask,
final int fullWidth,
final int fullHeight
) {
final int halfWidth = fullWidth / 2;
final int halfHeight = fullHeight / 2;
final boolean oddWidth = ((2 * halfWidth) != fullWidth);
int workload = 2 * halfHeight;
final float[] halfMask = new float[halfWidth * halfHeight];
int k = 0;
for (int y = 0; ((y < halfHeight) && (!t.isInterrupted())); y++) {
for (int x = 0; (x < halfWidth); x++) {
halfMask[k++] = 0.0F;
}
turboRegProgressBar.stepProgressBar();
workload--;
}
k = 0;
int n = 0;
for (int y = 0; ((y < (halfHeight - 1)) && (!t.isInterrupted())); y++) {
for (int x = 0; (x < (halfWidth - 1)); x++) {
halfMask[k] += Math.abs(fullMask[n++]);
halfMask[k] += Math.abs(fullMask[n]);
halfMask[++k] += Math.abs(fullMask[n++]);
}
halfMask[k] += Math.abs(fullMask[n++]);
halfMask[k++] += Math.abs(fullMask[n++]);
if (oddWidth) {
n++;
}
for (int x = 0; (x < (halfWidth - 1)); x++) {
halfMask[k - halfWidth] += Math.abs(fullMask[n]);
halfMask[k] += Math.abs(fullMask[n++]);
halfMask[k - halfWidth] += Math.abs(fullMask[n]);
halfMask[k - halfWidth + 1] += Math.abs(fullMask[n]);
halfMask[k] += Math.abs(fullMask[n]);
halfMask[++k] += Math.abs(fullMask[n++]);
}
halfMask[k - halfWidth] += Math.abs(fullMask[n]);
halfMask[k] += Math.abs(fullMask[n++]);
halfMask[k - halfWidth] += Math.abs(fullMask[n]);
halfMask[k++] += Math.abs(fullMask[n++]);
if (oddWidth) {
n++;
}
k -= halfWidth;
turboRegProgressBar.stepProgressBar();
workload--;
}
for (int x = 0; (x < (halfWidth - 1)); x++) {
halfMask[k] += Math.abs(fullMask[n++]);
halfMask[k] += Math.abs(fullMask[n]);
halfMask[++k] += Math.abs(fullMask[n++]);
}
halfMask[k] += Math.abs(fullMask[n++]);
halfMask[k++] += Math.abs(fullMask[n++]);
if (oddWidth) {
n++;
}
k -= halfWidth;
for (int x = 0; (x < (halfWidth - 1)); x++) {
halfMask[k] += Math.abs(fullMask[n++]);
halfMask[k] += Math.abs(fullMask[n]);
halfMask[++k] += Math.abs(fullMask[n++]);
}
halfMask[k] += Math.abs(fullMask[n++]);
halfMask[k] += Math.abs(fullMask[n]);
turboRegProgressBar.stepProgressBar();
workload--;
turboRegProgressBar.skipProgressBar(workload);
turboRegProgressBar.workloadDone(2 * halfHeight);
return(halfMask);
} /* end getHalfMask2D */
} /* end class turboRegMask */
/*====================================================================
| turboRegPointAction
\===================================================================*/
/*********************************************************************
This class implements the various listeners that are in charge of
user interactions when dealing with landmarks. It overrides the
listeners of ImageJ, if any. Those are restored upon restitution
of this <code>ImageCanvas</code> object to ImageJ.
********************************************************************/
class turboRegPointAction
extends
ImageCanvas
implements
AdjustmentListener,
FocusListener,
KeyListener,
MouseListener,
MouseMotionListener
{ /* class turboRegPointAction */
/*....................................................................
private variables
....................................................................*/
private ImagePlus mainImp;
private ImagePlus secondaryImp;
private turboRegPointHandler mainPh;
private turboRegPointHandler secondaryPh;
private turboRegPointToolbar tb;
private static final long serialVersionUID = 1L;
/*....................................................................
AdjustmentListener methods
....................................................................*/
/*********************************************************************
Listen to <code>AdjustmentEvent</code> events.
@param e Ignored.
********************************************************************/
public synchronized void adjustmentValueChanged (
AdjustmentEvent e
) {
updateAndDraw();
} /* adjustmentValueChanged */
/*....................................................................
FocusListener methods
....................................................................*/
/*********************************************************************
Listen to <code>focusGained</code> events.
@param e Ignored.
********************************************************************/
public void focusGained (
final FocusEvent e
) {
updateAndDraw();
} /* end focusGained */
/*********************************************************************
Listen to <code>focusGained</code> events.
@param e Ignored.
********************************************************************/
public void focusLost (
final FocusEvent e
) {
updateAndDraw();
} /* end focusLost */
/*....................................................................
KeyListener methods
....................................................................*/
/*********************************************************************
Listen to <code>keyPressed</code> events.
@param e The expected key codes are as follows:
<ul><li><code>KeyEvent.VK_COMMA</code>:
display the previous slice, if any;</li>
<li><code>KeyEvent.VK_DOWN</code>: move down the current landmark;</li>
<li><code>KeyEvent.VK_LEFT</code>: move the current landmark to the left;</li>
<li><code>KeyEvent.VK_PERIOD</code>: display the next slice, if any;</li>
<li><code>KeyEvent.VK_SPACE</code>: select the current landmark;</li>
<li><code>KeyEvent.VK_RIGHT</code>:
move the current landmark to the right;</li>
<li><code>KeyEvent.VK_UP</code>: move up the current landmark.</li></ul>
********************************************************************/
public void keyPressed (
final KeyEvent e
) {
switch (e.getKeyCode()) {
case KeyEvent.VK_COMMA: {
if (1 < mainImp.getCurrentSlice()) {
mainImp.setSlice(mainImp.getCurrentSlice() - 1);
updateStatus();
}
return;
}
case KeyEvent.VK_PERIOD: {
if (mainImp.getCurrentSlice() < mainImp.getStackSize()) {
mainImp.setSlice(mainImp.getCurrentSlice() + 1);
updateStatus();
}
return;
}
}
final int x = mainPh.getPoint().x;
final int y = mainPh.getPoint().y;
switch (e.getKeyCode()) {
case KeyEvent.VK_DOWN: {
mainPh.movePoint(mainImp.getWindow().getCanvas().screenX(x),
mainImp.getWindow().getCanvas().screenY(y
+ (int)Math.ceil(1.0
/ mainImp.getWindow().getCanvas().getMagnification())));
mainImp.setRoi(mainPh);
break;
}
case KeyEvent.VK_LEFT: {
mainPh.movePoint(mainImp.getWindow().getCanvas().screenX(x
- (int)Math.ceil(1.0
/ mainImp.getWindow().getCanvas().getMagnification())),
mainImp.getWindow().getCanvas().screenY(y));
mainImp.setRoi(mainPh);
break;
}
case KeyEvent.VK_RIGHT: {
mainPh.movePoint(mainImp.getWindow().getCanvas().screenX(x
+ (int)Math.ceil(1.0
/ mainImp.getWindow().getCanvas().getMagnification())),
mainImp.getWindow().getCanvas().screenY(y));
mainImp.setRoi(mainPh);
break;
}
case KeyEvent.VK_SPACE: {
break;
}
case KeyEvent.VK_UP: {
mainPh.movePoint(mainImp.getWindow().getCanvas().screenX(x),
mainImp.getWindow().getCanvas().screenY(y
- (int)Math.ceil(1.0
/ mainImp.getWindow().getCanvas().getMagnification())));
mainImp.setRoi(mainPh);
break;
}
}
updateStatus();
} /* end keyPressed */
/*********************************************************************
Listen to <code>keyReleased</code> events.
@param e Ignored.
********************************************************************/
public void keyReleased (
final KeyEvent e
) {
} /* end keyReleased */
/*********************************************************************
Listen to <code>keyTyped</code> events.
@param e Ignored.
********************************************************************/
public void keyTyped (
final KeyEvent e
) {
} /* end keyTyped */
/*....................................................................
MouseListener methods
....................................................................*/
/*********************************************************************
Listen to <code>mouseClicked</code> events.
@param e Ignored.
********************************************************************/
public void mouseClicked (
final MouseEvent e
) {
} /* end mouseClicked */
/*********************************************************************
Listen to <code>mouseEntered</code> events. Change the cursor to a
crosshair.
@param e Event.
********************************************************************/
public void mouseEntered (
final MouseEvent e
) {
WindowManager.setCurrentWindow(mainImp.getWindow());
mainImp.getWindow().toFront();
mainImp.getWindow().getCanvas().setCursor(crosshairCursor);
updateAndDraw();
} /* end mouseEntered */
/*********************************************************************
Listen to <code>mouseExited</code> events. Change the cursor to the
default cursor. Update the ImageJ status.
@param e Event.
********************************************************************/
public void mouseExited (
final MouseEvent e
) {
mainImp.getWindow().getCanvas().setCursor(defaultCursor);
IJ.showStatus("");
} /* end mouseExited */
/*********************************************************************
Listen to <code>mousePressed</code> events. Update the current point
or call the ImageJ's zoom methods.
@param e Event.
********************************************************************/
public void mousePressed (
final MouseEvent e
) {
final int x = e.getX();
final int y = e.getY();
switch (tb.getCurrentTool()) {
case turboRegPointHandler.MAGNIFIER: {
int flags = e.getModifiers();
if ((flags & (Event.ALT_MASK | Event.META_MASK | Event.CTRL_MASK))
!= 0) {
mainImp.getWindow().getCanvas().zoomOut(x, y);
}
else {
mainImp.getWindow().getCanvas().zoomIn(x, y);
}
break;
}
case turboRegPointHandler.MOVE_CROSS: {
final int currentPoint = mainPh.findClosest(x, y);
secondaryPh.setCurrentPoint(currentPoint);
updateAndDraw();
break;
}
}
} /* end mousePressed */
/*********************************************************************
Listen to <code>mouseReleased</code> events.
@param e Ignored.
********************************************************************/
public void mouseReleased (
final MouseEvent e
) {
} /* end mouseReleased */
/*....................................................................
MouseMotionListener methods
....................................................................*/
/*********************************************************************
Listen to <code>mouseDragged</code> events. Move the position of
the current point. Update the window's ROI. Update ImageJ's window.
@param e Event.
@see turboRegPointHandler#movePoint(int, int)
@see turboRegPointAction#mouseMoved(java.awt.event.MouseEvent)
********************************************************************/
public void mouseDragged (
final MouseEvent e
) {
final int x = e.getX();
final int y = e.getY();
if (tb.getCurrentTool() == turboRegPointHandler.MOVE_CROSS) {
mainPh.movePoint(x, y);
updateAndDraw();
}
mouseMoved(e);
} /* end mouseDragged */
/*********************************************************************
Listen to <code>mouseMoved</code> events. Update the ImageJ status
by displaying the value of the pixel under the cursor hot spot.
@param e Event.
********************************************************************/
public void mouseMoved (
final MouseEvent e
) {
int x = e.getX();
int y = e.getY();
x = mainImp.getWindow().getCanvas().offScreenX(x);
y = mainImp.getWindow().getCanvas().offScreenY(y);
IJ.showStatus(mainImp.getLocationAsString(x, y) + getValueAsString(x, y));
} /* end mouseMoved */
/*....................................................................
constructors
....................................................................*/
/*********************************************************************
Keep a local copy of the <code>turboRegPointHandler</code> and
<code>turboRegPointToolbar</code> objects.
@param imp <code>ImagePlus</code> object.
@param ph <code>turboRegPointHandler</code> object.
@param tb <code>turboRegPointToolbar</code> object.
********************************************************************/
public turboRegPointAction (
final ImagePlus imp,
final turboRegPointHandler ph,
final turboRegPointToolbar tb
) {
super(imp);
this.mainImp = imp;
this.mainPh = ph;
this.tb = tb;
} /* end turboRegPointAction */
/*....................................................................
public methods
....................................................................*/
/*********************************************************************
Set a reference to the <code>ImagePlus</code> and
<code>turboRegPointHandler</code> objects of the other image.
@param secondaryImp <code>ImagePlus</code> object.
@param secondaryPh <code>turboRegPointHandler</code> object.
********************************************************************/
public void setSecondaryPointHandler (
final ImagePlus secondaryImp,
final turboRegPointHandler secondaryPh
) {
this.secondaryImp = secondaryImp;
this.secondaryPh = secondaryPh;
} /* end setSecondaryPointHandler */
/*....................................................................
private methods
....................................................................*/
/*------------------------------------------------------------------*/
private String getValueAsString (
final int x,
final int y
) {
final Calibration cal = imp.getCalibration();
final int[] v = imp.getPixel(x, y);
switch (imp.getType()) {
case ImagePlus.GRAY8:
case ImagePlus.GRAY16: {
final double cValue = cal.getCValue(v[0]);
if (cValue==v[0]) {
return(", value=" + v[0]);
}
else {
return(", value=" + IJ.d2s(cValue) + " (" + v[0] + ")");
}
}
case ImagePlus.GRAY32: {
return(", value=" + Float.intBitsToFloat(v[0]));
}
case ImagePlus.COLOR_256: {
return(", index=" + v[3] + ", value="
+ v[0] + "," + v[1] + "," + v[2]);
}
case ImagePlus.COLOR_RGB: {
return(", value=" + v[0] + "," + v[1] + "," + v[2]);
}
default: {
return("");
}
}
} /* end getValueAsString */
/*------------------------------------------------------------------*/
private void updateAndDraw (
) {
mainImp.setRoi(mainPh);
secondaryImp.setRoi(secondaryPh);
} /* end updateAndDraw */
/*------------------------------------------------------------------*/
private void updateStatus (
) {
final Point p = mainPh.getPoint();
if (p == null) {
IJ.showStatus("");
return;
}
final int x = p.x;
final int y = p.y;
IJ.showStatus(imp.getLocationAsString(x, y) + getValueAsString(x, y));
} /* end updateStatus */
} /* end class turboRegPointAction */
/*====================================================================
| turboRegPointHandler
\===================================================================*/
/*********************************************************************
This class implements the graphic interactions when dealing with
landmarks.
********************************************************************/
class turboRegPointHandler
extends
PolygonRoi
{ /* class turboRegPointHandler */
/*....................................................................
public variables
....................................................................*/
/*********************************************************************
The magnifying tool is set in eleventh position to be coherent with
ImageJ.
********************************************************************/
public static final int MAGNIFIER = 11;
/*********************************************************************
The moving tool is set in second position to be coherent with the
<code>PointPicker_</code> plugin.
********************************************************************/
public static final int MOVE_CROSS = 1;
/*********************************************************************
The number of points we are willing to deal with is at most
<code>4</code>.
@see turboRegDialog#transformation
********************************************************************/
public static final int NUM_POINTS = 4;
/*....................................................................
private variables
....................................................................*/
/*********************************************************************
Serialization version number.
********************************************************************/
private static final long serialVersionUID = 1L;
/*********************************************************************
The drawn landmarks fit in a 11x11 matrix.
********************************************************************/
private static final int CROSS_HALFSIZE = 5;
/*********************************************************************
The golden ratio mathematical constant determines where to put the
initial landmarks.
********************************************************************/
private static final double GOLDEN_RATIO = 0.5 * (Math.sqrt(5.0) - 1.0);
private boolean interactive = true;
private boolean started = false;
private double[][] precisionPoint = new double[NUM_POINTS][2];
private final Point[] point = new Point[NUM_POINTS];
private final Color[] spectrum = new Color[NUM_POINTS];
private int transformation;
private int currentPoint = 0;
/*....................................................................
PolygonRoi methods
....................................................................*/
/*********************************************************************
Draw the landmarks. Outline the current point if the window has focus.
@param g Graphics environment.
********************************************************************/
public void draw (
final Graphics g
) {
if (started) {
final double mag = ic.getMagnification();
final int dx = (int)(mag / 2.0);
final int dy = (int)(mag / 2.0);
Point p;
if (transformation == turboRegDialog.RIGID_BODY) {
if (currentPoint == 0) {
for (int k = 1; (k < transformation); k++) {
p = point[k];
g.setColor(spectrum[k]);
g.fillRect(ic.screenX(p.x) - 2 + dx,
ic.screenY(p.y) - 2 + dy, 5, 5);
}
drawHorizon(g);
p = point[0];
g.setColor(spectrum[0]);
if (WindowManager.getCurrentImage() == imp) {
g.drawLine(ic.screenX(p.x - CROSS_HALFSIZE - 1) + dx,
ic.screenY(p.y - 1) + dy,
ic.screenX(p.x - 1) + dx,
ic.screenY(p.y - 1) + dy);
g.drawLine(ic.screenX(p.x - 1) + dx,
ic.screenY(p.y - 1) + dy,
ic.screenX(p.x - 1) + dx,
ic.screenY(p.y - CROSS_HALFSIZE - 1) + dy);
g.drawLine(ic.screenX(p.x - 1) + dx,
ic.screenY(p.y - CROSS_HALFSIZE - 1) + dy,
ic.screenX(p.x + 1) + dx,
ic.screenY(p.y - CROSS_HALFSIZE - 1) + dy);
g.drawLine(ic.screenX(p.x + 1) + dx,
ic.screenY(p.y - CROSS_HALFSIZE - 1) + dy,
ic.screenX(p.x + 1) + dx,
ic.screenY(p.y - 1) + dy);
g.drawLine(ic.screenX(p.x + 1) + dx,
ic.screenY(p.y - 1) + dy,
ic.screenX(p.x + CROSS_HALFSIZE + 1) + dx,
ic.screenY(p.y - 1) + dy);
g.drawLine(ic.screenX(p.x + CROSS_HALFSIZE + 1) + dx,
ic.screenY(p.y - 1) + dy,
ic.screenX(p.x + CROSS_HALFSIZE + 1) + dx,
ic.screenY(p.y + 1) + dy);
g.drawLine(ic.screenX(p.x + CROSS_HALFSIZE + 1) + dx,
ic.screenY(p.y + 1) + dy,
ic.screenX(p.x + 1) + dx,
ic.screenY(p.y + 1) + dy);
g.drawLine(ic.screenX(p.x + 1) + dx,
ic.screenY(p.y + 1) + dy,
ic.screenX(p.x + 1) + dx,
ic.screenY(p.y + CROSS_HALFSIZE + 1) + dy);
g.drawLine(ic.screenX(p.x + 1) + dx,
ic.screenY(p.y + CROSS_HALFSIZE + 1) + dy,
ic.screenX(p.x - 1) + dx,
ic.screenY(p.y + CROSS_HALFSIZE + 1) + dy);
g.drawLine(ic.screenX(p.x - 1) + dx,
ic.screenY(p.y + CROSS_HALFSIZE + 1) + dy,
ic.screenX(p.x - 1) + dx,
ic.screenY(p.y + 1) + dy);
g.drawLine(ic.screenX(p.x - 1) + dx,
ic.screenY(p.y + 1) + dy,
ic.screenX(p.x - CROSS_HALFSIZE - 1) + dx,
ic.screenY(p.y + 1) + dy);
g.drawLine(ic.screenX(p.x - CROSS_HALFSIZE - 1) + dx,
ic.screenY(p.y + 1) + dy,
ic.screenX(p.x - CROSS_HALFSIZE - 1) + dx,
ic.screenY(p.y - 1) + dy);
if (1.0 < ic.getMagnification()) {
g.drawLine(ic.screenX(p.x - CROSS_HALFSIZE) + dx,
ic.screenY(p.y) + dy,
ic.screenX(p.x + CROSS_HALFSIZE) + dx,
ic.screenY(p.y) + dy);
g.drawLine(ic.screenX(p.x) + dx,
ic.screenY(p.y - CROSS_HALFSIZE) + dy,
ic.screenX(p.x) + dx,
ic.screenY(p.y + CROSS_HALFSIZE) + dy);
}
}
else {
g.drawLine(ic.screenX(p.x - CROSS_HALFSIZE + 1) + dx,
ic.screenY(p.y - CROSS_HALFSIZE + 1) + dy,
ic.screenX(p.x + CROSS_HALFSIZE - 1) + dx,
ic.screenY(p.y + CROSS_HALFSIZE - 1) + dy);
g.drawLine(ic.screenX(p.x - CROSS_HALFSIZE + 1) + dx,
ic.screenY(p.y + CROSS_HALFSIZE - 1) + dy,
ic.screenX(p.x + CROSS_HALFSIZE - 1) + dx,
ic.screenY(p.y - CROSS_HALFSIZE + 1) + dy);
}
}
else {
p = point[0];
g.setColor(spectrum[0]);
g.drawLine(ic.screenX(p.x - CROSS_HALFSIZE) + dx,
ic.screenY(p.y) + dy,
ic.screenX(p.x + CROSS_HALFSIZE) + dx,
ic.screenY(p.y) + dy);
g.drawLine(ic.screenX(p.x) + dx,
ic.screenY(p.y - CROSS_HALFSIZE) + dy,
ic.screenX(p.x) + dx,
ic.screenY(p.y + CROSS_HALFSIZE) + dy);
drawHorizon(g);
if (WindowManager.getCurrentImage() == imp) {
drawArcs(g);
for (int k = 1; (k < transformation); k++) {
p = point[k];
g.setColor(spectrum[k]);
if (k == currentPoint) {
g.drawRect(ic.screenX(p.x) - 3 + dx,
ic.screenY(p.y) - 3 + dy, 6, 6);
}
else {
g.fillRect(ic.screenX(p.x) - 2 + dx,
ic.screenY(p.y) - 2 + dy, 5, 5);
}
}
}
else {
for (int k = 1; (k < transformation); k++) {
p = point[k];
g.setColor(spectrum[k]);
if (k == currentPoint) {
g.drawRect(ic.screenX(p.x) - 2 + dx,
ic.screenY(p.y) - 2 + dy, 5, 5);
}
else {
g.fillRect(ic.screenX(p.x) - 2 + dx,
ic.screenY(p.y) - 2 + dy, 5, 5);
}
}
}
}
}
else {
for (int k = 0; (k < (transformation / 2)); k++) {
p = point[k];
g.setColor(spectrum[k]);
if (k == currentPoint) {
if (WindowManager.getCurrentImage() == imp) {
g.drawLine(ic.screenX(p.x - CROSS_HALFSIZE - 1) + dx,
ic.screenY(p.y - 1) + dy,
ic.screenX(p.x - 1) + dx,
ic.screenY(p.y - 1) + dy);
g.drawLine(ic.screenX(p.x - 1) + dx,
ic.screenY(p.y - 1) + dy,
ic.screenX(p.x - 1) + dx,
ic.screenY(p.y - CROSS_HALFSIZE - 1) + dy);
g.drawLine(ic.screenX(p.x - 1) + dx,
ic.screenY(p.y - CROSS_HALFSIZE - 1) + dy,
ic.screenX(p.x + 1) + dx,
ic.screenY(p.y - CROSS_HALFSIZE - 1) + dy);
g.drawLine(ic.screenX(p.x + 1) + dx,
ic.screenY(p.y - CROSS_HALFSIZE - 1) + dy,
ic.screenX(p.x + 1) + dx,
ic.screenY(p.y - 1) + dy);
g.drawLine(ic.screenX(p.x + 1) + dx,
ic.screenY(p.y - 1) + dy,
ic.screenX(p.x + CROSS_HALFSIZE + 1) + dx,
ic.screenY(p.y - 1) + dy);
g.drawLine(ic.screenX(p.x + CROSS_HALFSIZE + 1) + dx,
ic.screenY(p.y - 1) + dy,
ic.screenX(p.x + CROSS_HALFSIZE + 1) + dx,
ic.screenY(p.y + 1) + dy);
g.drawLine(ic.screenX(p.x + CROSS_HALFSIZE + 1) + dx,
ic.screenY(p.y + 1) + dy,
ic.screenX(p.x + 1) + dx,
ic.screenY(p.y + 1) + dy);
g.drawLine(ic.screenX(p.x + 1) + dx,
ic.screenY(p.y + 1) + dy,
ic.screenX(p.x + 1) + dx,
ic.screenY(p.y + CROSS_HALFSIZE + 1) + dy);
g.drawLine(ic.screenX(p.x + 1) + dx,
ic.screenY(p.y + CROSS_HALFSIZE + 1) + dy,
ic.screenX(p.x - 1) + dx,
ic.screenY(p.y + CROSS_HALFSIZE + 1) + dy);
g.drawLine(ic.screenX(p.x - 1) + dx,
ic.screenY(p.y + CROSS_HALFSIZE + 1) + dy,
ic.screenX(p.x - 1) + dx,
ic.screenY(p.y + 1) + dy);
g.drawLine(ic.screenX(p.x - 1) + dx,
ic.screenY(p.y + 1) + dy,
ic.screenX(p.x - CROSS_HALFSIZE - 1) + dx,
ic.screenY(p.y + 1) + dy);
g.drawLine(ic.screenX(p.x - CROSS_HALFSIZE - 1) + dx,
ic.screenY(p.y + 1) + dy,
ic.screenX(p.x - CROSS_HALFSIZE - 1) + dx,
ic.screenY(p.y - 1) + dy);
if (1.0 < ic.getMagnification()) {
g.drawLine(ic.screenX(p.x - CROSS_HALFSIZE) + dx,
ic.screenY(p.y) + dy,
ic.screenX(p.x + CROSS_HALFSIZE) + dx,
ic.screenY(p.y) + dy);
g.drawLine(ic.screenX(p.x) + dx,
ic.screenY(p.y - CROSS_HALFSIZE) + dy,
ic.screenX(p.x) + dx,
ic.screenY(p.y + CROSS_HALFSIZE) + dy);
}
}
else {
g.drawLine(ic.screenX(p.x - CROSS_HALFSIZE + 1) + dx,
ic.screenY(p.y - CROSS_HALFSIZE + 1) + dy,
ic.screenX(p.x + CROSS_HALFSIZE - 1) + dx,
ic.screenY(p.y + CROSS_HALFSIZE - 1) + dy);
g.drawLine(ic.screenX(p.x - CROSS_HALFSIZE + 1) + dx,
ic.screenY(p.y + CROSS_HALFSIZE - 1) + dy,
ic.screenX(p.x + CROSS_HALFSIZE - 1) + dx,
ic.screenY(p.y - CROSS_HALFSIZE + 1) + dy);
}
}
else {
g.drawLine(ic.screenX(p.x - CROSS_HALFSIZE) + dx,
ic.screenY(p.y) + dy,
ic.screenX(p.x + CROSS_HALFSIZE) + dx,
ic.screenY(p.y) + dy);
g.drawLine(ic.screenX(p.x) + dx,
ic.screenY(p.y - CROSS_HALFSIZE) + dy,
ic.screenX(p.x) + dx,
ic.screenY(p.y + CROSS_HALFSIZE) + dy);
}
}
}
if (updateFullWindow) {
updateFullWindow = false;
imp.draw();
}
}
} /* end draw */
/*....................................................................
constructors
....................................................................*/
/*********************************************************************
Keep a local copy of the points and of the transformation.
********************************************************************/
public turboRegPointHandler (
final double[][] precisionPoint,
final int transformation
) {
super(new Polygon(), POLYGON);
this.transformation = transformation;
this.precisionPoint = precisionPoint;
interactive = false;
} /* end turboRegPointHandler */
/*********************************************************************
Keep a local copy of the <code>ImagePlus</code> object. Set the
landmarks to their initial position for the given transformation.
@param imp <code>ImagePlus</code> object.
@param transformation Transformation code.
@see turboRegDialog#restoreAll()
********************************************************************/
public turboRegPointHandler (
final ImagePlus imp,
final int transformation
) {
super(0, 0, imp);
this.imp = imp;
this.transformation = transformation;
setTransformation(transformation);
imp.setRoi(this);
started = true;
} /* end turboRegPointHandler */
/*********************************************************************
Set the landmarks to their initial position for the given
transformation.
@param transformation Transformation code.
@see turboRegDialog#restoreAll()
********************************************************************/
public turboRegPointHandler (
final int transformation,
final ImagePlus imp
) {
super(new Polygon(), POLYGON);
this.imp = imp;
this.transformation = transformation;
setTransformation(transformation);
imp.setRoi(this);
started = true;
} /* end turboRegPointHandler */
/*....................................................................
public methods
....................................................................*/
/*********************************************************************
Set the current point as that which is closest to (x, y).
@param x Horizontal coordinate in canvas units.
@param y Vertical coordinate in canvas units.
********************************************************************/
public int findClosest (
int x,
int y
) {
x = ic.offScreenX(x);
y = ic.offScreenY(y);
int closest = 0;
Point p = point[closest];
double distance = (double)(x - p.x) * (double)(x - p.x)
+ (double)(y - p.y) * (double)(y - p.y);
double candidate;
if (transformation == turboRegDialog.RIGID_BODY) {
for (int k = 1; (k < transformation); k++) {
p = point[k];
candidate = (double)(x - p.x) * (double)(x - p.x)
+ (double)(y - p.y) * (double)(y - p.y);
if (candidate < distance) {
distance = candidate;
closest = k;
}
}
}
else {
for (int k = 1; (k < (transformation / 2)); k++) {
p = point[k];
candidate = (double)(x - p.x) * (double)(x - p.x)
+ (double)(y - p.y) * (double)(y - p.y);
if (candidate < distance) {
distance = candidate;
closest = k;
}
}
}
currentPoint = closest;
return(currentPoint);
} /* end findClosest */
/*********************************************************************
Return the current point as a <code>Point</code> object.
********************************************************************/
public Point getPoint (
) {
return(point[currentPoint]);
} /* end getPoint */
/*********************************************************************
Return all landmarks as an array <code>double[transformation / 2][2]</code>,
except for a rigid-body transformation for which the array has size
<code>double[3][2]</code>.
********************************************************************/
public double[][] getPoints (
) {
if (interactive) {
if (transformation == turboRegDialog.RIGID_BODY) {
double[][] points = new double[transformation][2];
for (int k = 0; (k < transformation); k++) {
points[k][0] = (double)point[k].x;
points[k][1] = (double)point[k].y;
}
return(points);
}
else {
double[][] points = new double[transformation / 2][2];
for (int k = 0; (k < (transformation / 2)); k++) {
points[k][0] = (double)point[k].x;
points[k][1] = (double)point[k].y;
}
return(points);
}
}
else {
return(precisionPoint);
}
} /* end getPoints */
/*********************************************************************
Modify the location of the current point. Clip the admissible range
to the image size.
@param x Desired new horizontal coordinate in canvas units.
@param y Desired new vertical coordinate in canvas units.
********************************************************************/
public void movePoint (
int x,
int y
) {
interactive = true;
x = ic.offScreenX(x);
y = ic.offScreenY(y);
x = (x < 0) ? (0) : (x);
x = (imp.getWidth() <= x) ? (imp.getWidth() - 1) : (x);
y = (y < 0) ? (0) : (y);
y = (imp.getHeight() <= y) ? (imp.getHeight() - 1) : (y);
if ((transformation == turboRegDialog.RIGID_BODY) && (currentPoint != 0)) {
final Point p = new Point(x, y);
final Point q = point[3 - currentPoint];
final double radius = 0.5 * Math.sqrt(
(ic.screenX(p.x) - ic.screenX(q.x))
* (ic.screenX(p.x) - ic.screenX(q.x))
+ (ic.screenY(p.y) - ic.screenY(q.y))
* (ic.screenY(p.y) - ic.screenY(q.y)));
if ((double)CROSS_HALFSIZE < radius) {
point[currentPoint].x = x;
point[currentPoint].y = y;
}
}
else {
point[currentPoint].x = x;
point[currentPoint].y = y;
}
} /* end movePoint */
/*********************************************************************
Set a new current point.
@param currentPoint New current point index.
********************************************************************/
public void setCurrentPoint (
final int currentPoint
) {
this.currentPoint = currentPoint;
} /* end setCurrentPoint */
/*********************************************************************
Set new position for all landmarks, without clipping.
@param precisionPoint New coordinates in canvas units.
********************************************************************/
public void setPoints (
final double[][] precisionPoint
) {
interactive = false;
if (transformation == turboRegDialog.RIGID_BODY) {
for (int k = 0; (k < transformation); k++) {
point[k].x = (int)Math.round(precisionPoint[k][0]);
point[k].y = (int)Math.round(precisionPoint[k][1]);
this.precisionPoint[k][0] = precisionPoint[k][0];
this.precisionPoint[k][1] = precisionPoint[k][1];
}
}
else {
for (int k = 0; (k < (transformation / 2)); k++) {
point[k].x = (int)Math.round(precisionPoint[k][0]);
point[k].y = (int)Math.round(precisionPoint[k][1]);
this.precisionPoint[k][0] = precisionPoint[k][0];
this.precisionPoint[k][1] = precisionPoint[k][1];
}
}
} /* end setPoints */
/*********************************************************************
Reset the landmarks to their initial position for the given
transformation.
@param transformation Transformation code.
********************************************************************/
public void setTransformation (
final int transformation
) {
interactive = true;
this.transformation = transformation;
final int width = imp.getWidth();
final int height = imp.getHeight();
currentPoint = 0;
switch (transformation) {
case turboRegDialog.TRANSLATION: {
point[0] = new Point(
Math.round((float)(Math.floor(0.5 * (double)width))),
Math.round((float)(Math.floor(0.5 * (double)height))));
break;
}
case turboRegDialog.RIGID_BODY: {
point[0] = new Point(
Math.round((float)(Math.floor(0.5 * (double)width))),
Math.round((float)(Math.floor(0.5 * (double)height))));
point[1] = new Point(
Math.round((float)(Math.floor(0.5 * (double)width))),
Math.round((float)(Math.ceil(0.25 * GOLDEN_RATIO
* (double)height))));
point[2] = new Point(
Math.round((float)(Math.floor(0.5 * (double)width))),
height - Math.round((float)(Math.ceil(0.25 * GOLDEN_RATIO
* (double)height))));
break;
}
case turboRegDialog.SCALED_ROTATION: {
point[0] = new Point(
Math.round((float)(Math.floor(0.25 * GOLDEN_RATIO
* (double)width))),
Math.round((float)(Math.floor(0.5 * (double)height))));
point[1] = new Point(
width - Math.round((float)(Math.ceil(0.25 * GOLDEN_RATIO
* (double)width))),
Math.round((float)(Math.floor(0.5 * (double)height))));
break;
}
case turboRegDialog.AFFINE: {
point[0] = new Point(
Math.round((float)(Math.floor(0.5 * (double)width))),
Math.round((float)(Math.floor(0.25 * GOLDEN_RATIO
* (double)height))));
point[1] = new Point(
Math.round((float)(Math.floor(0.25 * GOLDEN_RATIO
* (double)width))),
height - Math.round((float)(Math.ceil(0.25 * GOLDEN_RATIO
* (double)height))));
point[2] = new Point(
width - Math.round((float)(Math.ceil(0.25 * GOLDEN_RATIO
* (double)width))),
height - Math.round((float)(Math.ceil(0.25 * GOLDEN_RATIO
* (double)height))));
break;
}
case turboRegDialog.BILINEAR: {
point[0] = new Point(
Math.round((float)(Math.floor(0.25 * GOLDEN_RATIO
* (double)width))),
Math.round((float)(Math.floor(0.25 * GOLDEN_RATIO
* (double)height))));
point[1] = new Point(
Math.round((float)(Math.floor(0.25 * GOLDEN_RATIO
* (double)width))),
height - Math.round((float)(Math.ceil(0.25 * GOLDEN_RATIO
* (double)height))));
point[2] = new Point(
width - Math.round((float)(Math.ceil(0.25 * GOLDEN_RATIO
* (double)width))),
Math.round((float)(Math.floor(0.25 * GOLDEN_RATIO
* (double)height))));
point[3] = new Point(
width - Math.round((float)(Math.ceil(0.25 * GOLDEN_RATIO
* (double)width))),
height - Math.round((float)(Math.ceil(0.25 * GOLDEN_RATIO
* (double)height))));
break;
}
}
setSpectrum();
imp.updateAndDraw();
} /* end setTransformation */
/*....................................................................
private methods
....................................................................*/
/*------------------------------------------------------------------*/
private void drawArcs (
final Graphics g
) {
final double mag = ic.getMagnification();
final int dx = (int)(mag / 2.0);
final int dy = (int)(mag / 2.0);
final Point p = point[1];
final Point q = point[2];
final double x0 = (double)(ic.screenX(p.x) + ic.screenX(q.x));
final double y0 = (double)(ic.screenY(p.y) + ic.screenY(q.y));
final double dx0 = (double)(ic.screenX(p.x) - ic.screenX(q.x));
final double dy0 = (double)(ic.screenY(p.y) - ic.screenY(q.y));
final double radius = 0.5 * Math.sqrt(dx0 * dx0 + dy0 * dy0);
final double orientation = Math.atan2(dx0, dy0);
final double spacerAngle = Math.asin((double)CROSS_HALFSIZE / radius);
g.setColor(spectrum[1]);
g.drawArc((int)Math.round(0.5 * x0 - radius) + dx,
(int)Math.round(0.5 * y0 - radius) + dy,
(int)Math.round(2.0 * radius), (int)Math.round(2.0 * radius),
(int)Math.round((orientation + spacerAngle + Math.PI)
* 180.0 / Math.PI),
(int)Math.round((Math.PI - 2.0 * spacerAngle) * 180.0 / Math.PI));
g.setColor(spectrum[2]);
g.drawArc((int)Math.round(0.5 * x0 - radius) + dx,
(int)Math.round(0.5 * y0 - radius) + dy,
(int)Math.round(2.0 * radius), (int)Math.round(2.0 * radius),
(int)Math.round((orientation + spacerAngle) * 180.0 / Math.PI),
(int)Math.round((Math.PI - 2.0 * spacerAngle) * 180.0 / Math.PI));
} /* end drawArcs */
/*------------------------------------------------------------------*/
private void drawHorizon (
final Graphics g
) {
final double mag = ic.getMagnification();
final int dx = (int)(mag / 2.0);
final int dy = (int)(mag / 2.0);
final Point p = point[1];
final Point q = point[2];
final double x0 = (double)(ic.screenX(p.x) + ic.screenX(q.x));
final double y0 = (double)(ic.screenY(p.y) + ic.screenY(q.y));
final double dx0 = (double)(ic.screenX(p.x) - ic.screenX(q.x));
final double dy0 = (double)(ic.screenY(p.y) - ic.screenY(q.y));
final double radius = 0.5 * Math.sqrt(dx0 * dx0 + dy0 * dy0);
final double spacerAngle = Math.asin((double)CROSS_HALFSIZE / radius);
final double s0 = Math.sin(spacerAngle);
final double s = 0.5 * dx0 / radius;
final double c = 0.5 * dy0 / radius;
double u;
double v;
g.setColor(spectrum[1]);
u = 0.5 * (x0 + s0 * dx0);
v = 0.5 * (y0 + s0 * dy0);
if (Math.abs(s) < Math.abs(c)) {
g.drawLine(-dx, (int)Math.round(
v + (u + 2.0 * (double)dx) * s / c) + dy,
(int)Math.round(mag * (double)ic.getSrcRect().width - 1.0) + dx,
(int)Math.round(v - (mag * (double)ic.getSrcRect().width - 1.0 - u)
* s / c) + dy);
}
else {
g.drawLine((int)Math.round(
u + (v + 2.0 * (double)dy) * c / s) + dx, -dy,
(int)Math.round(u - (mag * (double)ic.getSrcRect().height - 1.0 - v)
* c / s) + dx,
(int)Math.round(mag * (double)ic.getSrcRect().height - 1.0) + dy);
}
g.setColor(spectrum[2]);
u = 0.5 * (x0 - s0 * dx0);
v = 0.5 * (y0 - s0 * dy0);
if (Math.abs(s) < Math.abs(c)) {
g.drawLine(-dx, (int)Math.round(
v + (u + 2.0 * (double)dx) * s / c) + dy,
(int)Math.round(mag * (double)ic.getSrcRect().width - 1.0) + dx,
(int)Math.round(v - (mag * (double)ic.getSrcRect().width - 1.0 - u)
* s / c) + dy);
}
else {
g.drawLine((int)Math.round(
u + (v + 2.0 * (double)dy) * c / s) + dx, -dy,
(int)Math.round(u - (mag * (double)ic.getSrcRect().height - 1.0 - v)
* c / s) + dx, (int)Math.round(
mag * (double)ic.getSrcRect().height - 1.0) + dy);
}
} /* end drawHorizon */
/*------------------------------------------------------------------*/
private void setSpectrum (
) {
if (transformation == turboRegDialog.RIGID_BODY) {
spectrum[0] = Color.green;
spectrum[1] = new Color(16, 119, 169);
spectrum[2] = new Color(119, 85, 51);
}
else {
spectrum[0] = Color.green;
spectrum[1] = Color.yellow;
spectrum[2] = Color.magenta;
spectrum[3] = Color.cyan;
}
} /* end setSpectrum */
} /* end class turboRegPointHandler */
/*====================================================================
| turboRegPointToolbar
\===================================================================*/
/*********************************************************************
This class implements the user interactions when dealing with
the toolbar in the ImageJ's window.
********************************************************************/
class turboRegPointToolbar
extends
Canvas
implements
MouseListener
{ /* class turboRegPointToolbar */
/*....................................................................
private variables
....................................................................*/
/*********************************************************************
Serialization version number.
********************************************************************/
private static final long serialVersionUID = 1L;
/*********************************************************************
Same number of tools than in ImageJ version 1.22
********************************************************************/
private static final int NUM_TOOLS = 19;
/*********************************************************************
Same tool offset than in ImageJ version 1.22
********************************************************************/
private static final int OFFSET = 3;
/*********************************************************************
Same tool size than in ImageJ version 1.22
********************************************************************/
private static final int SIZE = 22;
private final Color gray = Color.lightGray;
private final Color brighter = gray.brighter();
private final Color darker = gray.darker();
private final Color evenDarker = darker.darker();
private final boolean[] down = new boolean[NUM_TOOLS];
private turboRegPointToolbar instance;
private Toolbar previousInstance;
private Graphics g;
private int currentTool = turboRegPointHandler.MOVE_CROSS;
private int x;
private int y;
private int xOffset;
private int yOffset;
/*....................................................................
Canvas methods
....................................................................*/
/*********************************************************************
Draw the toolbar tools.
@param g Graphics environment.
********************************************************************/
public void paint (
final Graphics g
) {
drawButtons(g);
} /* paint */
/*....................................................................
MouseListener methods
....................................................................*/
/*********************************************************************
Listen to <code>mouseClicked</code> events.
@param e Ignored.
********************************************************************/
public void mouseClicked (
final MouseEvent e
) {
} /* end mouseClicked */
/*********************************************************************
Listen to <code>mouseEntered</code> events.
@param e Ignored.
********************************************************************/
public void mouseEntered (
final MouseEvent e
) {
} /* end mouseEntered */
/*********************************************************************
Listen to <code>mouseExited</code> events.
@param e Ignored.
********************************************************************/
public void mouseExited (
final MouseEvent e
) {
} /* end mouseExited */
/*********************************************************************
Listen to <code>mousePressed</code> events. Set the current tool index.
@param e Event.
********************************************************************/
public void mousePressed (
final MouseEvent e
) {
final int x = e.getX();
int newTool = 0;
for (int i = 0; (i < NUM_TOOLS); i++) {
if (((i * SIZE) < x) && (x < (i * SIZE + SIZE))) {
newTool = i;
}
}
setTool(newTool);
} /* mousePressed */
/*********************************************************************
Listen to <code>mouseReleased</code> events.
@param e Ignored.
********************************************************************/
public void mouseReleased (
final MouseEvent e
) {
} /* end mouseReleased */
/*....................................................................
constructors
....................................................................*/
/*********************************************************************
Override the ImageJ toolbar by this <code>turboRegToolbar</code>
object. Store a local copy of the ImageJ's toolbar for later restore.
@see turboRegPointToolbar#restorePreviousToolbar()
********************************************************************/
public turboRegPointToolbar (
final Toolbar previousToolbar
) {
previousInstance = previousToolbar;
instance = this;
final Container container = previousToolbar.getParent();
final Component[] component = container.getComponents();
for (int i = 0; (i < component.length); i++) {
if (component[i] == previousToolbar) {
container.remove(previousToolbar);
container.add(this, i);
break;
}
}
resetButtons();
down[currentTool] = true;
setTool(currentTool);
setForeground(Color.black);
setBackground(gray);
addMouseListener(this);
container.validate();
} /* end turboRegPointToolbar */
/*....................................................................
public methods
....................................................................*/
/*********************************************************************
Return the current tool index.
********************************************************************/
public int getCurrentTool (
) {
return(currentTool);
} /* getCurrentTool */
/*********************************************************************
Restore the ImageJ toolbar.
********************************************************************/
public void restorePreviousToolbar (
) {
final Container container = instance.getParent();
final Component[] component = container.getComponents();
for (int i = 0; (i < component.length); i++) {
if (component[i] == instance) {
container.remove(instance);
container.add(previousInstance, i);
container.validate();
break;
}
}
} /* end restorePreviousToolbar */
/*********************************************************************
Set the current tool and update its appearance on the toolbar.
@param tool Tool index.
********************************************************************/
public void setTool (
final int tool
) {
if (tool == currentTool) {
return;
}
down[tool] = true;
down[currentTool] = false;
final Graphics g = this.getGraphics();
drawButton(g, currentTool);
drawButton(g, tool);
g.dispose();
showMessage(tool);
currentTool = tool;
} /* end setTool */
/*....................................................................
private methods
....................................................................*/
/*------------------------------------------------------------------*/
private void d (
int x,
int y
) {
x += xOffset;
y += yOffset;
g.drawLine(this.x, this.y, x, y);
this.x = x;
this.y = y;
} /* end d */
/*------------------------------------------------------------------*/
private void drawButton (
final Graphics g,
final int tool
) {
fill3DRect(g, tool * SIZE + 1, 1, SIZE, SIZE - 1, !down[tool]);
g.setColor(Color.black);
int x = tool * SIZE + OFFSET;
int y = OFFSET;
if (down[tool]) {
x++;
y++;
}
this.g = g;
switch (tool) {
case turboRegPointHandler.MOVE_CROSS: {
xOffset = x;
yOffset = y;
m(1, 1);
d(1, 10);
m(2, 2);
d(2, 9);
m(3, 3);
d(3, 8);
m(4, 4);
d(4, 7);
m(5, 5);
d(5, 7);
m(6, 6);
d(6, 7);
m(7, 7);
d(7, 7);
m(11, 5);
d(11, 6);
m(10, 7);
d(10, 8);
m(12, 7);
d(12, 8);
m(9, 9);
d(9, 11);
m(13, 9);
d(13, 11);
m(10, 12);
d(10, 15);
m(12, 12);
d(12, 15);
m(11, 9);
d(11, 10);
m(11, 13);
d(11, 15);
m(9, 13);
d(13, 13);
break;
}
case turboRegPointHandler.MAGNIFIER: {
xOffset = x + 2;
yOffset = y + 2;
m(3, 0);
d(3, 0);
d(5, 0);
d(8, 3);
d(8, 5);
d(7, 6);
d(7, 7);
d(6, 7);
d(5, 8);
d(3, 8);
d(0, 5);
d(0, 3);
d(3, 0);
m(8, 8);
d(9, 8);
d(13, 12);
d(13, 13);
d(12, 13);
d(8, 9);
d(8, 8);
break;
}
}
} /* end drawButton */
/*------------------------------------------------------------------*/
private void drawButtons (
final Graphics g
) {
for (int i = 0; (i < NUM_TOOLS); i++) {
drawButton(g, i);
}
} /* end drawButtons */
/*------------------------------------------------------------------*/
private void fill3DRect (
final Graphics g,
final int x,
final int y,
final int width,
final int height,
final boolean raised
) {
if (raised) {
g.setColor(gray);
}
else {
g.setColor(darker);
}
g.fillRect(x + 1, y + 1, width - 2, height - 2);
g.setColor((raised) ? (brighter) : (evenDarker));
g.drawLine(x, y, x, y + height - 1);
g.drawLine(x + 1, y, x + width - 2, y);
g.setColor((raised) ? (evenDarker) : (brighter));
g.drawLine(x + 1, y + height - 1, x + width - 1, y + height - 1);
g.drawLine(x + width - 1, y, x + width - 1, y + height - 2);
} /* end fill3DRect */
/*------------------------------------------------------------------*/
private void m (
final int x,
final int y
) {
this.x = xOffset + x;
this.y = yOffset + y;
} /* end m */
/*------------------------------------------------------------------*/
private void resetButtons (
) {
for (int i = 0; (i < NUM_TOOLS); i++) {
down[i] = false;
}
} /* end resetButtons */
/*------------------------------------------------------------------*/
private void showMessage (
final int tool
) {
switch (tool) {
case turboRegPointHandler.MOVE_CROSS: {
IJ.showStatus("Move crosses");
break;
}
case turboRegPointHandler.MAGNIFIER: {
IJ.showStatus("Magnifying glass");
break;
}
default: {
IJ.showStatus("Undefined operation");
break;
}
}
} /* end showMessage */
} /* end class turboRegPointToolbar */
/*====================================================================
| turboRegProgressBar
\===================================================================*/
/*********************************************************************
This class implements the interactions when dealing with ImageJ's
progress bar.
********************************************************************/
class turboRegProgressBar
{ /* class turboRegProgressBar */
/*....................................................................
private variables
....................................................................*/
/*********************************************************************
Same time constant than in ImageJ version 1.22
********************************************************************/
private static final long TIME_QUANTUM = 50L;
private static volatile long lastTime = System.currentTimeMillis();
private static volatile int completed = 0;
private static volatile int workload = 0;
/*....................................................................
public methods
....................................................................*/
/*********************************************************************
Extend the amount of work to perform by <code>batch</code>.
@param batch Additional amount of work that need be performed.
********************************************************************/
public static synchronized void addWorkload (
final int batch
) {
workload += batch;
} /* end addWorkload */
/*********************************************************************
Erase the progress bar and cancel pending operations.
********************************************************************/
public static synchronized void resetProgressBar (
) {
final long timeStamp = System.currentTimeMillis();
if ((timeStamp - lastTime) < TIME_QUANTUM) {
try {
Thread.sleep(TIME_QUANTUM - timeStamp + lastTime);
} catch (InterruptedException e) {
IJ.log(
"Unexpected interruption exception " + e.getMessage());
}
}
lastTime = timeStamp;
completed = 0;
workload = 0;
IJ.showProgress(1.0);
} /* end resetProgressBar */
/*********************************************************************
Perform <code>stride</code> operations at once.
@param stride Amount of work that is skipped.
********************************************************************/
public static synchronized void skipProgressBar (
final int stride
) {
completed += stride - 1;
stepProgressBar();
} /* end skipProgressBar */
/*********************************************************************
Perform <code>1</code> operation unit.
********************************************************************/
public static synchronized void stepProgressBar (
) {
final long timeStamp = System.currentTimeMillis();
completed = completed + 1;
if ((TIME_QUANTUM <= (timeStamp - lastTime)) | (completed == workload)) {
lastTime = timeStamp;
IJ.showProgress((double)completed / (double)workload);
}
} /* end stepProgressBar */
/*********************************************************************
Acknowledge that <code>batch</code> work has been performed.
@param batch Completed amount of work.
********************************************************************/
public static synchronized void workloadDone (
final int batch
) {
workload -= batch;
completed -= batch;
} /* end workloadDone */
} /* end class turboRegProgressBar */
/*====================================================================
| turboRegTransform
\===================================================================*/
/*********************************************************************
This class implements the algorithmic methods of the plugin. It
refines the landmarks and computes the final images.
********************************************************************/
class turboRegTransform
{ /* class turboRegTransform */
/*....................................................................
private variables
....................................................................*/
/*********************************************************************
Maximal number of registration iterations per level, when
speed is requested at the expense of accuracy. This number must be
corrected so that there are more iterations at the coarse levels
of the pyramid than at the fine levels.
@see turboRegTransform#ITERATION_PROGRESSION
********************************************************************/
private static final int FEW_ITERATIONS = 5;
/*********************************************************************
Initial value of the Marquardt-Levenberg fudge factor.
********************************************************************/
private static final double FIRST_LAMBDA = 1.0;
/*********************************************************************
Update parameter of the Marquardt-Levenberg fudge factor.
********************************************************************/
private static final double LAMBDA_MAGSTEP = 4.0;
/*********************************************************************
Maximal number of registration iterations per level, when
accuracy is requested at the expense of speed. This number must be
corrected so that there are more iterations at the coarse levels
of the pyramid than at the fine levels.
@see turboRegTransform#ITERATION_PROGRESSION
********************************************************************/
private static final int MANY_ITERATIONS = 10;
/*********************************************************************
Minimal update distance of the landmarks, in pixel units, when
accuracy is requested at the expense of speed. This distance does
not depend on the pyramid level.
********************************************************************/
private static final double PIXEL_HIGH_PRECISION = 0.001;
/*********************************************************************
Minimal update distance of the landmarks, in pixel units, when
speed is requested at the expense of accuracy. This distance does
not depend on the pyramid level.
********************************************************************/
private static final double PIXEL_LOW_PRECISION = 0.1;
/*********************************************************************
Multiplicative factor that determines how many more iterations
are allowed for a pyramid level one unit coarser.
********************************************************************/
private static final int ITERATION_PROGRESSION = 2;
private boolean accelerated;
private boolean interactive;
private double c0;
private double c0u;
private double c0v;
private double c0uv;
private double c1;
private double c1u;
private double c1v;
private double c1uv;
private double c2;
private double c2u;
private double c2v;
private double c2uv;
private double c3;
private double c3u;
private double c3v;
private double c3uv;
private double pixelPrecision;
private double s;
private double t;
private double targetJacobian;
private double x;
private double y;
private double[][] sourcePoint;
private double[][] targetPoint;
private final double[] dxWeight = new double[4];
private final double[] dyWeight = new double[4];
private final double[] xWeight = new double[4];
private final double[] yWeight = new double[4];
private final int[] xIndex = new int[4];
private final int[] yIndex = new int[4];
private float[] inImg;
private float[] inMsk;
private float[] outImg;
private float[] outMsk;
private float[] xGradient;
private float[] yGradient;
private int inNx;
private int inNy;
private int iterationCost;
private int iterationPower;
private int maxIterations;
private int outNx;
private int outNy;
private int p;
private int pyramidDepth;
private int q;
private int transformation;
private int twiceInNx;
private int twiceInNy;
private turboRegImage sourceImg;
private turboRegImage targetImg;
private turboRegMask sourceMsk;
private turboRegMask targetMsk;
private turboRegPointHandler sourcePh;
/*....................................................................
constructors
....................................................................*/
/*********************************************************************
Keep a local copy of most everything. Select among the pre-stored
constants.
@param targetImg Target image pyramid.
@param targetMsk Target mask pyramid.
@param sourceImg Source image pyramid.
@param sourceMsk Source mask pyramid.
@param targetPh Target <code>turboRegPointHandler</code> object.
@param sourcePh Source <code>turboRegPointHandler</code> object.
@param transformation Transformation code.
@param accelerated Trade-off between speed and accuracy.
@param interactive Shows or hides the resulting image.
********************************************************************/
public turboRegTransform (
final turboRegImage sourceImg,
final turboRegMask sourceMsk,
final turboRegPointHandler sourcePh,
final turboRegImage targetImg,
final turboRegMask targetMsk,
final turboRegPointHandler targetPh,
final int transformation,
final boolean accelerated,
final boolean interactive
) {
this.sourceImg = sourceImg;
this.sourceMsk = sourceMsk;
this.sourcePh = sourcePh;
this.targetImg = targetImg;
this.targetMsk = targetMsk;
this.transformation = transformation;
this.accelerated = accelerated;
this.interactive = interactive;
sourcePoint = sourcePh.getPoints();
targetPoint = targetPh.getPoints();
if (accelerated) {
pixelPrecision = PIXEL_LOW_PRECISION;
maxIterations = FEW_ITERATIONS;
}
else {
pixelPrecision = PIXEL_HIGH_PRECISION;
maxIterations = MANY_ITERATIONS;
}
} /* end turboRegTransform */
/*....................................................................
public methods
....................................................................*/
/*********************************************************************
Append the current landmarks into a text file. Rigid format.
@param pathAndFilename Path and name of the file where batch results
are being written.
@see turboRegDialog#loadLandmarks()
********************************************************************/
public void appendTransformation (
final String pathAndFilename
) {
outNx = targetImg.getWidth();
outNy = targetImg.getHeight();
inNx = sourceImg.getWidth();
inNy = sourceImg.getHeight();
if (pathAndFilename == null) {
return;
}
try {
final FileWriter fw = new FileWriter(pathAndFilename, true);
fw.write("\n");
switch (transformation) {
case turboRegDialog.TRANSLATION: {
fw.write("TRANSLATION\n");
break;
}
case turboRegDialog.RIGID_BODY: {
fw.write("RIGID_BODY\n");
break;
}
case turboRegDialog.SCALED_ROTATION: {
fw.write("SCALED_ROTATION\n");
break;
}
case turboRegDialog.AFFINE: {
fw.write("AFFINE\n");
break;
}
case turboRegDialog.BILINEAR: {
fw.write("BILINEAR\n");
break;
}
}
fw.write("\n");
fw.write("Source size\n");
fw.write(inNx + "\t" + inNy + "\n");
fw.write("\n");
fw.write("Target size\n");
fw.write(outNx + "\t" + outNy + "\n");
fw.write("\n");
fw.write("Refined source landmarks\n");
if (transformation == turboRegDialog.RIGID_BODY) {
for (int i = 0; (i < transformation); i++) {
fw.write(sourcePoint[i][0] + "\t" + sourcePoint[i][1] + "\n");
}
}
else {
for (int i = 0; (i < (transformation / 2)); i++) {
fw.write(sourcePoint[i][0] + "\t" + sourcePoint[i][1] + "\n");
}
}
fw.write("\n");
fw.write("Target landmarks\n");
if (transformation == turboRegDialog.RIGID_BODY) {
for (int i = 0; (i < transformation); i++) {
fw.write(targetPoint[i][0] + "\t" + targetPoint[i][1] + "\n");
}
}
else {
for (int i = 0; (i < (transformation / 2)); i++) {
fw.write(targetPoint[i][0] + "\t" + targetPoint[i][1] + "\n");
}
}
fw.close();
} catch (IOException e) {
IJ.log(
"IOException exception " + e.getMessage());
} catch (SecurityException e) {
IJ.log(
"Security exception " + e.getMessage());
}
} /* end appendTransformation */
/*********************************************************************
Compute the final image.
********************************************************************/
public void doBatchFinalTransform (
final float[] pixels
) {
if (accelerated) {
inImg = sourceImg.getImage();
}
else {
inImg = sourceImg.getCoefficient();
}
inNx = sourceImg.getWidth();
inNy = sourceImg.getHeight();
twiceInNx = 2 * inNx;
twiceInNy = 2 * inNy;
outImg = pixels;
outNx = targetImg.getWidth();
outNy = targetImg.getHeight();
final double[][] matrix = getTransformationMatrix(targetPoint, sourcePoint);
switch (transformation) {
case turboRegDialog.TRANSLATION: {
translationTransform(matrix);
break;
}
case turboRegDialog.RIGID_BODY:
case turboRegDialog.SCALED_ROTATION:
case turboRegDialog.AFFINE: {
affineTransform(matrix);
break;
}
case turboRegDialog.BILINEAR: {
bilinearTransform(matrix);
break;
}
}
} /* end doBatchFinalTransform */
/*********************************************************************
Compute the final image.
********************************************************************/
public ImagePlus doFinalTransform (
final int width,
final int height
) {
if (accelerated) {
inImg = sourceImg.getImage();
}
else {
inImg = sourceImg.getCoefficient();
}
inMsk = sourceMsk.getMask();
inNx = sourceImg.getWidth();
inNy = sourceImg.getHeight();
twiceInNx = 2 * inNx;
twiceInNy = 2 * inNy;
final ImageStack is = new ImageStack(width, height);
final FloatProcessor dataFp = new FloatProcessor(width, height);
is.addSlice("Data", dataFp);
final FloatProcessor maskFp = new FloatProcessor(width, height);
is.addSlice("Mask", maskFp);
final ImagePlus imp = new ImagePlus("Output", is);
imp.setSlice(1);
outImg = (float[])dataFp.getPixels();
imp.setSlice(2);
final float[] outMsk = (float[])maskFp.getPixels();
outNx = imp.getWidth();
outNy = imp.getHeight();
final double[][] matrix = getTransformationMatrix(targetPoint, sourcePoint);
switch (transformation) {
case turboRegDialog.TRANSLATION: {
translationTransform(matrix, outMsk);
break;
}
case turboRegDialog.RIGID_BODY:
case turboRegDialog.SCALED_ROTATION:
case turboRegDialog.AFFINE: {
affineTransform(matrix, outMsk);
break;
}
case turboRegDialog.BILINEAR: {
bilinearTransform(matrix, outMsk);
break;
}
}
imp.setSlice(1);
imp.getProcessor().resetMinAndMax();
if (interactive) {
imp.show();
imp.updateAndDraw();
}
return(imp);
} /* end doFinalTransform */
/*********************************************************************
Compute the final image.
********************************************************************/
public float[] doFinalTransform (
final turboRegImage sourceImg,
final turboRegPointHandler sourcePh,
final turboRegImage targetImg,
final turboRegPointHandler targetPh,
final int transformation,
final boolean accelerated
) {
this.sourceImg = sourceImg;
this.targetImg = targetImg;
this.sourcePh = sourcePh;
this.transformation = transformation;
this.accelerated = accelerated;
sourcePoint = sourcePh.getPoints();
targetPoint = targetPh.getPoints();
if (accelerated) {
inImg = sourceImg.getImage();
}
else {
inImg = sourceImg.getCoefficient();
}
inNx = sourceImg.getWidth();
inNy = sourceImg.getHeight();
twiceInNx = 2 * inNx;
twiceInNy = 2 * inNy;
outNx = targetImg.getWidth();
outNy = targetImg.getHeight();
outImg = new float[outNx * outNy];
final double[][] matrix = getTransformationMatrix(targetPoint, sourcePoint);
switch (transformation) {
case turboRegDialog.TRANSLATION: {
translationTransform(matrix);
break;
}
case turboRegDialog.RIGID_BODY:
case turboRegDialog.SCALED_ROTATION:
case turboRegDialog.AFFINE: {
affineTransform(matrix);
break;
}
case turboRegDialog.BILINEAR: {
bilinearTransform(matrix);
break;
}
}
return(outImg);
} /* end doFinalTransform */
/*********************************************************************
Refine the landmarks.
********************************************************************/
public void doRegistration (
) {
Stack<?> sourceImgPyramid;
Stack<?> sourceMskPyramid;
Stack<?> targetImgPyramid;
Stack<?> targetMskPyramid;
if (sourceMsk == null) {
sourceImgPyramid = sourceImg.getPyramid();
sourceMskPyramid = null;
targetImgPyramid = (Stack<?>)targetImg.getPyramid().clone();
targetMskPyramid = (Stack<?>)targetMsk.getPyramid().clone();
}
else {
sourceImgPyramid = sourceImg.getPyramid();
sourceMskPyramid = sourceMsk.getPyramid();
targetImgPyramid = targetImg.getPyramid();
targetMskPyramid = targetMsk.getPyramid();
}
pyramidDepth = targetImg.getPyramidDepth();
iterationPower = (int)Math.pow(
(double)ITERATION_PROGRESSION, (double)pyramidDepth);
turboRegProgressBar.addWorkload(
pyramidDepth * maxIterations * iterationPower
/ ITERATION_PROGRESSION
- (iterationPower - 1) / (ITERATION_PROGRESSION - 1));
iterationCost = 1;
scaleBottomDownLandmarks();
while (!targetImgPyramid.isEmpty()) {
iterationPower /= ITERATION_PROGRESSION;
if (transformation == turboRegDialog.BILINEAR) {
inNx = ((Integer)sourceImgPyramid.pop()).intValue();
inNy = ((Integer)sourceImgPyramid.pop()).intValue();
inImg = (float[])sourceImgPyramid.pop();
if (sourceMskPyramid == null) {
inMsk = null;
}
else {
inMsk = (float[])sourceMskPyramid.pop();
}
outNx = ((Integer)targetImgPyramid.pop()).intValue();
outNy = ((Integer)targetImgPyramid.pop()).intValue();
outImg = (float[])targetImgPyramid.pop();
outMsk = (float[])targetMskPyramid.pop();
}
else {
inNx = ((Integer)targetImgPyramid.pop()).intValue();
inNy = ((Integer)targetImgPyramid.pop()).intValue();
inImg = (float[])targetImgPyramid.pop();
inMsk = (float[])targetMskPyramid.pop();
outNx = ((Integer)sourceImgPyramid.pop()).intValue();
outNy = ((Integer)sourceImgPyramid.pop()).intValue();
outImg = (float[])sourceImgPyramid.pop();
xGradient = (float[])sourceImgPyramid.pop();
yGradient = (float[])sourceImgPyramid.pop();
if (sourceMskPyramid == null) {
outMsk = null;
}
else {
outMsk = (float[])sourceMskPyramid.pop();
}
}
twiceInNx = 2 * inNx;
twiceInNy = 2 * inNy;
switch (transformation) {
case turboRegDialog.TRANSLATION: {
targetJacobian = 1.0;
inverseMarquardtLevenbergOptimization(
iterationPower * maxIterations - 1);
break;
}
case turboRegDialog.RIGID_BODY: {
inverseMarquardtLevenbergRigidBodyOptimization(
iterationPower * maxIterations - 1);
break;
}
case turboRegDialog.SCALED_ROTATION: {
targetJacobian = (targetPoint[0][0] - targetPoint[1][0])
* (targetPoint[0][0] - targetPoint[1][0])
+ (targetPoint[0][1] - targetPoint[1][1])
* (targetPoint[0][1] - targetPoint[1][1]);
inverseMarquardtLevenbergOptimization(
iterationPower * maxIterations - 1);
break;
}
case turboRegDialog.AFFINE: {
targetJacobian = (targetPoint[1][0] - targetPoint[2][0])
* targetPoint[0][1]
+ (targetPoint[2][0] - targetPoint[0][0])
* targetPoint[1][1]
+ (targetPoint[0][0] - targetPoint[1][0])
* targetPoint[2][1];
inverseMarquardtLevenbergOptimization(
iterationPower * maxIterations - 1);
break;
}
case turboRegDialog.BILINEAR: {
marquardtLevenbergOptimization(
iterationPower * maxIterations - 1);
break;
}
}
scaleUpLandmarks();
sourcePh.setPoints(sourcePoint);
iterationCost *= ITERATION_PROGRESSION;
}
iterationPower /= ITERATION_PROGRESSION;
if (transformation == turboRegDialog.BILINEAR) {
inNx = sourceImg.getWidth();
inNy = sourceImg.getHeight();
inImg = sourceImg.getCoefficient();
if (sourceMsk == null) {
inMsk = null;
}
else {
inMsk = sourceMsk.getMask();
}
outNx = targetImg.getWidth();
outNy = targetImg.getHeight();
outImg = targetImg.getImage();
outMsk = targetMsk.getMask();
}
else {
inNx = targetImg.getWidth();
inNy = targetImg.getHeight();
inImg = targetImg.getCoefficient();
inMsk = targetMsk.getMask();
outNx = sourceImg.getWidth();
outNy = sourceImg.getHeight();
outImg = sourceImg.getImage();
xGradient = sourceImg.getXGradient();
yGradient = sourceImg.getYGradient();
if (sourceMsk == null) {
outMsk = null;
}
else {
outMsk = sourceMsk.getMask();
}
}
twiceInNx = 2 * inNx;
twiceInNy = 2 * inNy;
if (accelerated) {
turboRegProgressBar.skipProgressBar(
iterationCost * (maxIterations - 1));
}
else {
switch (transformation) {
case turboRegDialog.RIGID_BODY: {
inverseMarquardtLevenbergRigidBodyOptimization(
maxIterations - 1);
break;
}
case turboRegDialog.TRANSLATION:
case turboRegDialog.SCALED_ROTATION:
case turboRegDialog.AFFINE: {
inverseMarquardtLevenbergOptimization(maxIterations - 1);
break;
}
case turboRegDialog.BILINEAR: {
marquardtLevenbergOptimization(maxIterations - 1);
break;
}
}
}
sourcePh.setPoints(sourcePoint);
iterationPower = (int)Math.pow(
(double)ITERATION_PROGRESSION, (double)pyramidDepth);
turboRegProgressBar.workloadDone(
pyramidDepth * maxIterations * iterationPower / ITERATION_PROGRESSION
- (iterationPower - 1) / (ITERATION_PROGRESSION - 1));
} /* end doRegistration */
/*********************************************************************
Save the current landmarks into a text file and return the path
and name of the file. Rigid format.
@see turboRegDialog#loadLandmarks()
********************************************************************/
public String saveTransformation (
String filename
) {
inNx = sourceImg.getWidth();
inNy = sourceImg.getHeight();
outNx = targetImg.getWidth();
outNy = targetImg.getHeight();
String path = "";
if (filename == null) {
final Frame f = new Frame();
final FileDialog fd = new FileDialog(f, "Save landmarks",
FileDialog.SAVE);
filename = "landmarks.txt";
fd.setFile(filename);
fd.setVisible(true);
path = fd.getDirectory();
filename = fd.getFile();
if ((path == null) || (filename == null)) {
return("");
}
}
try {
final FileWriter fw = new FileWriter(path + filename);
fw.write("Transformation\n");
switch (transformation) {
case turboRegDialog.TRANSLATION: {
fw.write("TRANSLATION\n");
break;
}
case turboRegDialog.RIGID_BODY: {
fw.write("RIGID_BODY\n");
break;
}
case turboRegDialog.SCALED_ROTATION: {
fw.write("SCALED_ROTATION\n");
break;
}
case turboRegDialog.AFFINE: {
fw.write("AFFINE\n");
break;
}
case turboRegDialog.BILINEAR: {
fw.write("BILINEAR\n");
break;
}
}
fw.write("\n");
fw.write("Source size\n");
fw.write(inNx + "\t" + inNy + "\n");
fw.write("\n");
fw.write("Target size\n");
fw.write(outNx + "\t" + outNy + "\n");
fw.write("\n");
fw.write("Refined source landmarks\n");
if (transformation == turboRegDialog.RIGID_BODY) {
for (int i = 0; (i < transformation); i++) {
fw.write(sourcePoint[i][0] + "\t" + sourcePoint[i][1] + "\n");
}
}
else {
for (int i = 0; (i < (transformation / 2)); i++) {
fw.write(sourcePoint[i][0] + "\t" + sourcePoint[i][1] + "\n");
}
}
fw.write("\n");
fw.write("Target landmarks\n");
if (transformation == turboRegDialog.RIGID_BODY) {
for (int i = 0; (i < transformation); i++) {
fw.write(targetPoint[i][0] + "\t" + targetPoint[i][1] + "\n");
}
}
else {
for (int i = 0; (i < (transformation / 2)); i++) {
fw.write(targetPoint[i][0] + "\t" + targetPoint[i][1] + "\n");
}
}
fw.close();
} catch (IOException e) {
IJ.log(
"IOException exception " + e.getMessage());
} catch (SecurityException e) {
IJ.log(
"Security exception " + e.getMessage());
}
return(path + filename);
} /* end saveTransformation */
/*....................................................................
private methods
....................................................................*/
/*------------------------------------------------------------------*/
private void affineTransform (
final double[][] matrix
) {
double yx;
double yy;
double x0;
double y0;
int xMsk;
int yMsk;
int k = 0;
turboRegProgressBar.addWorkload(outNy);
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx) && (0 <= yMsk) && (yMsk < inNy)) {
xMsk += yMsk * inNx;
if (accelerated) {
outImg[k++] = inImg[xMsk];
}
else {
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
outImg[k++] = (float)interpolate();
}
}
else {
outImg[k++] = 0.0F;
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
turboRegProgressBar.stepProgressBar();
}
turboRegProgressBar.workloadDone(outNy);
} /* affineTransform */
/*------------------------------------------------------------------*/
private void affineTransform (
final double[][] matrix,
final float[] outMsk
) {
double yx;
double yy;
double x0;
double y0;
int xMsk;
int yMsk;
int k = 0;
turboRegProgressBar.addWorkload(outNy);
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx) && (0 <= yMsk) && (yMsk < inNy)) {
xMsk += yMsk * inNx;
if (accelerated) {
outImg[k] = inImg[xMsk];
}
else {
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
outImg[k] = (float)interpolate();
}
outMsk[k++] = inMsk[xMsk];
}
else {
outImg[k] = 0.0F;
outMsk[k++] = 0.0F;
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
turboRegProgressBar.stepProgressBar();
}
turboRegProgressBar.workloadDone(outNy);
} /* affineTransform */
/*------------------------------------------------------------------*/
private void bilinearTransform (
final double[][] matrix
) {
double yx;
double yy;
double yxy;
double yyy;
double x0;
double y0;
int xMsk;
int yMsk;
int k = 0;
turboRegProgressBar.addWorkload(outNy);
yx = matrix[0][0];
yy = matrix[1][0];
yxy = 0.0;
yyy = 0.0;
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx) && (0 <= yMsk) && (yMsk < inNy)) {
xMsk += yMsk * inNx;
if (accelerated) {
outImg[k++] = inImg[xMsk];
}
else {
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
outImg[k++] = (float)interpolate();
}
}
else {
outImg[k++] = 0.0F;
}
x0 += matrix[0][1] + yxy;
y0 += matrix[1][1] + yyy;
}
yx += matrix[0][2];
yy += matrix[1][2];
yxy += matrix[0][3];
yyy += matrix[1][3];
turboRegProgressBar.stepProgressBar();
}
turboRegProgressBar.workloadDone(outNy);
} /* bilinearTransform */
/*------------------------------------------------------------------*/
private void bilinearTransform (
final double[][] matrix,
final float[] outMsk
) {
double yx;
double yy;
double yxy;
double yyy;
double x0;
double y0;
int xMsk;
int yMsk;
int k = 0;
turboRegProgressBar.addWorkload(outNy);
yx = matrix[0][0];
yy = matrix[1][0];
yxy = 0.0;
yyy = 0.0;
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx) && (0 <= yMsk) && (yMsk < inNy)) {
xMsk += yMsk * inNx;
if (accelerated) {
outImg[k] = inImg[xMsk];
}
else {
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
outImg[k] = (float)interpolate();
}
outMsk[k++] = inMsk[xMsk];
}
else {
outImg[k] = 0.0F;
outMsk[k++] = 0.0F;
}
x0 += matrix[0][1] + yxy;
y0 += matrix[1][1] + yyy;
}
yx += matrix[0][2];
yy += matrix[1][2];
yxy += matrix[0][3];
yyy += matrix[1][3];
turboRegProgressBar.stepProgressBar();
}
turboRegProgressBar.workloadDone(outNy);
} /* bilinearTransform */
/*------------------------------------------------------------------*/
private void computeBilinearGradientConstants (
) {
final double u1 = targetPoint[0][0];
final double u2 = targetPoint[1][0];
final double u3 = targetPoint[2][0];
final double u4 = targetPoint[3][0];
final double v1 = targetPoint[0][1];
final double v2 = targetPoint[1][1];
final double v3 = targetPoint[2][1];
final double v4 = targetPoint[3][1];
final double v12 = v1 - v2;
final double v13 = v1 - v3;
final double v14 = v1 - v4;
final double v23 = v2 - v3;
final double v24 = v2 - v4;
final double v34 = v3 - v4;
final double uv12 = u1 * u2 * v12;
final double uv13 = u1 * u3 * v13;
final double uv14 = u1 * u4 * v14;
final double uv23 = u2 * u3 * v23;
final double uv24 = u2 * u4 * v24;
final double uv34 = u3 * u4 * v34;
final double det = uv12 * v34 - uv13 * v24 + uv14 * v23 + uv23 * v14
- uv24 * v13 + uv34 * v12;
c0 = (-uv34 * v2 + uv24 * v3 - uv23 * v4) / det;
c0u = (u3 * v3 * v24 - u2 * v2 * v34 - u4 * v4 * v23) / det;
c0v = (uv23 - uv24 + uv34) / det;
c0uv = (u4 * v23 - u3 * v24 + u2 * v34) / det;
c1 = (uv34 * v1 - uv14 * v3 + uv13 * v4) / det;
c1u = (-u3 * v3 * v14 + u1 * v1 * v34 + u4 * v4 * v13) / det;
c1v = (-uv13 + uv14 - uv34) / det;
c1uv = (-u4 * v13 + u3 * v14 - u1 * v34) / det;
c2 = (-uv24 * v1 + uv14 * v2 - uv12 * v4) / det;
c2u = (u2 * v2 * v14 - u1 * v1 * v24 - u4 * v4 * v12) / det;
c2v = (uv12 - uv14 + uv24) / det;
c2uv = (u4 * v12 - u2 * v14 + u1 * v24) / det;
c3 = (uv23 * v1 - uv13 * v2 + uv12 * v3) / det;
c3u = (-u2 * v2 * v13 + u1 * v1 * v23 + u3 * v3 * v12) / det;
c3v = (-uv12 + uv13 - uv23) / det;
c3uv = (-u3 * v1 + u2 * v13 + u3 * v2 - u1 * v23) / det;
} /* end computeBilinearGradientConstants */
/*------------------------------------------------------------------*/
private double getAffineMeanSquares (
final double[][] sourcePoint,
final double[][] matrix
) {
final double u1 = sourcePoint[0][0];
final double u2 = sourcePoint[1][0];
final double u3 = sourcePoint[2][0];
final double v1 = sourcePoint[0][1];
final double v2 = sourcePoint[1][1];
final double v3 = sourcePoint[2][1];
final double uv32 = u3 * v2 - u2 * v3;
final double uv21 = u2 * v1 - u1 * v2;
final double uv13 = u1 * v3 - u3 * v1;
final double det = uv32 + uv21 + uv13;
double yx;
double yy;
double x0;
double y0;
double difference;
double meanSquares = 0.0;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
if (outMsk == null) {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if (inMsk[yMsk * inNx + xMsk] != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
else {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if ((outMsk[k] * inMsk[yMsk * inNx + xMsk]) != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
return(meanSquares / ((double)area * Math.abs(det / targetJacobian)));
} /* getAffineMeanSquares */
/*------------------------------------------------------------------*/
private double getAffineMeanSquares (
final double[][] sourcePoint,
final double[][] matrix,
final double[] gradient
) {
final double u1 = sourcePoint[0][0];
final double u2 = sourcePoint[1][0];
final double u3 = sourcePoint[2][0];
final double v1 = sourcePoint[0][1];
final double v2 = sourcePoint[1][1];
final double v3 = sourcePoint[2][1];
double uv32 = u3 * v2 - u2 * v3;
double uv21 = u2 * v1 - u1 * v2;
double uv13 = u1 * v3 - u3 * v1;
final double det = uv32 + uv21 + uv13;
final double u12 = (u1 - u2) /det;
final double u23 = (u2 - u3) /det;
final double u31 = (u3 - u1) /det;
final double v12 = (v1 - v2) /det;
final double v23 = (v2 - v3) /det;
final double v31 = (v3 - v1) /det;
double yx;
double yy;
double x0;
double y0;
double difference;
double meanSquares = 0.0;
double g0;
double g1;
double g2;
double dx0;
double dx1;
double dx2;
double dy0;
double dy1;
double dy2;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
uv32 /= det;
uv21 /= det;
uv13 /= det;
for (int i = 0; (i < transformation); i++) {
gradient[i] = 0.0;
}
if (outMsk == null) {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if (inMsk[yMsk * inNx + xMsk] != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
g0 = u23 * (double)v - v23 * (double)u + uv32;
g1 = u31 * (double)v - v31 * (double)u + uv13;
g2 = u12 * (double)v - v12 * (double)u + uv21;
dx0 = xGradient[k] * g0;
dy0 = yGradient[k] * g0;
dx1 = xGradient[k] * g1;
dy1 = yGradient[k] * g1;
dx2 = xGradient[k] * g2;
dy2 = yGradient[k] * g2;
gradient[0] += difference * dx0;
gradient[1] += difference * dy0;
gradient[2] += difference * dx1;
gradient[3] += difference * dy1;
gradient[4] += difference * dx2;
gradient[5] += difference * dy2;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
else {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if ((outMsk[k] * inMsk[yMsk * inNx + xMsk]) != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
g0 = u23 * (double)v - v23 * (double)u + uv32;
g1 = u31 * (double)v - v31 * (double)u + uv13;
g2 = u12 * (double)v - v12 * (double)u + uv21;
dx0 = xGradient[k] * g0;
dy0 = yGradient[k] * g0;
dx1 = xGradient[k] * g1;
dy1 = yGradient[k] * g1;
dx2 = xGradient[k] * g2;
dy2 = yGradient[k] * g2;
gradient[0] += difference * dx0;
gradient[1] += difference * dy0;
gradient[2] += difference * dx1;
gradient[3] += difference * dy1;
gradient[4] += difference * dx2;
gradient[5] += difference * dy2;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
return(meanSquares / ((double)area * Math.abs(det / targetJacobian)));
} /* getAffineMeanSquares */
/*------------------------------------------------------------------*/
private double getAffineMeanSquares (
final double[][] sourcePoint,
final double[][] matrix,
final double[][] hessian,
final double[] gradient
) {
final double u1 = sourcePoint[0][0];
final double u2 = sourcePoint[1][0];
final double u3 = sourcePoint[2][0];
final double v1 = sourcePoint[0][1];
final double v2 = sourcePoint[1][1];
final double v3 = sourcePoint[2][1];
double uv32 = u3 * v2 - u2 * v3;
double uv21 = u2 * v1 - u1 * v2;
double uv13 = u1 * v3 - u3 * v1;
final double det = uv32 + uv21 + uv13;
final double u12 = (u1 - u2) /det;
final double u23 = (u2 - u3) /det;
final double u31 = (u3 - u1) /det;
final double v12 = (v1 - v2) /det;
final double v23 = (v2 - v3) /det;
final double v31 = (v3 - v1) /det;
double yx;
double yy;
double x0;
double y0;
double difference;
double meanSquares = 0.0;
double g0;
double g1;
double g2;
double dx0;
double dx1;
double dx2;
double dy0;
double dy1;
double dy2;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
uv32 /= det;
uv21 /= det;
uv13 /= det;
for (int i = 0; (i < transformation); i++) {
gradient[i] = 0.0;
for (int j = 0; (j < transformation); j++) {
hessian[i][j] = 0.0;
}
}
if (outMsk == null) {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if (inMsk[yMsk * inNx + xMsk] != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
g0 = u23 * (double)v - v23 * (double)u + uv32;
g1 = u31 * (double)v - v31 * (double)u + uv13;
g2 = u12 * (double)v - v12 * (double)u + uv21;
dx0 = xGradient[k] * g0;
dy0 = yGradient[k] * g0;
dx1 = xGradient[k] * g1;
dy1 = yGradient[k] * g1;
dx2 = xGradient[k] * g2;
dy2 = yGradient[k] * g2;
gradient[0] += difference * dx0;
gradient[1] += difference * dy0;
gradient[2] += difference * dx1;
gradient[3] += difference * dy1;
gradient[4] += difference * dx2;
gradient[5] += difference * dy2;
hessian[0][0] += dx0 * dx0;
hessian[0][1] += dx0 * dy0;
hessian[0][2] += dx0 * dx1;
hessian[0][3] += dx0 * dy1;
hessian[0][4] += dx0 * dx2;
hessian[0][5] += dx0 * dy2;
hessian[1][1] += dy0 * dy0;
hessian[1][2] += dy0 * dx1;
hessian[1][3] += dy0 * dy1;
hessian[1][4] += dy0 * dx2;
hessian[1][5] += dy0 * dy2;
hessian[2][2] += dx1 * dx1;
hessian[2][3] += dx1 * dy1;
hessian[2][4] += dx1 * dx2;
hessian[2][5] += dx1 * dy2;
hessian[3][3] += dy1 * dy1;
hessian[3][4] += dy1 * dx2;
hessian[3][5] += dy1 * dy2;
hessian[4][4] += dx2 * dx2;
hessian[4][5] += dx2 * dy2;
hessian[5][5] += dy2 * dy2;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
else {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if ((outMsk[k] * inMsk[yMsk * inNx + xMsk]) != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
g0 = u23 * (double)v - v23 * (double)u + uv32;
g1 = u31 * (double)v - v31 * (double)u + uv13;
g2 = u12 * (double)v - v12 * (double)u + uv21;
dx0 = xGradient[k] * g0;
dy0 = yGradient[k] * g0;
dx1 = xGradient[k] * g1;
dy1 = yGradient[k] * g1;
dx2 = xGradient[k] * g2;
dy2 = yGradient[k] * g2;
gradient[0] += difference * dx0;
gradient[1] += difference * dy0;
gradient[2] += difference * dx1;
gradient[3] += difference * dy1;
gradient[4] += difference * dx2;
gradient[5] += difference * dy2;
hessian[0][0] += dx0 * dx0;
hessian[0][1] += dx0 * dy0;
hessian[0][2] += dx0 * dx1;
hessian[0][3] += dx0 * dy1;
hessian[0][4] += dx0 * dx2;
hessian[0][5] += dx0 * dy2;
hessian[1][1] += dy0 * dy0;
hessian[1][2] += dy0 * dx1;
hessian[1][3] += dy0 * dy1;
hessian[1][4] += dy0 * dx2;
hessian[1][5] += dy0 * dy2;
hessian[2][2] += dx1 * dx1;
hessian[2][3] += dx1 * dy1;
hessian[2][4] += dx1 * dx2;
hessian[2][5] += dx1 * dy2;
hessian[3][3] += dy1 * dy1;
hessian[3][4] += dy1 * dx2;
hessian[3][5] += dy1 * dy2;
hessian[4][4] += dx2 * dx2;
hessian[4][5] += dx2 * dy2;
hessian[5][5] += dy2 * dy2;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
for (int i = 1; (i < transformation); i++) {
for (int j = 0; (j < i); j++) {
hessian[i][j] = hessian[j][i];
}
}
return(meanSquares / ((double)area * Math.abs(det / targetJacobian)));
} /* getAffineMeanSquares */
/*------------------------------------------------------------------*/
private double getBilinearMeanSquares (
final double[][] matrix
) {
double yx;
double yy;
double yxy;
double yyy;
double x0;
double y0;
double difference;
double meanSquares = 0.0;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
if (inMsk == null) {
yx = matrix[0][0];
yy = matrix[1][0];
yxy = 0.0;
yyy = 0.0;
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
if (outMsk[k] != 0.0F) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
xIndexes();
yIndexes();
area++;
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = interpolate() - (double)outImg[k];
meanSquares += difference * difference;
}
}
x0 += matrix[0][1] + yxy;
y0 += matrix[1][1] + yyy;
}
yx += matrix[0][2];
yy += matrix[1][2];
yxy += matrix[0][3];
yyy += matrix[1][3];
}
}
else {
yx = matrix[0][0];
yy = matrix[1][0];
yxy = 0.0;
yyy = 0.0;
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
xMsk += yMsk * inNx;
if ((outMsk[k] * inMsk[xMsk]) != 0.0F) {
xIndexes();
yIndexes();
area++;
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = interpolate() - (double)outImg[k];
meanSquares += difference * difference;
}
}
x0 += matrix[0][1] + yxy;
y0 += matrix[1][1] + yyy;
}
yx += matrix[0][2];
yy += matrix[1][2];
yxy += matrix[0][3];
yyy += matrix[1][3];
}
}
return(meanSquares / (double)area);
} /* getBilinearMeanSquares */
/*------------------------------------------------------------------*/
private double getBilinearMeanSquares (
final double[][] matrix,
final double[][] hessian,
final double[] gradient
) {
double yx;
double yy;
double yxy;
double yyy;
double x0;
double y0;
double uv;
double xGradient;
double yGradient;
double difference;
double meanSquares = 0.0;
double g0;
double g1;
double g2;
double g3;
double dx0;
double dx1;
double dx2;
double dx3;
double dy0;
double dy1;
double dy2;
double dy3;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
computeBilinearGradientConstants();
for (int i = 0; (i < transformation); i++) {
gradient[i] = 0.0;
for (int j = 0; (j < transformation); j++) {
hessian[i][j] = 0.0;
}
}
if (inMsk == null) {
yx = matrix[0][0];
yy = matrix[1][0];
yxy = 0.0;
yyy = 0.0;
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
if (outMsk[k] != 0.0F) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xDxWeights();
yDyWeights();
difference = interpolate() - (double)outImg[k];
meanSquares += difference * difference;
xGradient = interpolateDx();
yGradient = interpolateDy();
uv = (double)u * (double)v;
g0 = c0uv * uv + c0u * (double)u + c0v * (double)v + c0;
g1 = c1uv * uv + c1u * (double)u + c1v * (double)v + c1;
g2 = c2uv * uv + c2u * (double)u + c2v * (double)v + c2;
g3 = c3uv * uv + c3u * (double)u + c3v * (double)v + c3;
dx0 = xGradient * g0;
dy0 = yGradient * g0;
dx1 = xGradient * g1;
dy1 = yGradient * g1;
dx2 = xGradient * g2;
dy2 = yGradient * g2;
dx3 = xGradient * g3;
dy3 = yGradient * g3;
gradient[0] += difference * dx0;
gradient[1] += difference * dy0;
gradient[2] += difference * dx1;
gradient[3] += difference * dy1;
gradient[4] += difference * dx2;
gradient[5] += difference * dy2;
gradient[6] += difference * dx3;
gradient[7] += difference * dy3;
hessian[0][0] += dx0 * dx0;
hessian[0][1] += dx0 * dy0;
hessian[0][2] += dx0 * dx1;
hessian[0][3] += dx0 * dy1;
hessian[0][4] += dx0 * dx2;
hessian[0][5] += dx0 * dy2;
hessian[0][6] += dx0 * dx3;
hessian[0][7] += dx0 * dy3;
hessian[1][1] += dy0 * dy0;
hessian[1][2] += dy0 * dx1;
hessian[1][3] += dy0 * dy1;
hessian[1][4] += dy0 * dx2;
hessian[1][5] += dy0 * dy2;
hessian[1][6] += dy0 * dx3;
hessian[1][7] += dy0 * dy3;
hessian[2][2] += dx1 * dx1;
hessian[2][3] += dx1 * dy1;
hessian[2][4] += dx1 * dx2;
hessian[2][5] += dx1 * dy2;
hessian[2][6] += dx1 * dx3;
hessian[2][7] += dx1 * dy3;
hessian[3][3] += dy1 * dy1;
hessian[3][4] += dy1 * dx2;
hessian[3][5] += dy1 * dy2;
hessian[3][6] += dy1 * dx3;
hessian[3][7] += dy1 * dy3;
hessian[4][4] += dx2 * dx2;
hessian[4][5] += dx2 * dy2;
hessian[4][6] += dx2 * dx3;
hessian[4][7] += dx2 * dy3;
hessian[5][5] += dy2 * dy2;
hessian[5][6] += dy2 * dx3;
hessian[5][7] += dy2 * dy3;
hessian[6][6] += dx3 * dx3;
hessian[6][7] += dx3 * dy3;
hessian[7][7] += dy3 * dy3;
}
}
x0 += matrix[0][1] + yxy;
y0 += matrix[1][1] + yyy;
}
yx += matrix[0][2];
yy += matrix[1][2];
yxy += matrix[0][3];
yyy += matrix[1][3];
}
}
else {
yx = matrix[0][0];
yy = matrix[1][0];
yxy = 0.0;
yyy = 0.0;
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
xMsk += yMsk * inNx;
if ((outMsk[k] * inMsk[xMsk]) != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xDxWeights();
yDyWeights();
difference = interpolate() - (double)outImg[k];
meanSquares += difference * difference;
xGradient = interpolateDx();
yGradient = interpolateDy();
uv = (double)u * (double)v;
g0 = c0uv * uv + c0u * (double)u + c0v * (double)v + c0;
g1 = c1uv * uv + c1u * (double)u + c1v * (double)v + c1;
g2 = c2uv * uv + c2u * (double)u + c2v * (double)v + c2;
g3 = c3uv * uv + c3u * (double)u + c3v * (double)v + c3;
dx0 = xGradient * g0;
dy0 = yGradient * g0;
dx1 = xGradient * g1;
dy1 = yGradient * g1;
dx2 = xGradient * g2;
dy2 = yGradient * g2;
dx3 = xGradient * g3;
dy3 = yGradient * g3;
gradient[0] += difference * dx0;
gradient[1] += difference * dy0;
gradient[2] += difference * dx1;
gradient[3] += difference * dy1;
gradient[4] += difference * dx2;
gradient[5] += difference * dy2;
gradient[6] += difference * dx3;
gradient[7] += difference * dy3;
hessian[0][0] += dx0 * dx0;
hessian[0][1] += dx0 * dy0;
hessian[0][2] += dx0 * dx1;
hessian[0][3] += dx0 * dy1;
hessian[0][4] += dx0 * dx2;
hessian[0][5] += dx0 * dy2;
hessian[0][6] += dx0 * dx3;
hessian[0][7] += dx0 * dy3;
hessian[1][1] += dy0 * dy0;
hessian[1][2] += dy0 * dx1;
hessian[1][3] += dy0 * dy1;
hessian[1][4] += dy0 * dx2;
hessian[1][5] += dy0 * dy2;
hessian[1][6] += dy0 * dx3;
hessian[1][7] += dy0 * dy3;
hessian[2][2] += dx1 * dx1;
hessian[2][3] += dx1 * dy1;
hessian[2][4] += dx1 * dx2;
hessian[2][5] += dx1 * dy2;
hessian[2][6] += dx1 * dx3;
hessian[2][7] += dx1 * dy3;
hessian[3][3] += dy1 * dy1;
hessian[3][4] += dy1 * dx2;
hessian[3][5] += dy1 * dy2;
hessian[3][6] += dy1 * dx3;
hessian[3][7] += dy1 * dy3;
hessian[4][4] += dx2 * dx2;
hessian[4][5] += dx2 * dy2;
hessian[4][6] += dx2 * dx3;
hessian[4][7] += dx2 * dy3;
hessian[5][5] += dy2 * dy2;
hessian[5][6] += dy2 * dx3;
hessian[5][7] += dy2 * dy3;
hessian[6][6] += dx3 * dx3;
hessian[6][7] += dx3 * dy3;
hessian[7][7] += dy3 * dy3;
}
}
x0 += matrix[0][1] + yxy;
y0 += matrix[1][1] + yyy;
}
yx += matrix[0][2];
yy += matrix[1][2];
yxy += matrix[0][3];
yyy += matrix[1][3];
}
}
for (int i = 1; (i < transformation); i++) {
for (int j = 0; (j < i); j++) {
hessian[i][j] = hessian[j][i];
}
}
return(meanSquares / (double)area);
} /* getBilinearMeanSquares */
/*------------------------------------------------------------------*/
private double getRigidBodyMeanSquares (
final double[][] matrix
) {
double yx;
double yy;
double x0;
double y0;
double difference;
double meanSquares = 0.0;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
if (outMsk == null) {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if (inMsk[yMsk * inNx + xMsk] != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
else {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if ((outMsk[k] * inMsk[yMsk * inNx + xMsk]) != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
return(meanSquares / (double)area);
} /* getRigidBodyMeanSquares */
/*------------------------------------------------------------------*/
private double getRigidBodyMeanSquares (
final double[][] matrix,
final double[] gradient
) {
double yx;
double yy;
double x0;
double y0;
double difference;
double meanSquares = 0.0;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
for (int i = 0; (i < transformation); i++) {
gradient[i] = 0.0;
}
if (outMsk == null) {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if (inMsk[yMsk * inNx + xMsk] != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
gradient[0] += difference * (yGradient[k] * (double)u
- xGradient[k] * (double)v);
gradient[1] += difference * xGradient[k];
gradient[2] += difference * yGradient[k];
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
else {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if ((outMsk[k] * inMsk[yMsk * inNx + xMsk]) != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
gradient[0] += difference * (yGradient[k] * (double)u
- xGradient[k] * (double)v);
gradient[1] += difference * xGradient[k];
gradient[2] += difference * yGradient[k];
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
return(meanSquares / (double)area);
} /* getRigidBodyMeanSquares */
/*------------------------------------------------------------------*/
private double getRigidBodyMeanSquares (
final double[][] matrix,
final double[][] hessian,
final double[] gradient
) {
double yx;
double yy;
double x0;
double y0;
double dTheta;
double difference;
double meanSquares = 0.0;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
for (int i = 0; (i < transformation); i++) {
gradient[i] = 0.0;
for (int j = 0; (j < transformation); j++) {
hessian[i][j] = 0.0;
}
}
if (outMsk == null) {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if (inMsk[yMsk * inNx + xMsk] != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
dTheta = yGradient[k] * (double)u
- xGradient[k] * (double)v;
gradient[0] += difference * dTheta;
gradient[1] += difference * xGradient[k];
gradient[2] += difference * yGradient[k];
hessian[0][0] += dTheta * dTheta;
hessian[0][1] += dTheta * xGradient[k];
hessian[0][2] += dTheta * yGradient[k];
hessian[1][1] += xGradient[k] * xGradient[k];
hessian[1][2] += xGradient[k] * yGradient[k];
hessian[2][2] += yGradient[k] * yGradient[k];
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
else {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if ((outMsk[k] * inMsk[yMsk * inNx + xMsk]) != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
dTheta = yGradient[k] * (double)u
- xGradient[k] * (double)v;
gradient[0] += difference * dTheta;
gradient[1] += difference * xGradient[k];
gradient[2] += difference * yGradient[k];
hessian[0][0] += dTheta * dTheta;
hessian[0][1] += dTheta * xGradient[k];
hessian[0][2] += dTheta * yGradient[k];
hessian[1][1] += xGradient[k] * xGradient[k];
hessian[1][2] += xGradient[k] * yGradient[k];
hessian[2][2] += yGradient[k] * yGradient[k];
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
for (int i = 1; (i < transformation); i++) {
for (int j = 0; (j < i); j++) {
hessian[i][j] = hessian[j][i];
}
}
return(meanSquares / (double)area);
} /* getRigidBodyMeanSquares */
/*------------------------------------------------------------------*/
private double getScaledRotationMeanSquares (
final double[][] sourcePoint,
final double[][] matrix
) {
final double u1 = sourcePoint[0][0];
final double u2 = sourcePoint[1][0];
final double v1 = sourcePoint[0][1];
final double v2 = sourcePoint[1][1];
final double u12 = u1 - u2;
final double v12 = v1 - v2;
final double uv2 = u12 * u12 + v12 * v12;
double yx;
double yy;
double x0;
double y0;
double difference;
double meanSquares = 0.0;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
if (outMsk == null) {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if (inMsk[yMsk * inNx + xMsk] != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
else {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if ((outMsk[k] * inMsk[yMsk * inNx + xMsk]) != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
return(meanSquares / ((double)area * uv2 / targetJacobian));
} /* getScaledRotationMeanSquares */
/*------------------------------------------------------------------*/
private double getScaledRotationMeanSquares (
final double[][] sourcePoint,
final double[][] matrix,
final double[] gradient
) {
final double u1 = sourcePoint[0][0];
final double u2 = sourcePoint[1][0];
final double v1 = sourcePoint[0][1];
final double v2 = sourcePoint[1][1];
final double u12 = u1 - u2;
final double v12 = v1 - v2;
final double uv2 = u12 * u12 + v12 * v12;
final double c = 0.5 * (u2 * v1 - u1 * v2) / uv2;
final double c1 = u12 / uv2;
final double c2 = v12 / uv2;
final double c3 = (uv2 - u12 * v12) / uv2;
final double c4 = (uv2 + u12 * v12) / uv2;
final double c5 = c + u1 * c1 + u2 * c2;
final double c6 = c * (u12 * u12 - v12 * v12) / uv2;
final double c7 = c1 * c4;
final double c8 = c1 - c2 - c1 * c2 * v12;
final double c9 = c1 + c2 - c1 * c2 * u12;
final double c0 = c2 * c3;
final double dgxx0 = c1 * u2 + c2 * v2;
final double dgyx0 = 2.0 * c;
final double dgxx1 = c5 + c6;
final double dgyy1 = c5 - c6;
double yx;
double yy;
double x0;
double y0;
double difference;
double meanSquares = 0.0;
double gxx0;
double gxx1;
double gxy0;
double gxy1;
double gyx0;
double gyx1;
double gyy0;
double gyy1;
double dx0;
double dx1;
double dy0;
double dy1;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
for (int i = 0; (i < transformation); i++) {
gradient[i] = 0.0;
}
if (outMsk == null) {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if (inMsk[yMsk * inNx + xMsk] != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
gxx0 = (double)u * c1 + (double)v * c2 - dgxx0;
gyx0 = (double)v * c1 - (double)u * c2 + dgyx0;
gxy0 = -gyx0;
gyy0 = gxx0;
gxx1 = (double)v * c8 - (double)u * c7 + dgxx1;
gyx1 = -c3 * gyx0;
gxy1 = c4 * gyx0;
gyy1 = dgyy1 - (double)u * c9 - (double)v * c0;
dx0 = xGradient[k] * gxx0 + yGradient[k] * gyx0;
dy0 = xGradient[k] * gxy0 + yGradient[k] * gyy0;
dx1 = xGradient[k] * gxx1 + yGradient[k] * gyx1;
dy1 = xGradient[k] * gxy1 + yGradient[k] * gyy1;
gradient[0] += difference * dx0;
gradient[1] += difference * dy0;
gradient[2] += difference * dx1;
gradient[3] += difference * dy1;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
else {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if ((outMsk[k] * inMsk[yMsk * inNx + xMsk]) != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
gxx0 = (double)u * c1 + (double)v * c2 - dgxx0;
gyx0 = (double)v * c1 - (double)u * c2 + dgyx0;
gxy0 = -gyx0;
gyy0 = gxx0;
gxx1 = (double)v * c8 - (double)u * c7 + dgxx1;
gyx1 = -c3 * gyx0;
gxy1 = c4 * gyx0;
gyy1 = dgyy1 - (double)u * c9 - (double)v * c0;
dx0 = xGradient[k] * gxx0 + yGradient[k] * gyx0;
dy0 = xGradient[k] * gxy0 + yGradient[k] * gyy0;
dx1 = xGradient[k] * gxx1 + yGradient[k] * gyx1;
dy1 = xGradient[k] * gxy1 + yGradient[k] * gyy1;
gradient[0] += difference * dx0;
gradient[1] += difference * dy0;
gradient[2] += difference * dx1;
gradient[3] += difference * dy1;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
return(meanSquares / ((double)area * uv2 / targetJacobian));
} /* getScaledRotationMeanSquares */
/*------------------------------------------------------------------*/
private double getScaledRotationMeanSquares (
final double[][] sourcePoint,
final double[][] matrix,
final double[][] hessian,
final double[] gradient
) {
final double u1 = sourcePoint[0][0];
final double u2 = sourcePoint[1][0];
final double v1 = sourcePoint[0][1];
final double v2 = sourcePoint[1][1];
final double u12 = u1 - u2;
final double v12 = v1 - v2;
final double uv2 = u12 * u12 + v12 * v12;
final double c = 0.5 * (u2 * v1 - u1 * v2) / uv2;
final double c1 = u12 / uv2;
final double c2 = v12 / uv2;
final double c3 = (uv2 - u12 * v12) / uv2;
final double c4 = (uv2 + u12 * v12) / uv2;
final double c5 = c + u1 * c1 + u2 * c2;
final double c6 = c * (u12 * u12 - v12 * v12) / uv2;
final double c7 = c1 * c4;
final double c8 = c1 - c2 - c1 * c2 * v12;
final double c9 = c1 + c2 - c1 * c2 * u12;
final double c0 = c2 * c3;
final double dgxx0 = c1 * u2 + c2 * v2;
final double dgyx0 = 2.0 * c;
final double dgxx1 = c5 + c6;
final double dgyy1 = c5 - c6;
double yx;
double yy;
double x0;
double y0;
double difference;
double meanSquares = 0.0;
double gxx0;
double gxx1;
double gxy0;
double gxy1;
double gyx0;
double gyx1;
double gyy0;
double gyy1;
double dx0;
double dx1;
double dy0;
double dy1;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
for (int i = 0; (i < transformation); i++) {
gradient[i] = 0.0;
for (int j = 0; (j < transformation); j++) {
hessian[i][j] = 0.0;
}
}
if (outMsk == null) {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if (inMsk[yMsk * inNx + xMsk] != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
gxx0 = (double)u * c1 + (double)v * c2 - dgxx0;
gyx0 = (double)v * c1 - (double)u * c2 + dgyx0;
gxy0 = -gyx0;
gyy0 = gxx0;
gxx1 = (double)v * c8 - (double)u * c7 + dgxx1;
gyx1 = -c3 * gyx0;
gxy1 = c4 * gyx0;
gyy1 = dgyy1 - (double)u * c9 - (double)v * c0;
dx0 = xGradient[k] * gxx0 + yGradient[k] * gyx0;
dy0 = xGradient[k] * gxy0 + yGradient[k] * gyy0;
dx1 = xGradient[k] * gxx1 + yGradient[k] * gyx1;
dy1 = xGradient[k] * gxy1 + yGradient[k] * gyy1;
gradient[0] += difference * dx0;
gradient[1] += difference * dy0;
gradient[2] += difference * dx1;
gradient[3] += difference * dy1;
hessian[0][0] += dx0 * dx0;
hessian[0][1] += dx0 * dy0;
hessian[0][2] += dx0 * dx1;
hessian[0][3] += dx0 * dy1;
hessian[1][1] += dy0 * dy0;
hessian[1][2] += dy0 * dx1;
hessian[1][3] += dy0 * dy1;
hessian[2][2] += dx1 * dx1;
hessian[2][3] += dx1 * dy1;
hessian[3][3] += dy1 * dy1;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
else {
yx = matrix[0][0];
yy = matrix[1][0];
for (int v = 0; (v < outNy); v++) {
x0 = yx;
y0 = yy;
for (int u = 0; (u < outNx); u++, k++) {
x = x0;
y = y0;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)
&& (0 <= yMsk) && (yMsk < inNy)) {
if ((outMsk[k] * inMsk[yMsk * inNx + xMsk]) != 0.0F) {
area++;
xIndexes();
yIndexes();
x -= (0.0 <= x) ? ((int)x) : ((int)x - 1);
y -= (0.0 <= y) ? ((int)y) : ((int)y - 1);
xWeights();
yWeights();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
gxx0 = (double)u * c1 + (double)v * c2 - dgxx0;
gyx0 = (double)v * c1 - (double)u * c2 + dgyx0;
gxy0 = -gyx0;
gyy0 = gxx0;
gxx1 = (double)v * c8 - (double)u * c7 + dgxx1;
gyx1 = -c3 * gyx0;
gxy1 = c4 * gyx0;
gyy1 = dgyy1 - (double)u * c9 - (double)v * c0;
dx0 = xGradient[k] * gxx0 + yGradient[k] * gyx0;
dy0 = xGradient[k] * gxy0 + yGradient[k] * gyy0;
dx1 = xGradient[k] * gxx1 + yGradient[k] * gyx1;
dy1 = xGradient[k] * gxy1 + yGradient[k] * gyy1;
gradient[0] += difference * dx0;
gradient[1] += difference * dy0;
gradient[2] += difference * dx1;
gradient[3] += difference * dy1;
hessian[0][0] += dx0 * dx0;
hessian[0][1] += dx0 * dy0;
hessian[0][2] += dx0 * dx1;
hessian[0][3] += dx0 * dy1;
hessian[1][1] += dy0 * dy0;
hessian[1][2] += dy0 * dx1;
hessian[1][3] += dy0 * dy1;
hessian[2][2] += dx1 * dx1;
hessian[2][3] += dx1 * dy1;
hessian[3][3] += dy1 * dy1;
}
}
x0 += matrix[0][1];
y0 += matrix[1][1];
}
yx += matrix[0][2];
yy += matrix[1][2];
}
}
for (int i = 1; (i < transformation); i++) {
for (int j = 0; (j < i); j++) {
hessian[i][j] = hessian[j][i];
}
}
return(meanSquares / ((double)area * uv2 / targetJacobian));
} /* getScaledRotationMeanSquares */
/*------------------------------------------------------------------*/
private double[][] getTransformationMatrix (
final double[][] fromCoord,
final double[][] toCoord
) {
double[][] matrix = null;
double[][] a = null;
double[] v = null;
switch (transformation) {
case turboRegDialog.TRANSLATION: {
matrix = new double[2][1];
matrix[0][0] = toCoord[0][0] - fromCoord[0][0];
matrix[1][0] = toCoord[0][1] - fromCoord[0][1];
break;
}
case turboRegDialog.RIGID_BODY: {
final double angle = Math.atan2(fromCoord[2][0] - fromCoord[1][0],
fromCoord[2][1] - fromCoord[1][1])
- Math.atan2(toCoord[2][0] - toCoord[1][0],
toCoord[2][1] - toCoord[1][1]);
final double c = Math.cos(angle);
final double s = Math.sin(angle);
matrix = new double[2][3];
matrix[0][0] = toCoord[0][0]
- c * fromCoord[0][0] + s * fromCoord[0][1];
matrix[0][1] = c;
matrix[0][2] = -s;
matrix[1][0] = toCoord[0][1]
- s * fromCoord[0][0] - c * fromCoord[0][1];
matrix[1][1] = s;
matrix[1][2] = c;
break;
}
case turboRegDialog.SCALED_ROTATION: {
matrix = new double[2][3];
a = new double[3][3];
v = new double[3];
a[0][0] = 1.0;
a[0][1] = fromCoord[0][0];
a[0][2] = fromCoord[0][1];
a[1][0] = 1.0;
a[1][1] = fromCoord[1][0];
a[1][2] = fromCoord[1][1];
a[2][0] = 1.0;
a[2][1] = fromCoord[0][1] - fromCoord[1][1] + fromCoord[1][0];
a[2][2] = fromCoord[1][0] + fromCoord[1][1] - fromCoord[0][0];
invertGauss(a);
v[0] = toCoord[0][0];
v[1] = toCoord[1][0];
v[2] = toCoord[0][1] - toCoord[1][1] + toCoord[1][0];
for (int i = 0; (i < 3); i++) {
matrix[0][i] = 0.0;
for (int j = 0; (j < 3); j++) {
matrix[0][i] += a[i][j] * v[j];
}
}
v[0] = toCoord[0][1];
v[1] = toCoord[1][1];
v[2] = toCoord[1][0] + toCoord[1][1] - toCoord[0][0];
for (int i = 0; (i < 3); i++) {
matrix[1][i] = 0.0;
for (int j = 0; (j < 3); j++) {
matrix[1][i] += a[i][j] * v[j];
}
}
break;
}
case turboRegDialog.AFFINE: {
matrix = new double[2][3];
a = new double[3][3];
v = new double[3];
a[0][0] = 1.0;
a[0][1] = fromCoord[0][0];
a[0][2] = fromCoord[0][1];
a[1][0] = 1.0;
a[1][1] = fromCoord[1][0];
a[1][2] = fromCoord[1][1];
a[2][0] = 1.0;
a[2][1] = fromCoord[2][0];
a[2][2] = fromCoord[2][1];
invertGauss(a);
v[0] = toCoord[0][0];
v[1] = toCoord[1][0];
v[2] = toCoord[2][0];
for (int i = 0; (i < 3); i++) {
matrix[0][i] = 0.0;
for (int j = 0; (j < 3); j++) {
matrix[0][i] += a[i][j] * v[j];
}
}
v[0] = toCoord[0][1];
v[1] = toCoord[1][1];
v[2] = toCoord[2][1];
for (int i = 0; (i < 3); i++) {
matrix[1][i] = 0.0;
for (int j = 0; (j < 3); j++) {
matrix[1][i] += a[i][j] * v[j];
}
}
break;
}
case turboRegDialog.BILINEAR: {
matrix = new double[2][4];
a = new double[4][4];
v = new double[4];
a[0][0] = 1.0;
a[0][1] = fromCoord[0][0];
a[0][2] = fromCoord[0][1];
a[0][3] = fromCoord[0][0] * fromCoord[0][1];
a[1][0] = 1.0;
a[1][1] = fromCoord[1][0];
a[1][2] = fromCoord[1][1];
a[1][3] = fromCoord[1][0] * fromCoord[1][1];
a[2][0] = 1.0;
a[2][1] = fromCoord[2][0];
a[2][2] = fromCoord[2][1];
a[2][3] = fromCoord[2][0] * fromCoord[2][1];
a[3][0] = 1.0;
a[3][1] = fromCoord[3][0];
a[3][2] = fromCoord[3][1];
a[3][3] = fromCoord[3][0] * fromCoord[3][1];
invertGauss(a);
v[0] = toCoord[0][0];
v[1] = toCoord[1][0];
v[2] = toCoord[2][0];
v[3] = toCoord[3][0];
for (int i = 0; (i < 4); i++) {
matrix[0][i] = 0.0;
for (int j = 0; (j < 4); j++) {
matrix[0][i] += a[i][j] * v[j];
}
}
v[0] = toCoord[0][1];
v[1] = toCoord[1][1];
v[2] = toCoord[2][1];
v[3] = toCoord[3][1];
for (int i = 0; (i < 4); i++) {
matrix[1][i] = 0.0;
for (int j = 0; (j < 4); j++) {
matrix[1][i] += a[i][j] * v[j];
}
}
break;
}
}
return(matrix);
} /* end getTransformationMatrix */
/*------------------------------------------------------------------*/
private double getTranslationMeanSquares (
final double[][] matrix
) {
double dx = matrix[0][0];
double dy = matrix[1][0];
final double dx0 = dx;
double difference;
double meanSquares = 0.0;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
x = dx - Math.floor(dx);
y = dy - Math.floor(dy);
xWeights();
yWeights();
if (outMsk == null) {
for (int v = 0; (v < outNy); v++) {
y = dy++;
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= yMsk) && (yMsk < inNy)) {
yMsk *= inNx;
yIndexes();
dx = dx0;
for (int u = 0; (u < outNx); u++, k++) {
x = dx++;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)) {
if (inMsk[yMsk + xMsk] != 0.0F) {
xIndexes();
area++;
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
}
}
}
}
else {
k += outNx;
}
}
}
else {
for (int v = 0; (v < outNy); v++) {
y = dy++;
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= yMsk) && (yMsk < inNy)) {
yMsk *= inNx;
yIndexes();
dx = dx0;
for (int u = 0; (u < outNx); u++, k++) {
x = dx++;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)) {
if ((outMsk[k] * inMsk[yMsk + xMsk]) != 0.0F) {
xIndexes();
area++;
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
}
}
}
}
else {
k += outNx;
}
}
}
return(meanSquares / (double)area);
} /* end getTranslationMeanSquares */
/*------------------------------------------------------------------*/
private double getTranslationMeanSquares (
final double[][] matrix,
final double[] gradient
) {
double dx = matrix[0][0];
double dy = matrix[1][0];
final double dx0 = dx;
double difference;
double meanSquares = 0.0;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
for (int i = 0; (i < transformation); i++) {
gradient[i] = 0.0;
}
x = dx - Math.floor(dx);
y = dy - Math.floor(dy);
xWeights();
yWeights();
if (outMsk == null) {
for (int v = 0; (v < outNy); v++) {
y = dy++;
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= yMsk) && (yMsk < inNy)) {
yMsk *= inNx;
yIndexes();
dx = dx0;
for (int u = 0; (u < outNx); u++, k++) {
x = dx++;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)) {
if (inMsk[yMsk + xMsk] != 0.0F) {
area++;
xIndexes();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
gradient[0] += difference * xGradient[k];
gradient[1] += difference * yGradient[k];
}
}
}
}
else {
k += outNx;
}
}
}
else {
for (int v = 0; (v < outNy); v++) {
y = dy++;
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= yMsk) && (yMsk < inNy)) {
yMsk *= inNx;
yIndexes();
dx = dx0;
for (int u = 0; (u < outNx); u++, k++) {
x = dx++;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)) {
if ((outMsk[k] * inMsk[yMsk + xMsk]) != 0.0F) {
area++;
xIndexes();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
gradient[0] += difference * xGradient[k];
gradient[1] += difference * yGradient[k];
}
}
}
}
else {
k += outNx;
}
}
}
return(meanSquares / (double)area);
} /* end getTranslationMeanSquares */
/*------------------------------------------------------------------*/
private double getTranslationMeanSquares (
final double[][] matrix,
final double[][] hessian,
final double[] gradient
) {
double dx = matrix[0][0];
double dy = matrix[1][0];
final double dx0 = dx;
double difference;
double meanSquares = 0.0;
long area = 0L;
int xMsk;
int yMsk;
int k = 0;
for (int i = 0; (i < transformation); i++) {
gradient[i] = 0.0;
for (int j = 0; (j < transformation); j++) {
hessian[i][j] = 0.0;
}
}
x = dx - Math.floor(dx);
y = dy - Math.floor(dy);
xWeights();
yWeights();
if (outMsk == null) {
for (int v = 0; (v < outNy); v++) {
y = dy++;
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= yMsk) && (yMsk < inNy)) {
yMsk *= inNx;
yIndexes();
dx = dx0;
for (int u = 0; (u < outNx); u++, k++) {
x = dx++;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)) {
if (inMsk[yMsk + xMsk] != 0.0F) {
area++;
xIndexes();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
gradient[0] += difference * xGradient[k];
gradient[1] += difference * yGradient[k];
hessian[0][0] += xGradient[k] * xGradient[k];
hessian[0][1] += xGradient[k] * yGradient[k];
hessian[1][1] += yGradient[k] * yGradient[k];
}
}
}
}
else {
k += outNx;
}
}
}
else {
for (int v = 0; (v < outNy); v++) {
y = dy++;
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= yMsk) && (yMsk < inNy)) {
yMsk *= inNx;
yIndexes();
dx = dx0;
for (int u = 0; (u < outNx); u++, k++) {
x = dx++;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)) {
if ((outMsk[k] * inMsk[yMsk + xMsk]) != 0.0F) {
area++;
xIndexes();
difference = (double)outImg[k] - interpolate();
meanSquares += difference * difference;
gradient[0] += difference * xGradient[k];
gradient[1] += difference * yGradient[k];
hessian[0][0] += xGradient[k] * xGradient[k];
hessian[0][1] += xGradient[k] * yGradient[k];
hessian[1][1] += yGradient[k] * yGradient[k];
}
}
}
}
else {
k += outNx;
}
}
}
for (int i = 1; (i < transformation); i++) {
for (int j = 0; (j < i); j++) {
hessian[i][j] = hessian[j][i];
}
}
return(meanSquares / (double)area);
} /* end getTranslationMeanSquares */
/*------------------------------------------------------------------*/
private double interpolate (
) {
t = 0.0;
for (int j = 0; (j < 4); j++) {
s = 0.0;
p = yIndex[j];
for (int i = 0; (i < 4); i++) {
s += xWeight[i] * (double)inImg[p + xIndex[i]];
}
t += yWeight[j] * s;
}
return(t);
} /* end interpolate */
/*------------------------------------------------------------------*/
private double interpolateDx (
) {
t = 0.0;
for (int j = 0; (j < 4); j++) {
s = 0.0;
p = yIndex[j];
for (int i = 0; (i < 4); i++) {
s += dxWeight[i] * (double)inImg[p + xIndex[i]];
}
t += yWeight[j] * s;
}
return(t);
} /* end interpolateDx */
/*------------------------------------------------------------------*/
private double interpolateDy (
) {
t = 0.0;
for (int j = 0; (j < 4); j++) {
s = 0.0;
p = yIndex[j];
for (int i = 0; (i < 4); i++) {
s += xWeight[i] * (double)inImg[p + xIndex[i]];
}
t += dyWeight[j] * s;
}
return(t);
} /* end interpolateDy */
/*------------------------------------------------------------------*/
private void inverseMarquardtLevenbergOptimization (
int workload
) {
final double[][] attempt = new double[transformation / 2][2];
final double[][] hessian = new double[transformation][transformation];
final double[][] pseudoHessian = new double[transformation][transformation];
final double[] gradient = new double[transformation];
double[][] matrix = getTransformationMatrix(sourcePoint, targetPoint);
double[] update = new double[transformation];
double bestMeanSquares = 0.0;
double meanSquares = 0.0;
double lambda = FIRST_LAMBDA;
double displacement;
int iteration = 0;
switch (transformation) {
case turboRegDialog.TRANSLATION: {
bestMeanSquares = getTranslationMeanSquares(
matrix, hessian, gradient);
break;
}
case turboRegDialog.SCALED_ROTATION: {
bestMeanSquares = getScaledRotationMeanSquares(
sourcePoint, matrix, hessian, gradient);
break;
}
case turboRegDialog.AFFINE: {
bestMeanSquares = getAffineMeanSquares(
sourcePoint, matrix, hessian, gradient);
break;
}
}
iteration++;
do {
for (int k = 0; (k < transformation); k++) {
pseudoHessian[k][k] = (1.0 + lambda) * hessian[k][k];
}
invertGauss(pseudoHessian);
update = matrixMultiply(pseudoHessian, gradient);
displacement = 0.0;
for (int k = 0; (k < (transformation / 2)); k++) {
attempt[k][0] = sourcePoint[k][0] - update[2 * k];
attempt[k][1] = sourcePoint[k][1] - update[2 * k + 1];
displacement += Math.sqrt(update[2 * k] * update[2 * k]
+ update[2 * k + 1] * update[2 * k + 1]);
}
displacement /= 0.5 * (double)transformation;
matrix = getTransformationMatrix(attempt, targetPoint);
switch (transformation) {
case turboRegDialog.TRANSLATION: {
if (accelerated) {
meanSquares = getTranslationMeanSquares(
matrix, gradient);
}
else {
meanSquares = getTranslationMeanSquares(
matrix, hessian, gradient);
}
break;
}
case turboRegDialog.SCALED_ROTATION: {
if (accelerated) {
meanSquares = getScaledRotationMeanSquares(
attempt, matrix, gradient);
}
else {
meanSquares = getScaledRotationMeanSquares(
attempt, matrix, hessian, gradient);
}
break;
}
case turboRegDialog.AFFINE: {
if (accelerated) {
meanSquares = getAffineMeanSquares(
attempt, matrix, gradient);
}
else {
meanSquares = getAffineMeanSquares(
attempt, matrix, hessian, gradient);
}
break;
}
}
iteration++;
if (meanSquares < bestMeanSquares) {
bestMeanSquares = meanSquares;
for (int k = 0; (k < (transformation / 2)); k++) {
sourcePoint[k][0] = attempt[k][0];
sourcePoint[k][1] = attempt[k][1];
}
lambda /= LAMBDA_MAGSTEP;
}
else {
lambda *= LAMBDA_MAGSTEP;
}
turboRegProgressBar.skipProgressBar(iterationCost);
workload--;
} while ((iteration < (maxIterations * iterationPower - 1))
&& (pixelPrecision <= displacement));
invertGauss(hessian);
update = matrixMultiply(hessian, gradient);
for (int k = 0; (k < (transformation / 2)); k++) {
attempt[k][0] = sourcePoint[k][0] - update[2 * k];
attempt[k][1] = sourcePoint[k][1] - update[2 * k + 1];
}
matrix = getTransformationMatrix(attempt, targetPoint);
switch (transformation) {
case turboRegDialog.TRANSLATION: {
meanSquares = getTranslationMeanSquares(matrix);
break;
}
case turboRegDialog.SCALED_ROTATION: {
meanSquares = getScaledRotationMeanSquares(attempt, matrix);
break;
}
case turboRegDialog.AFFINE: {
meanSquares = getAffineMeanSquares(attempt, matrix);
break;
}
}
iteration++;
if (meanSquares < bestMeanSquares) {
for (int k = 0; (k < (transformation / 2)); k++) {
sourcePoint[k][0] = attempt[k][0];
sourcePoint[k][1] = attempt[k][1];
}
}
turboRegProgressBar.skipProgressBar(workload * iterationCost);
} /* end inverseMarquardtLevenbergOptimization */
/*------------------------------------------------------------------*/
private void inverseMarquardtLevenbergRigidBodyOptimization (
int workload
) {
final double[][] attempt = new double[2][3];
final double[][] hessian = new double[transformation][transformation];
final double[][] pseudoHessian = new double[transformation][transformation];
final double[] gradient = new double[transformation];
double[][] matrix = getTransformationMatrix(targetPoint, sourcePoint);
double[] update = new double[transformation];
double bestMeanSquares = 0.0;
double meanSquares = 0.0;
double lambda = FIRST_LAMBDA;
double angle;
double c;
double s;
double displacement;
int iteration = 0;
for (int k = 0; (k < transformation); k++) {
sourcePoint[k][0] = matrix[0][0] + targetPoint[k][0] * matrix[0][1]
+ targetPoint[k][1] * matrix[0][2];
sourcePoint[k][1] = matrix[1][0] + targetPoint[k][0] * matrix[1][1]
+ targetPoint[k][1] * matrix[1][2];
}
matrix = getTransformationMatrix(sourcePoint, targetPoint);
bestMeanSquares = getRigidBodyMeanSquares(matrix, hessian, gradient);
iteration++;
do {
for (int k = 0; (k < transformation); k++) {
pseudoHessian[k][k] = (1.0 + lambda) * hessian[k][k];
}
invertGauss(pseudoHessian);
update = matrixMultiply(pseudoHessian, gradient);
angle = Math.atan2(matrix[0][2], matrix[0][1]) - update[0];
attempt[0][1] = Math.cos(angle);
attempt[0][2] = Math.sin(angle);
attempt[1][1] = -attempt[0][2];
attempt[1][2] = attempt[0][1];
c = Math.cos(update[0]);
s = Math.sin(update[0]);
attempt[0][0] = (matrix[0][0] + update[1]) * c
- (matrix[1][0] + update[2]) * s;
attempt[1][0] = (matrix[0][0] + update[1]) * s
+ (matrix[1][0] + update[2]) * c;
displacement = Math.sqrt(update[1] * update[1] + update[2] * update[2])
+ 0.25 * Math.sqrt((double)(inNx * inNx) + (double)(inNy * inNy))
* Math.abs(update[0]);
if (accelerated) {
meanSquares = getRigidBodyMeanSquares(attempt, gradient);
}
else {
meanSquares = getRigidBodyMeanSquares(attempt, hessian, gradient);
}
iteration++;
if (meanSquares < bestMeanSquares) {
bestMeanSquares = meanSquares;
for (int i = 0; (i < 2); i++) {
for (int j = 0; (j < 3); j++) {
matrix[i][j] = attempt[i][j];
}
}
lambda /= LAMBDA_MAGSTEP;
}
else {
lambda *= LAMBDA_MAGSTEP;
}
turboRegProgressBar.skipProgressBar(iterationCost);
workload--;
} while ((iteration < (maxIterations * iterationPower - 1))
&& (pixelPrecision <= displacement));
invertGauss(hessian);
update = matrixMultiply(hessian, gradient);
angle = Math.atan2(matrix[0][2], matrix[0][1]) - update[0];
attempt[0][1] = Math.cos(angle);
attempt[0][2] = Math.sin(angle);
attempt[1][1] = -attempt[0][2];
attempt[1][2] = attempt[0][1];
c = Math.cos(update[0]);
s = Math.sin(update[0]);
attempt[0][0] = (matrix[0][0] + update[1]) * c
- (matrix[1][0] + update[2]) * s;
attempt[1][0] = (matrix[0][0] + update[1]) * s
+ (matrix[1][0] + update[2]) * c;
meanSquares = getRigidBodyMeanSquares(attempt);
iteration++;
if (meanSquares < bestMeanSquares) {
for (int i = 0; (i < 2); i++) {
for (int j = 0; (j < 3); j++) {
matrix[i][j] = attempt[i][j];
}
}
}
for (int k = 0; (k < transformation); k++) {
sourcePoint[k][0] = (targetPoint[k][0] - matrix[0][0]) * matrix[0][1]
+ (targetPoint[k][1] - matrix[1][0]) * matrix[1][1];
sourcePoint[k][1] = (targetPoint[k][0] - matrix[0][0]) * matrix[0][2]
+ (targetPoint[k][1] - matrix[1][0]) * matrix[1][2];
}
turboRegProgressBar.skipProgressBar(workload * iterationCost);
} /* end inverseMarquardtLevenbergRigidBodyOptimization */
/*------------------------------------------------------------------*/
private void invertGauss (
final double[][] matrix
) {
final int n = matrix.length;
final double[][] inverse = new double[n][n];
for (int i = 0; (i < n); i++) {
double max = matrix[i][0];
double absMax = Math.abs(max);
for (int j = 0; (j < n); j++) {
inverse[i][j] = 0.0;
if (absMax < Math.abs(matrix[i][j])) {
max = matrix[i][j];
absMax = Math.abs(max);
}
}
inverse[i][i] = 1.0 / max;
for (int j = 0; (j < n); j++) {
matrix[i][j] /= max;
}
}
for (int j = 0; (j < n); j++) {
double max = matrix[j][j];
double absMax = Math.abs(max);
int k = j;
for (int i = j + 1; (i < n); i++) {
if (absMax < Math.abs(matrix[i][j])) {
max = matrix[i][j];
absMax = Math.abs(max);
k = i;
}
}
if (k != j) {
final double[] partialLine = new double[n - j];
final double[] fullLine = new double[n];
System.arraycopy(matrix[j], j, partialLine, 0, n - j);
System.arraycopy(matrix[k], j, matrix[j], j, n - j);
System.arraycopy(partialLine, 0, matrix[k], j, n - j);
System.arraycopy(inverse[j], 0, fullLine, 0, n);
System.arraycopy(inverse[k], 0, inverse[j], 0, n);
System.arraycopy(fullLine, 0, inverse[k], 0, n);
}
for (k = 0; (k <= j); k++) {
inverse[j][k] /= max;
}
for (k = j + 1; (k < n); k++) {
matrix[j][k] /= max;
inverse[j][k] /= max;
}
for (int i = j + 1; (i < n); i++) {
for (k = 0; (k <= j); k++) {
inverse[i][k] -= matrix[i][j] * inverse[j][k];
}
for (k = j + 1; (k < n); k++) {
matrix[i][k] -= matrix[i][j] * matrix[j][k];
inverse[i][k] -= matrix[i][j] * inverse[j][k];
}
}
}
for (int j = n - 1; (1 <= j); j--) {
for (int i = j - 1; (0 <= i); i--) {
for (int k = 0; (k <= j); k++) {
inverse[i][k] -= matrix[i][j] * inverse[j][k];
}
for (int k = j + 1; (k < n); k++) {
matrix[i][k] -= matrix[i][j] * matrix[j][k];
inverse[i][k] -= matrix[i][j] * inverse[j][k];
}
}
}
for (int i = 0; (i < n); i++) {
System.arraycopy(inverse[i], 0, matrix[i], 0, n);
}
} /* end invertGauss */
/*------------------------------------------------------------------*/
private void marquardtLevenbergOptimization (
int workload
) {
final double[][] attempt = new double[transformation / 2][2];
final double[][] hessian = new double[transformation][transformation];
final double[][] pseudoHessian = new double[transformation][transformation];
final double[] gradient = new double[transformation];
double[][] matrix = getTransformationMatrix(targetPoint, sourcePoint);
double[] update = new double[transformation];
double bestMeanSquares = 0.0;
double meanSquares = 0.0;
double lambda = FIRST_LAMBDA;
double displacement;
int iteration = 0;
bestMeanSquares = getBilinearMeanSquares(matrix, hessian, gradient);
iteration++;
do {
for (int k = 0; (k < transformation); k++) {
pseudoHessian[k][k] = (1.0 + lambda) * hessian[k][k];
}
invertGauss(pseudoHessian);
update = matrixMultiply(pseudoHessian, gradient);
displacement = 0.0;
for (int k = 0; (k < (transformation / 2)); k++) {
attempt[k][0] = sourcePoint[k][0] - update[2 * k];
attempt[k][1] = sourcePoint[k][1] - update[2 * k + 1];
displacement += Math.sqrt(update[2 * k] * update[2 * k]
+ update[2 * k + 1] * update[2 * k + 1]);
}
displacement /= 0.5 * (double)transformation;
matrix = getTransformationMatrix(targetPoint, attempt);
meanSquares = getBilinearMeanSquares(matrix, hessian, gradient);
iteration++;
if (meanSquares < bestMeanSquares) {
bestMeanSquares = meanSquares;
for (int k = 0; (k < (transformation / 2)); k++) {
sourcePoint[k][0] = attempt[k][0];
sourcePoint[k][1] = attempt[k][1];
}
lambda /= LAMBDA_MAGSTEP;
}
else {
lambda *= LAMBDA_MAGSTEP;
}
turboRegProgressBar.skipProgressBar(iterationCost);
workload--;
} while ((iteration < (maxIterations * iterationPower - 1))
&& (pixelPrecision <= displacement));
invertGauss(hessian);
update = matrixMultiply(hessian, gradient);
for (int k = 0; (k < (transformation / 2)); k++) {
attempt[k][0] = sourcePoint[k][0] - update[2 * k];
attempt[k][1] = sourcePoint[k][1] - update[2 * k + 1];
}
matrix = getTransformationMatrix(targetPoint, attempt);
meanSquares = getBilinearMeanSquares(matrix);
iteration++;
if (meanSquares < bestMeanSquares) {
for (int k = 0; (k < (transformation / 2)); k++) {
sourcePoint[k][0] = attempt[k][0];
sourcePoint[k][1] = attempt[k][1];
}
}
turboRegProgressBar.skipProgressBar(workload * iterationCost);
} /* end marquardtLevenbergOptimization */
/*------------------------------------------------------------------*/
private double[] matrixMultiply (
final double[][] matrix,
final double[] vector
) {
final double[] result = new double[matrix.length];
for (int i = 0; (i < matrix.length); i++) {
result[i] = 0.0;
for (int j = 0; (j < vector.length); j++) {
result[i] += matrix[i][j] * vector[j];
}
}
return(result);
} /* end matrixMultiply */
/*------------------------------------------------------------------*/
private void scaleBottomDownLandmarks (
) {
for (int depth = 1; (depth < pyramidDepth); depth++) {
if (transformation == turboRegDialog.RIGID_BODY) {
for (int n = 0; (n < transformation); n++) {
sourcePoint[n][0] *= 0.5;
sourcePoint[n][1] *= 0.5;
targetPoint[n][0] *= 0.5;
targetPoint[n][1] *= 0.5;
}
}
else {
for (int n = 0; (n < (transformation / 2)); n++) {
sourcePoint[n][0] *= 0.5;
sourcePoint[n][1] *= 0.5;
targetPoint[n][0] *= 0.5;
targetPoint[n][1] *= 0.5;
}
}
}
} /* end scaleBottomDownLandmarks */
/*------------------------------------------------------------------*/
private void scaleUpLandmarks (
) {
if (transformation == turboRegDialog.RIGID_BODY) {
for (int n = 0; (n < transformation); n++) {
sourcePoint[n][0] *= 2.0;
sourcePoint[n][1] *= 2.0;
targetPoint[n][0] *= 2.0;
targetPoint[n][1] *= 2.0;
}
}
else {
for (int n = 0; (n < (transformation / 2)); n++) {
sourcePoint[n][0] *= 2.0;
sourcePoint[n][1] *= 2.0;
targetPoint[n][0] *= 2.0;
targetPoint[n][1] *= 2.0;
}
}
} /* end scaleUpLandmarks */
/*------------------------------------------------------------------*/
private void translationTransform (
final double[][] matrix
) {
double dx = matrix[0][0];
double dy = matrix[1][0];
final double dx0 = dx;
int xMsk;
int yMsk;
x = dx - Math.floor(dx);
y = dy - Math.floor(dy);
if (!accelerated) {
xWeights();
yWeights();
}
int k = 0;
turboRegProgressBar.addWorkload(outNy);
for (int v = 0; (v < outNy); v++) {
y = dy++;
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= yMsk) && (yMsk < inNy)) {
yMsk *= inNx;
if (!accelerated) {
yIndexes();
}
dx = dx0;
for (int u = 0; (u < outNx); u++) {
x = dx++;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)) {
xMsk += yMsk;
if (accelerated) {
outImg[k++] = inImg[xMsk];
}
else {
xIndexes();
outImg[k++] = (float)interpolate();
}
}
else {
outImg[k++] = 0.0F;
}
}
}
else {
for (int u = 0; (u < outNx); u++) {
outImg[k++] = 0.0F;
}
}
turboRegProgressBar.stepProgressBar();
}
turboRegProgressBar.workloadDone(outNy);
} /* translationTransform */
/*------------------------------------------------------------------*/
private void translationTransform (
final double[][] matrix,
final float[] outMsk
) {
double dx = matrix[0][0];
double dy = matrix[1][0];
final double dx0 = dx;
int xMsk;
int yMsk;
x = dx - Math.floor(dx);
y = dy - Math.floor(dy);
if (!accelerated) {
xWeights();
yWeights();
}
int k = 0;
turboRegProgressBar.addWorkload(outNy);
for (int v = 0; (v < outNy); v++) {
y = dy++;
yMsk = (0.0 <= y) ? ((int)(y + 0.5)) : ((int)(y - 0.5));
if ((0 <= yMsk) && (yMsk < inNy)) {
yMsk *= inNx;
if (!accelerated) {
yIndexes();
}
dx = dx0;
for (int u = 0; (u < outNx); u++, k++) {
x = dx++;
xMsk = (0.0 <= x) ? ((int)(x + 0.5)) : ((int)(x - 0.5));
if ((0 <= xMsk) && (xMsk < inNx)) {
xMsk += yMsk;
if (accelerated) {
outImg[k] = inImg[xMsk];
}
else {
xIndexes();
outImg[k] = (float)interpolate();
}
outMsk[k] = inMsk[xMsk];
}
else {
outImg[k] = 0.0F;
outMsk[k] = 0.0F;
}
}
}
else {
for (int u = 0; (u < outNx); u++, k++) {
outImg[k] = 0.0F;
outMsk[k] = 0.0F;
}
}
turboRegProgressBar.stepProgressBar();
}
turboRegProgressBar.workloadDone(outNy);
} /* translationTransform */
/*------------------------------------------------------------------*/
private void xDxWeights (
) {
s = 1.0 - x;
dxWeight[0] = 0.5 * x * x;
xWeight[0] = x * dxWeight[0] / 3.0;
dxWeight[3] = -0.5 * s * s;
xWeight[3] = s * dxWeight[3] / -3.0;
dxWeight[1] = 1.0 - 2.0 * dxWeight[0] + dxWeight[3];
xWeight[1] = 2.0 / 3.0 + (1.0 + x) * dxWeight[3];
dxWeight[2] = 1.5 * x * (x - 4.0/ 3.0);
xWeight[2] = 2.0 / 3.0 - (2.0 - x) * dxWeight[0];
} /* xDxWeights */
/*------------------------------------------------------------------*/
private void xIndexes (
) {
p = (0.0 <= x) ? ((int)x + 2) : ((int)x + 1);
for (int k = 0; (k < 4); p--, k++) {
q = (p < 0) ? (-1 - p) : (p);
if (twiceInNx <= q) {
q -= twiceInNx * (q / twiceInNx);
}
xIndex[k] = (inNx <= q) ? (twiceInNx - 1 - q) : (q);
}
} /* xIndexes */
/*------------------------------------------------------------------*/
private void xWeights (
) {
s = 1.0 - x;
xWeight[3] = s * s * s / 6.0;
s = x * x;
xWeight[2] = 2.0 / 3.0 - 0.5 * s * (2.0 - x);
xWeight[0] = s * x / 6.0;
xWeight[1] = 1.0 - xWeight[0] - xWeight[2] - xWeight[3];
} /* xWeights */
/*------------------------------------------------------------------*/
private void yDyWeights (
) {
t = 1.0 - y;
dyWeight[0] = 0.5 * y * y;
yWeight[0] = y * dyWeight[0] / 3.0;
dyWeight[3] = -0.5 * t * t;
yWeight[3] = t * dyWeight[3] / -3.0;
dyWeight[1] = 1.0 - 2.0 * dyWeight[0] + dyWeight[3];
yWeight[1] = 2.0 / 3.0 + (1.0 + y) * dyWeight[3];
dyWeight[2] = 1.5 * y * (y - 4.0/ 3.0);
yWeight[2] = 2.0 / 3.0 - (2.0 - y) * dyWeight[0];
} /* yDyWeights */
/*------------------------------------------------------------------*/
private void yIndexes (
) {
p = (0.0 <= y) ? ((int)y + 2) : ((int)y + 1);
for (int k = 0; (k < 4); p--, k++) {
q = (p < 0) ? (-1 - p) : (p);
if (twiceInNy <= q) {
q -= twiceInNy * (q / twiceInNy);
}
yIndex[k] = (inNy <= q) ? ((twiceInNy - 1 - q) * inNx) : (q * inNx);
}
} /* yIndexes */
/*------------------------------------------------------------------*/
private void yWeights (
) {
t = 1.0 - y;
yWeight[3] = t * t * t / 6.0;
t = y * y;
yWeight[2] = 2.0 / 3.0 - 0.5 * t * (2.0 - y);
yWeight[0] = t * y / 6.0;
yWeight[1] = 1.0 - yWeight[0] - yWeight[2] - yWeight[3];
} /* yWeights */
} /* end class turboRegTransform */
| 294,009 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
BackgroundProcessor.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/align/BackgroundProcessor.java | package ezcol.align;
import ij.IJ;
import ij.ImagePlus;
import ij.measure.Calibration;
import ij.measure.Measurements;
import ij.plugin.filter.BackgroundSubtracter;
import ij.process.ImageProcessor;
import ij.process.ImageStatistics;
import ij.process.ShortProcessor;
import ij.process.AutoThresholder.Method;
import ij.process.ByteProcessor;
import ij.process.ColorProcessor;
import ij.process.FloatProcessor;
import ezcol.debug.ExceptionHandler;
public class BackgroundProcessor {
public static final boolean DEFAULT_CREATEBACKGROUND = false, DEFAULT_LIGHTBACKGROUND = true,
DEFAULT_USEPARABOLOID = false, DEFAULT_DOPRESMOOTH = true, DEFAULT_CORRECTCORNERS = true;
// The input ImageProcessor
private ImageProcessor srcIp;
// lightBackground means the histogram of the image is skewed to high values
// That is more pixels on the image have higher pixel values
// Assuming background has more pixels than the image,
private Boolean lightBackground;
// ipThred right now always keep objects as 255 and background as 0 with a regular LUT
// when using ParticleAnalyzer, please remember to invert it
private ByteProcessor ipThold;
private Method algorithm;
// Add in 1.1.0 to take in manualTholds
private double[] manualTholds = new double[] { ImageProcessor.NO_THRESHOLD, ImageProcessor.NO_THRESHOLD };
public BackgroundProcessor() {
srcIp = null;
algorithm = Method.Default;
}
public BackgroundProcessor(ImageProcessor inputIp) {
this(new ImagePlus("", inputIp));
}
public BackgroundProcessor(ImagePlus inputImp) {
this(inputImp, Method.Default.name());
}
public BackgroundProcessor(ImageProcessor inputIp, String inputString) {
this(new ImagePlus("", inputIp), inputString);
}
public BackgroundProcessor(ImagePlus inputImp, String inputString) {
srcIp = inputImp.getProcessor();
try{
algorithm = Method.valueOf(inputString);
}catch(Exception e){
algorithm = null;
}
}
// apply the threshold tothe input phase contrast image
public ByteProcessor thredImp() {
if(srcIp == null)
return null;
if (srcIp instanceof ColorProcessor) {
ExceptionHandler.addError(Thread.currentThread(), "Phase Contrast Image cannot be RGB");
ipThold = (ByteProcessor) srcIp.convertToByteProcessor().createProcessor(srcIp.getWidth(),
srcIp.getHeight());
}
else {
if(lightBackground == null)
setBackgroundOption(isLightBackground());
if (srcIp.isBinary()) {
ipThold = (ByteProcessor) srcIp.duplicate();
if(ipThold.isInvertedLut())
ipThold.invertLut();
if(lightBackground)
ipThold.invert();
} else {
ImageProcessor thredPhase = srcIp.duplicate();
if(thredPhase.isInvertedLut())
thredPhase.invertLut();
// Set the algorithm to default if manual thresholds are missing
if (algorithm == null && (manualTholds == null || manualTholds[0] == ImageProcessor.NO_THRESHOLD
|| manualTholds[1] == ImageProcessor.NO_THRESHOLD))
algorithm = Method.Default;
if (algorithm == null) {
thredPhase.setThreshold(manualTholds[0], manualTholds[1], ImageProcessor.NO_LUT_UPDATE);
applyManualThresholds(thredPhase, manualTholds);
} else {
thredPhase.setAutoThreshold(algorithm, !lightBackground, ImageProcessor.NO_LUT_UPDATE);
if(lightBackground)
thredPhase.threshold((int) thredPhase.getMaxThreshold());
else
thredPhase.threshold((int) thredPhase.getMinThreshold());
if(lightBackground)
thredPhase.invert();
}
ipThold = thredPhase.convertToByteProcessor(false);
}
}
return ipThold.convertToByteProcessor();
}
public ByteProcessor thredImp(Boolean lightBack) {
lightBackground = lightBack;
return thredImp();
}
public static ImageProcessor thredImp(ImageProcessor ip, String inputalgorithm) {
return BackgroundProcessor.thredImp(ip, inputalgorithm, BackgroundProcessor.isLightBackground(ip));
}
public static ImageProcessor thredImp(ImageProcessor ip, double[] manualTholds) {
return BackgroundProcessor.thredImp(ip, manualTholds, BackgroundProcessor.isLightBackground(ip));
}
/**
* This method will convert an image to a binary image
* which has pixel values of 255 for objects
* and 0 for background with a regular LUT
* Because the threshold might be different for light and dark background due to ties
* All light background images are converted to dark background first
* @param ip Input ImageProcessor
* @param inputalgorithm
* @param lightBackground
* @return A inverted binary mask with a regular LUT
*/
public static ByteProcessor thredImp(ImageProcessor ip, String inputalgorithm, Boolean lightBackground) {
if (ip instanceof ColorProcessor) {
ExceptionHandler.addError(Thread.currentThread(), "Phase Contrast Image cannot be RGB");
return null;
}
if(lightBackground == null)
lightBackground = isLightBackground(ip);
ByteProcessor byteIp;
if (ip.isBinary()) {
byteIp = (ByteProcessor) ip.duplicate();
if(byteIp.isInvertedLut())
byteIp.invertLut();
if(lightBackground)
byteIp.invert();
} else {
ImageProcessor rip = ip.duplicate();
if(rip.isInvertedLut())
rip.invertLut();
rip.setAutoThreshold(getMethod(inputalgorithm), !lightBackground, ImageProcessor.NO_LUT_UPDATE);
if(lightBackground)
rip.threshold((int) rip.getMaxThreshold());
else
rip.threshold((int) rip.getMinThreshold());
byteIp = rip.convertToByteProcessor(false);
if(lightBackground)
byteIp.invert();
}
return byteIp;
}
/**
* This method will convert an image to a binary image using a given range
* which has pixel values of 255 for objects
* and 0 for background with a regular LUT
* @see BackgroundProcessor#thredImp(ImageProcessor ip, String inputalgorithm, boolean lightBackground)
* @param ip
* @param manualTholds
* @param lightBackground
* @return
*/
public static ByteProcessor thredImp(ImageProcessor ip, double[] manualTholds, Boolean lightBackground) {
if (ip instanceof ColorProcessor) {
ExceptionHandler.addError(Thread.currentThread(), BackgroundProcessor.class.getName() + " cannot apply a threshold to a RGB image");
return null;
}
if(lightBackground == null)
lightBackground = isLightBackground(ip);
ImageProcessor rip = ip.duplicate();
if(rip.isInvertedLut())
rip.invertLut();
applyManualThresholds(rip, manualTholds);
return rip.convertToByteProcessor(false);
}
private static void applyManualThresholds(ImageProcessor ip, double[] thresholds){
int width = ip.getWidth();
int height = ip.getHeight();
int fillfront = 255, fillback = 0;
for (int w = 0; w < width; w++){
for (int h = 0; h < height; h++){
if (ip.get(w, h) >= thresholds[0] && ip.get(w, h) <= thresholds[1])
ip.set(w, h, fillfront);
else
ip.set(w, h, fillback);
}
}
if (ip instanceof ShortProcessor) {((ShortProcessor)ip).findMinAndMax();}
else if (ip instanceof FloatProcessor) {((FloatProcessor)ip).findMinAndMax();}
}
public boolean isLightBackground() {
if (srcIp != null) {
ImageStatistics ipStats = ImageStatistics.getStatistics(srcIp, Measurements.SKEWNESS, null);
return ipStats.skewness < 0;
}
return DEFAULT_LIGHTBACKGROUND;
}
public static boolean isLightBackground(ImageProcessor ip) {
if (ip != null) {
ImageStatistics ipStats = ImageStatistics.getStatistics(ip, Measurements.SKEWNESS, null);
return ipStats.skewness < 0;
}
return DEFAULT_LIGHTBACKGROUND;
}
/**
* Automatically detect if an image has dark or light background using
* skewness
* <p>
* skewness>=0: dark background
* <p>
* skewness< 0: light background
* <p>
* This might not be very accurate but sufficient for most flourescent
* images
*
* @param imp
* @return true if it is light background, false if it is dark background
*/
public static boolean isLightBackground(ImagePlus imp) {
if (imp != null) {
//Add in 1.1.0 avoid roi override
ImageProcessor ip = imp.getProcessor().duplicate();
ip.resetRoi();
ImageStatistics ipStats = ImageStatistics.getStatistics(ip, Measurements.SKEWNESS, null);
return ipStats.skewness < 0;
}
return DEFAULT_LIGHTBACKGROUND;
}
/**
* Return true if the image appears to have light background
* which takes inverted LUT into account
* @param imp
* @return
*/
public static boolean looksLightBackground(ImagePlus imp){
if(imp.getProcessor().isInvertedLut())
return !isLightBackground(imp);
else
return isLightBackground(imp);
}
public void setBackgroundOption(boolean lightBackground) {
this.lightBackground = lightBackground;
ipThold = null;
}
public static Method getMethod(String inputString) {
return Method.valueOf(Method.class, inputString);
}
public void setMethod(String inputString) {
algorithm = Method.valueOf(Method.class, inputString);
ipThold = null;
}
public void setInput(ImageProcessor ip) {
srcIp = ip;
ipThold = null;
}
/**
* Add in 2.0.0 here to set the manual thresholds (min and max)
* if *Manual* is selected
* Note: no need to reset ipThold here unless algorithm is null (*Manual*)
* @param thresholds
*/
public void setManualThresholds(double[] thresholds) {
this.manualTholds = thresholds;
if(algorithm == null)
ipThold = null;
}
public void reset() {
srcIp = null;
ipThold = null;
lightBackground = null;
algorithm = Method.Default;
}
public ByteProcessor getThredImg() {
if (ipThold == null)
return thredImp();
return (ByteProcessor) ipThold.duplicate();
}
public ByteProcessor getThredMask() {
if (ipThold == null)
thredImp();
ByteProcessor ipMask = (ByteProcessor) ipThold.duplicate();
ipMask.invert();
return ipMask;
}
public ImageStatistics calcBackground(ImageProcessor ip) {
return calcBackground(ip, Measurements.MEAN);
}
public ImageStatistics calcBackground(ImageProcessor ip, int measurements) {
return calcBackground(ip, measurements, isLightBackground(ip), null);
}
public ImageStatistics calcBackground(ImageProcessor ip, int measurements, boolean lightBack, Calibration cal) {
if (ip == null)
return null;
setBackgroundOption(lightBack);
thredImp();
ip.resetRoi();
ip.setMask(getThredMask());
//if (ip.getMax() >= ip.getMin())
// ip.setThreshold(ip.getMin() + Double.MIN_VALUE, ip.getMax(), ImageProcessor.NO_LUT_UPDATE);
ImageStatistics impStatistics = ImageStatistics.getStatistics(ip, measurements, cal);
return impStatistics;
}
public static void rollSubBackground(ImageProcessor subip, double radius) {
rollSubBackground(subip, radius, DEFAULT_CREATEBACKGROUND, isLightBackground(subip), DEFAULT_USEPARABOLOID,
DEFAULT_DOPRESMOOTH, DEFAULT_CORRECTCORNERS);
}
public static void rollSubBackground(ImageProcessor subip, double radius, Boolean lightBackground) {
if (lightBackground == null)
lightBackground = isLightBackground(subip);
rollSubBackground(subip, radius, DEFAULT_CREATEBACKGROUND, lightBackground, DEFAULT_USEPARABOLOID,
DEFAULT_DOPRESMOOTH, DEFAULT_CORRECTCORNERS);
}
public static void rollSubBackground(ImageProcessor subip, double radius, boolean createBackground,
boolean lightBackground, boolean useParaboloid, boolean doPresmooth, boolean correctCorners) {
BackgroundSubtracter subBack = new BackgroundSubtracter();
subBack.rollingBallBackground(subip, radius, createBackground, lightBackground, useParaboloid, doPresmooth,
correctCorners);
// erase progressbar
IJ.showProgress(1.1);
}
}
| 11,518 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
ImageAligner.java | /FileExtraction/Java_unseen/DrHanLim_EzColocalization/src/main/java/ezcol/align/ImageAligner.java | package ezcol.align;
/*
* This class is modified by Huanjie Sheng (UC Berkeley)
* from StackRegJ by Jay, Unruh from Stowers Institute for Medical Research
* http://research.stowers.org/imagejplugins/
*/
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.List;
import ij.*;
import ij.gui.GenericDialog;
import ij.process.*;
import ezcol.debug.ExceptionHandler;
import ezcol.main.PluginStatic;
public class ImageAligner {
// this plugin is a highly modified version of the StackReg plugin available
// from http://bigwww.epfl.ch/thevenaz/stackreg/
// this version will align a hyperstack based on a selected slice and
// channel
// the alignment outputs a translation trajectory for further alignments
private int slices, channels, frames, targetFrame, targetChannel, targetSlice, slices2, channels2, frames2;
private final String[] transformationItem = { "Translation", "Rigid Body", "Scaled Rotation", "Affine", };
private static double[][] manualTholds = PluginStatic.newArray(ImageProcessor.NO_THRESHOLD, 2, 2);
public ImageProcessor runAlignment(ImageProcessor imp1, ImageProcessor imp2, String transformationChoice,
String[] inputalgorithm, boolean[] lightBacks) {
return runAlignment(imp1, imp2, transformationChoice, inputalgorithm, lightBacks, false, null);
}
public ImageProcessor runAlignment(ImageProcessor ip1, ImageProcessor ip2, String transformationChoice,
String[] inputalgorithm, boolean[] lightBacks, boolean subtractBackground, double[] rollingBallSizes) {
if (ip1 == null || ip2 == null) {
ExceptionHandler.addError("Missing Images for alignment");
return null;
}
if (ip1.getHeight() != ip2.getHeight() || ip1.getWidth() != ip2.getWidth()) {
ExceptionHandler.addError("Dimensions mismatch");
return null;
}
if(rollingBallSizes == null || rollingBallSizes[0] <= 0)
subtractBackground = false;
if(lightBacks == null){
lightBacks = new boolean[2];
lightBacks[0] = BackgroundProcessor.isLightBackground(ip1);
lightBacks[1] = BackgroundProcessor.isLightBackground(ip2);
}
ImageProcessor imp1Byte, imp2Byte;
imp1Byte = ip1.duplicate();
// Add in 1.1.0 to deal with manual thresholds
if (PluginStatic.getMethod(inputalgorithm[0]) != null) {
if (subtractBackground && !ip1.isBinary())
BackgroundProcessor.rollSubBackground(imp1Byte, rollingBallSizes[0], lightBacks[0]);
imp1Byte = BackgroundProcessor.thredImp(imp1Byte, inputalgorithm[0], lightBacks[0]);
} else if (manualTholds == null || manualTholds[0] == null
|| manualTholds[0][0] == ImageProcessor.NO_THRESHOLD
|| manualTholds[0][1] == ImageProcessor.NO_THRESHOLD) {
if (subtractBackground && !ip1.isBinary())
BackgroundProcessor.rollSubBackground(imp1Byte, rollingBallSizes[0], lightBacks[0]);
imp1Byte = BackgroundProcessor.thredImp(imp1Byte, "Default", lightBacks[0]);
} else {
imp1Byte = BackgroundProcessor.thredImp(imp1Byte, manualTholds[0], lightBacks[0]);
}
imp2Byte = ip2.duplicate();
// Add in 1.1.0 to deal with manual thresholds
if (PluginStatic.getMethod(inputalgorithm[1]) != null) {
if (subtractBackground && !ip2.isBinary())
BackgroundProcessor.rollSubBackground(imp2Byte, rollingBallSizes[1], lightBacks[1]);
imp2Byte = BackgroundProcessor.thredImp(imp2Byte, inputalgorithm[1], lightBacks[1]);
} else if (manualTholds == null || manualTholds[1] == null
|| manualTholds[1][0] == ImageProcessor.NO_THRESHOLD
|| manualTholds[1][1] == ImageProcessor.NO_THRESHOLD) {
if (subtractBackground && !ip2.isBinary())
BackgroundProcessor.rollSubBackground(imp2Byte, rollingBallSizes[1], lightBacks[1]);
imp2Byte = BackgroundProcessor.thredImp(imp2Byte, "Default", lightBacks[1]);
} else {
imp2Byte = BackgroundProcessor.thredImp(imp2Byte, manualTholds[1], lightBacks[1]);
}
ImageStack stack1 = new ImageStack(imp1Byte.getWidth(), imp1Byte.getHeight());
ImageStack stack2 = new ImageStack(ip1.getWidth(), ip1.getHeight());
stack1.addSlice(imp1Byte);
stack1.addSlice(imp2Byte);
stack2.addSlice(ip2);
stack2.addSlice(ip2);
ImagePlus align1 = new ImagePlus("Align1", stack1);
ImagePlus align2 = new ImagePlus("Align2", stack2);
runAlignment(align1, align2, transformationChoice);
return align2.getStack().getProcessor(2);
}
private void runAlignment(ImagePlus imp, ImagePlus simp, String transformationChoice) {
List<String> transformationList = Arrays.asList(transformationItem);
final int transformation = transformationList.indexOf(transformationChoice);
final int width = imp.getWidth();
final int height = imp.getHeight();
slices = imp.getNSlices();
channels = imp.getNChannels();
frames = imp.getNFrames();
targetFrame = imp.getFrame();
targetChannel = imp.getChannel();
targetSlice = imp.getSlice();
if (simp != null) {
slices2 = simp.getNSlices();
channels2 = simp.getNChannels();
frames2 = simp.getNFrames();
}
if (frames == 1) {
frames = slices;
slices = 1;
targetFrame = targetSlice;
targetSlice = 1;
frames2 = slices2;
slices2 = 1;
}
if (frames2 != frames) {
ExceptionHandler.addError("Number of frames in images doesn't match, ignoring secondary");
simp = null;
}
double[][] globalTransform = { { 1.0, 0.0, 0.0 }, { 0.0, 1.0, 0.0 }, { 0.0, 0.0, 1.0 } };
double[][] anchorPoints = null;
switch (transformation) {
case 0: {
anchorPoints = new double[1][3];
anchorPoints[0][0] = (double) (width / 2);
anchorPoints[0][1] = (double) (height / 2);
anchorPoints[0][2] = 1.0;
break;
}
case 1: {
anchorPoints = new double[3][3];
anchorPoints[0][0] = (double) (width / 2);
anchorPoints[0][1] = (double) (height / 2);
anchorPoints[0][2] = 1.0;
anchorPoints[1][0] = (double) (width / 2);
anchorPoints[1][1] = (double) (height / 4);
anchorPoints[1][2] = 1.0;
anchorPoints[2][0] = (double) (width / 2);
anchorPoints[2][1] = (double) ((3 * height) / 4);
anchorPoints[2][2] = 1.0;
break;
}
case 2: {
anchorPoints = new double[2][3];
anchorPoints[0][0] = (double) (width / 4);
anchorPoints[0][1] = (double) (height / 2);
anchorPoints[0][2] = 1.0;
anchorPoints[1][0] = (double) ((3 * width) / 4);
anchorPoints[1][1] = (double) (height / 2);
anchorPoints[1][2] = 1.0;
break;
}
case 3: {
anchorPoints = new double[3][3];
anchorPoints[0][0] = (double) (width / 2);
anchorPoints[0][1] = (double) (height / 4);
anchorPoints[0][2] = 1.0;
anchorPoints[1][0] = (double) (width / 4);
anchorPoints[1][1] = (double) ((3 * height) / 4);
anchorPoints[1][2] = 1.0;
anchorPoints[2][0] = (double) ((3 * width) / 4);
anchorPoints[2][1] = (double) ((3 * height) / 4);
anchorPoints[2][2] = 1.0;
break;
}
default: {
ExceptionHandler.addError(Thread.currentThread(), "Unexpected transformation");
return;
}
}
ImagePlus target = new ImagePlus("StackRegTarget",
getImpProcessor(imp, targetChannel, targetSlice, targetFrame));
float[][] trans = new float[2][frames];
for (int f = (targetFrame - 1); f > 0; f--) {
if (!registerSlice(target, imp, width, height, transformation, globalTransform, anchorPoints, f, simp))
return;
float[] trans2 = get_translation(globalTransform, width, height);
trans[0][f - 1] = trans2[0];
trans[1][f - 1] = trans2[1];
}
if ((1 < targetFrame) && (targetFrame < frames)) {
globalTransform[0][0] = 1.0;
globalTransform[0][1] = 0.0;
globalTransform[0][2] = 0.0;
globalTransform[1][0] = 0.0;
globalTransform[1][1] = 1.0;
globalTransform[1][2] = 0.0;
globalTransform[2][0] = 0.0;
globalTransform[2][1] = 0.0;
globalTransform[2][2] = 1.0;
target.getProcessor().copyBits(getImpProcessor(imp, targetChannel, targetSlice, targetFrame), 0, 0,
Blitter.COPY);
}
for (int f = (targetFrame + 1); f <= frames; f++) {
if (!registerSlice(target, imp, width, height, transformation, globalTransform, anchorPoints, f, simp))
return;
float[] trans2 = get_translation(globalTransform, width, height);
trans[0][f - 1] = trans2[0];
trans[1][f - 1] = trans2[1];
}
// imp.updateAndDraw();
}
private float[] get_translation(double[][] globalTransform, int width, int height) {
double[][] anchorPoints = new double[1][3];
anchorPoints[0][0] = 0.5 * (double) width;
anchorPoints[0][1] = 0.5 * (double) height;
anchorPoints[0][2] = 1.0;
double[][] sourcePoints = new double[1][3];
for (int i = 0; (i < 3); i++) {
sourcePoints[0][i] = 0.0;
for (int j = 0; (j < 3); j++) {
sourcePoints[0][i] += globalTransform[i][j] * anchorPoints[0][j];
}
}
return new float[] { (float) (sourcePoints[0][0] - anchorPoints[0][0]),
(float) (sourcePoints[0][1] - anchorPoints[0][1]) };
}
private double[][] getTransformationMatrix(final double[][] fromCoord, final double[][] toCoord,
final int transformation) {
// this was copied essentially as is from StackReg
double[][] matrix = new double[3][3];
switch (transformation) {
case 0: {
matrix[0][0] = 1.0;
matrix[0][1] = 0.0;
matrix[0][2] = toCoord[0][0] - fromCoord[0][0];
matrix[1][0] = 0.0;
matrix[1][1] = 1.0;
matrix[1][2] = toCoord[0][1] - fromCoord[0][1];
break;
}
case 1: {
final double angle = Math.atan2(fromCoord[2][0] - fromCoord[1][0], fromCoord[2][1] - fromCoord[1][1])
- Math.atan2(toCoord[2][0] - toCoord[1][0], toCoord[2][1] - toCoord[1][1]);
final double c = Math.cos(angle);
final double s = Math.sin(angle);
matrix[0][0] = c;
matrix[0][1] = -s;
matrix[0][2] = toCoord[0][0] - c * fromCoord[0][0] + s * fromCoord[0][1];
matrix[1][0] = s;
matrix[1][1] = c;
matrix[1][2] = toCoord[0][1] - s * fromCoord[0][0] - c * fromCoord[0][1];
break;
}
case 2: {
double[][] a = new double[3][3];
double[] v = new double[3];
a[0][0] = fromCoord[0][0];
a[0][1] = fromCoord[0][1];
a[0][2] = 1.0;
a[1][0] = fromCoord[1][0];
a[1][1] = fromCoord[1][1];
a[1][2] = 1.0;
a[2][0] = fromCoord[0][1] - fromCoord[1][1] + fromCoord[1][0];
a[2][1] = fromCoord[1][0] + fromCoord[1][1] - fromCoord[0][0];
a[2][2] = 1.0;
invertGauss(a);
v[0] = toCoord[0][0];
v[1] = toCoord[1][0];
v[2] = toCoord[0][1] - toCoord[1][1] + toCoord[1][0];
for (int i = 0; (i < 3); i++) {
matrix[0][i] = 0.0;
for (int j = 0; (j < 3); j++) {
matrix[0][i] += a[i][j] * v[j];
}
}
v[0] = toCoord[0][1];
v[1] = toCoord[1][1];
v[2] = toCoord[1][0] + toCoord[1][1] - toCoord[0][0];
for (int i = 0; (i < 3); i++) {
matrix[1][i] = 0.0;
for (int j = 0; (j < 3); j++) {
matrix[1][i] += a[i][j] * v[j];
}
}
break;
}
case 3: {
double[][] a = new double[3][3];
double[] v = new double[3];
a[0][0] = fromCoord[0][0];
a[0][1] = fromCoord[0][1];
a[0][2] = 1.0;
a[1][0] = fromCoord[1][0];
a[1][1] = fromCoord[1][1];
a[1][2] = 1.0;
a[2][0] = fromCoord[2][0];
a[2][1] = fromCoord[2][1];
a[2][2] = 1.0;
invertGauss(a);
v[0] = toCoord[0][0];
v[1] = toCoord[1][0];
v[2] = toCoord[2][0];
for (int i = 0; (i < 3); i++) {
matrix[0][i] = 0.0;
for (int j = 0; (j < 3); j++) {
matrix[0][i] += a[i][j] * v[j];
}
}
v[0] = toCoord[0][1];
v[1] = toCoord[1][1];
v[2] = toCoord[2][1];
for (int i = 0; (i < 3); i++) {
matrix[1][i] = 0.0;
for (int j = 0; (j < 3); j++) {
matrix[1][i] += a[i][j] * v[j];
}
}
break;
}
default: {
ExceptionHandler.addError(Thread.currentThread(), "Unexpected transformation");
}
}
matrix[2][0] = 0.0;
matrix[2][1] = 0.0;
matrix[2][2] = 1.0;
return (matrix);
} /* end getTransformationMatrix */
/*------------------------------------------------------------------*/
private void invertGauss(final double[][] matrix) {
// also copied from StackReg
final int n = matrix.length;
final double[][] inverse = new double[n][n];
for (int i = 0; (i < n); i++) {
double max = matrix[i][0];
double absMax = Math.abs(max);
for (int j = 0; (j < n); j++) {
inverse[i][j] = 0.0;
if (absMax < Math.abs(matrix[i][j])) {
max = matrix[i][j];
absMax = Math.abs(max);
}
}
inverse[i][i] = 1.0 / max;
for (int j = 0; (j < n); j++) {
matrix[i][j] /= max;
}
}
for (int j = 0; (j < n); j++) {
double max = matrix[j][j];
double absMax = Math.abs(max);
int k = j;
for (int i = j + 1; (i < n); i++) {
if (absMax < Math.abs(matrix[i][j])) {
max = matrix[i][j];
absMax = Math.abs(max);
k = i;
}
}
if (k != j) {
final double[] partialLine = new double[n - j];
final double[] fullLine = new double[n];
System.arraycopy(matrix[j], j, partialLine, 0, n - j);
System.arraycopy(matrix[k], j, matrix[j], j, n - j);
System.arraycopy(partialLine, 0, matrix[k], j, n - j);
System.arraycopy(inverse[j], 0, fullLine, 0, n);
System.arraycopy(inverse[k], 0, inverse[j], 0, n);
System.arraycopy(fullLine, 0, inverse[k], 0, n);
}
for (k = 0; (k <= j); k++) {
inverse[j][k] /= max;
}
for (k = j + 1; (k < n); k++) {
matrix[j][k] /= max;
inverse[j][k] /= max;
}
for (int i = j + 1; (i < n); i++) {
for (k = 0; (k <= j); k++) {
inverse[i][k] -= matrix[i][j] * inverse[j][k];
}
for (k = j + 1; (k < n); k++) {
matrix[i][k] -= matrix[i][j] * matrix[j][k];
inverse[i][k] -= matrix[i][j] * inverse[j][k];
}
}
}
for (int j = n - 1; (1 <= j); j--) {
for (int i = j - 1; (0 <= i); i--) {
for (int k = 0; (k <= j); k++) {
inverse[i][k] -= matrix[i][j] * inverse[j][k];
}
for (int k = j + 1; (k < n); k++) {
matrix[i][k] -= matrix[i][j] * matrix[j][k];
inverse[i][k] -= matrix[i][j] * inverse[j][k];
}
}
}
for (int i = 0; (i < n); i++) {
System.arraycopy(inverse[i], 0, matrix[i], 0, n);
}
} /* end invertGauss */
public void setHyperstackSlice(ImagePlus imp, int channel, int slice, int frame) {
// imp.setSlice((channel-1)+(slice-1)*channels+(frame-1)*slices*channels+1);
imp.setPosition((channel - 1) + (slice - 1) * channels + (frame - 1) * slices * channels + 1);
// int[]
// pos=imp.convertIndexToPosition((channel-1)+(slice-1)*channels+(frame-1)*slices*channels+1);
// imp.setPositionWithoutUpdate(pos[0],pos[1],pos[2]);
}
public ImageProcessor getImpProcessor(final ImagePlus imp, int channel, int slice, int frame) {
int index = (channel - 1) + (slice - 1) * channels + (frame - 1) * slices * channels + 1;
return imp.getStack().getProcessor(index).convertToFloat();
}
public void setImpProcessor(final ImagePlus imp, ImagePlus source, int channel, int slice, int frame) {
source.getStack().deleteLastSlice();
int index = (channel - 1) + (slice - 1) * channels + (frame - 1) * slices * channels + 1;
switch (imp.getType()) {
case ImagePlus.GRAY8: {
source.getProcessor().setMinAndMax(0.0, 255.0);
imp.getStack().setPixels(source.getProcessor().convertToByte(false).getPixels(), index);
break;
}
case ImagePlus.GRAY16: {
source.getProcessor().setMinAndMax(0.0, 65535.0);
imp.getStack().setPixels(source.getProcessor().convertToShort(false).getPixels(), index);
break;
}
case ImagePlus.GRAY32: {
imp.getStack().setPixels(source.getProcessor().getPixels(), index);
break;
}
default: {
ExceptionHandler.addError(Thread.currentThread(), "Unexpected image type");
}
}
}
/*------------------------------------------------------------------*/
private boolean registerSlice(final ImagePlus target, final ImagePlus imp, final int width, final int height,
final int transformation, final double[][] globalTransform, final double[][] anchorPoints, final int f,
final ImagePlus simp) {
// imp.setSlice(s);
// setHyperstackSlice(imp,targetChannel,targetSlice,f);
double[][] sourcePoints = null;
double[][] targetPoints = null;
double[][] localTransform = null;
ImagePlus source = new ImagePlus("StackRegSource", getImpProcessor(imp, targetChannel, targetSlice, f));
TurboRegJ trj = gettrj();
switch (transformation) {
case 0: {
// simple translation
trj.setTargetPoints(new double[][] { { width / 2, height / 2 } });
trj.setSourcePoints(new double[][] { { width / 2, height / 2 } });
trj.initAlignment(source, target, TurboRegJ.TRANSLATION);
break;
}
case 1: {
// rigid body
trj.setSourcePoints(new double[][] { { width / 2, height / 2 }, { width / 2, height / 4 },
{ width / 2, 3 * height / 4 } });
trj.setTargetPoints(new double[][] { { width / 2, height / 2 }, { width / 2, height / 4 },
{ width / 2, 3 * height / 4 } });
trj.initAlignment(source, target, TurboRegJ.RIGID_BODY);
break;
}
case 2: {
// scaled rotation
trj.setSourcePoints(new double[][] { { width / 4, height / 2 }, { 3 * width / 4, height / 2 } });
trj.setTargetPoints(new double[][] { { width / 4, height / 2 }, { 3 * width / 4, height / 2 } });
trj.initAlignment(source, target, TurboRegJ.SCALED_ROTATION);
break;
}
case 3: {
// affine
trj.setSourcePoints(new double[][] { { width / 2, height / 4 }, { width / 4, 3 * height / 4 },
{ 3 * width / 4, 3 * height / 4 } });
trj.setTargetPoints(new double[][] { { width / 2, height / 4 }, { width / 4, 3 * height / 4 },
{ 3 * width / 4, 3 * height / 4 } });
trj.initAlignment(source, target, TurboRegJ.AFFINE);
break;
}
default: {
ExceptionHandler.addError(Thread.currentThread(), "Unexpected transformation");
return false;
}
}
target.setProcessor(null, source.getProcessor());
sourcePoints = trj.getSourcePoints();
targetPoints = trj.getTargetPoints();
localTransform = getTransformationMatrix(targetPoints, sourcePoints, transformation);
double[][] rescued = { { globalTransform[0][0], globalTransform[0][1], globalTransform[0][2] },
{ globalTransform[1][0], globalTransform[1][1], globalTransform[1][2] },
{ globalTransform[2][0], globalTransform[2][1], globalTransform[2][2] } };
// here multiply the global transformation by the recent local transform
// to add all previous transformations
for (int i = 0; (i < 3); i++) {
for (int j = 0; (j < 3); j++) {
globalTransform[i][j] = 0.0;
for (int k = 0; (k < 3); k++) {
globalTransform[i][j] += localTransform[i][k] * rescued[k][j];
}
}
}
switch (transformation) {
case 0: {
sourcePoints = new double[1][3];
for (int i = 0; (i < 3); i++) {
sourcePoints[0][i] = 0.0;
for (int j = 0; (j < 3); j++) {
sourcePoints[0][i] += globalTransform[i][j] * anchorPoints[0][j];
}
}
for (int i = 1; i <= slices; i++) {
for (int j = 1; j <= channels; j++) {
trj = gettrj();
trj.setSourcePoints(new double[][] { { sourcePoints[0][0], sourcePoints[0][1] } });
trj.setTargetPoints(new double[][] { { width / 2, height / 2 } });
ImagePlus source2 = new ImagePlus("StackRegSource", getImpProcessor(imp, j, i, f));
ImagePlus transformed = trj.transformImage(source2, width, height, TurboRegJ.TRANSLATION);
if (transformed == null)
return false;
setImpProcessor(imp, transformed, j, i, f);
}
}
if (simp != null) {
for (int i = 1; i <= slices2; i++) {
for (int j = 1; j <= channels2; j++) {
trj = gettrj();
trj.setSourcePoints(
new double[][] { { Math.round(sourcePoints[0][0]), Math.round(sourcePoints[0][1]) } });
trj.setTargetPoints(new double[][] { { Math.round(width / 2), Math.round(height / 2) } });
ImagePlus source2 = new ImagePlus("StackRegSource", getImpProcessor(simp, j, i, f));
ImagePlus transformed = trj.transformImage(source2, width, height, TurboRegJ.TRANSLATION);
if (transformed == null)
return false;
setImpProcessor(simp, transformed, j, i, f);
}
}
}
break;
}
case 1: {
sourcePoints = new double[3][3];
for (int i = 0; (i < 3); i++) {
sourcePoints[0][i] = 0.0;
sourcePoints[1][i] = 0.0;
sourcePoints[2][i] = 0.0;
for (int j = 0; (j < 3); j++) {
sourcePoints[0][i] += globalTransform[i][j] * anchorPoints[0][j];
sourcePoints[1][i] += globalTransform[i][j] * anchorPoints[1][j];
sourcePoints[2][i] += globalTransform[i][j] * anchorPoints[2][j];
}
}
for (int i = 1; i <= slices; i++) {
for (int j = 1; j <= channels; j++) {
trj = gettrj();
trj.setSourcePoints(new double[][] { { sourcePoints[0][0], sourcePoints[0][1] },
{ sourcePoints[1][0], sourcePoints[1][1] }, { sourcePoints[2][0], sourcePoints[2][1] } });
trj.setTargetPoints(new double[][] { { width / 2, height / 2 }, { width / 2, height / 4 },
{ width / 2, 3 * height / 4 } });
ImagePlus source2 = new ImagePlus("StackRegSource", getImpProcessor(imp, j, i, f));
ImagePlus transformed = trj.transformImage(source2, width, height, TurboRegJ.RIGID_BODY);
if (transformed == null)
return false;
setImpProcessor(imp, transformed, j, i, f);
}
}
if (simp != null) {
for (int i = 1; i <= slices2; i++) {
for (int j = 1; j <= channels2; j++) {
trj = gettrj();
trj.setSourcePoints(
new double[][] { { Math.round(sourcePoints[0][0]), Math.round(sourcePoints[0][1]) },
{ Math.round(sourcePoints[1][0]), Math.round(sourcePoints[1][1]) },
{ Math.round(sourcePoints[2][0]), Math.round(sourcePoints[2][1]) } });
trj.setTargetPoints(new double[][] { { Math.round(width / 2), Math.round(height / 2) },
{ Math.round(width / 2), Math.round(height / 4) },
{ Math.round(width / 2), Math.round(3 * height / 4) } });
ImagePlus source2 = new ImagePlus("StackRegSource", getImpProcessor(simp, j, i, f));
ImagePlus transformed = trj.transformImage(source2, width, height, TurboRegJ.RIGID_BODY);
if (transformed == null)
return false;
setImpProcessor(simp, transformed, j, i, f);
}
}
}
break;
}
case 2: {
sourcePoints = new double[2][3];
for (int i = 0; (i < 3); i++) {
sourcePoints[0][i] = 0.0;
sourcePoints[1][i] = 0.0;
for (int j = 0; (j < 3); j++) {
sourcePoints[0][i] += globalTransform[i][j] * anchorPoints[0][j];
sourcePoints[1][i] += globalTransform[i][j] * anchorPoints[1][j];
}
}
for (int i = 1; i <= slices; i++) {
for (int j = 1; j <= channels; j++) {
trj = gettrj();
trj.setSourcePoints(new double[][] { { sourcePoints[0][0], sourcePoints[0][1] },
{ sourcePoints[1][0], sourcePoints[1][1] } });
trj.setTargetPoints(new double[][] { { width / 4, height / 2 }, { 3 * width / 4, height / 2 } });
ImagePlus source2 = new ImagePlus("StackRegSource", getImpProcessor(imp, j, i, f));
ImagePlus transformed = trj.transformImage(source2, width, height, TurboRegJ.SCALED_ROTATION);
if (transformed == null)
return false;
setImpProcessor(imp, transformed, j, i, f);
}
}
if (simp != null) {
for (int i = 1; i <= slices2; i++) {
for (int j = 1; j <= channels2; j++) {
trj = gettrj();
trj.setSourcePoints(
new double[][] { { Math.round(sourcePoints[0][0]), Math.round(sourcePoints[0][1]) },
{ Math.round(sourcePoints[1][0]), Math.round(sourcePoints[1][1]) } });
trj.setTargetPoints(new double[][] { { Math.round(width / 4), Math.round(height / 2) },
{ Math.round(3 * width / 4), Math.round(height / 2) } });
ImagePlus source2 = new ImagePlus("StackRegSource", getImpProcessor(simp, j, i, f));
ImagePlus transformed = trj.transformImage(source2, width, height, TurboRegJ.SCALED_ROTATION);
if (transformed == null)
return false;
setImpProcessor(simp, transformed, j, i, f);
}
}
}
break;
}
case 3: {
sourcePoints = new double[3][3];
for (int i = 0; (i < 3); i++) {
sourcePoints[0][i] = 0.0;
sourcePoints[1][i] = 0.0;
sourcePoints[2][i] = 0.0;
for (int j = 0; (j < 3); j++) {
sourcePoints[0][i] += globalTransform[i][j] * anchorPoints[0][j];
sourcePoints[1][i] += globalTransform[i][j] * anchorPoints[1][j];
sourcePoints[2][i] += globalTransform[i][j] * anchorPoints[2][j];
}
}
for (int i = 1; i <= slices; i++) {
for (int j = 1; j <= channels; j++) {
trj = gettrj();
trj.setSourcePoints(new double[][] { { sourcePoints[0][0], sourcePoints[0][1] },
{ sourcePoints[1][0], sourcePoints[1][1] }, { sourcePoints[2][0], sourcePoints[2][1] } });
trj.setTargetPoints(new double[][] { { width / 2, height / 4 }, { width / 4, 3 * height / 4 },
{ 3 * width / 4, 3 * height / 4 } });
ImagePlus source2 = new ImagePlus("StackRegSource", getImpProcessor(imp, j, i, f));
ImagePlus transformed = trj.transformImage(source2, width, height, TurboRegJ.AFFINE);
if (transformed == null)
return false;
setImpProcessor(imp, transformed, j, i, f);
}
}
if (simp != null) {
for (int i = 1; i <= slices2; i++) {
for (int j = 1; j <= channels2; j++) {
trj = gettrj();
trj.setSourcePoints(
new double[][] { { Math.round(sourcePoints[0][0]), Math.round(sourcePoints[0][1]) },
{ Math.round(sourcePoints[1][0]), Math.round(sourcePoints[1][1]) },
{ Math.round(sourcePoints[2][0]), Math.round(sourcePoints[2][1]) } });
trj.setTargetPoints(new double[][] { { Math.round(width / 2), Math.round(height / 4) },
{ Math.round(width / 4), Math.round(3 * height / 4) },
{ Math.round(3 * width / 4), Math.round(3 * height / 4) } });
ImagePlus source2 = new ImagePlus("StackRegSource", getImpProcessor(simp, j, i, f));
ImagePlus transformed = trj.transformImage(source2, width, height, TurboRegJ.AFFINE);
if (transformed == null)
return false;
setImpProcessor(simp, transformed, j, i, f);
}
}
}
break;
}
}
return true;
}
public TurboRegJ gettrj() {
try {
Class<?> c = Class
.forName(this.getClass().getPackage().getName() + "." + TurboRegMod.class.getSimpleName());
Object tr = c.newInstance();
return new TurboRegJ(tr);
} catch (Throwable e) {
IJ.log(e.toString());
}
return null;
}
public static ImagePlus[] selectImages(boolean addnull, int nimages, String[] labels) {
Object[] windowlist = getImageWindowList(addnull);
String[] titles = (String[]) windowlist[1];
int[] ids = (int[]) windowlist[0];
GenericDialog gd = new GenericDialog("Select Images");
for (int i = 0; i < nimages; i++) {
gd.addChoice(labels[i], titles, titles[0]);
}
gd.showDialog();
if (gd.wasCanceled()) {
return null;
}
ImagePlus[] windows = new ImagePlus[nimages];
for (int i = 0; i < nimages; i++) {
int index = gd.getNextChoiceIndex();
if (index == ids.length) {
windows[i] = null;
} else {
windows[i] = WindowManager.getImage(ids[index]);
}
}
return windows;
}
public static Object[] getImageWindowList(boolean addnull) {
int[] ids = WindowManager.getIDList();
String[] titles = null;
if (addnull) {
titles = new String[ids.length + 1];
} else {
titles = new String[ids.length];
}
for (int i = 0; i < ids.length; i++) {
ImagePlus imp = WindowManager.getImage(ids[i]);
if (imp != null) {
titles[i] = imp.getTitle();
} else {
titles[i] = "";
}
}
if (addnull) {
titles[ids.length] = "null";
}
Object[] retvals = { ids, titles };
return retvals;
}
public static ImagePlus[] selectImages(boolean addnull, int nimages) {
String[] labels = new String[nimages];
for (int i = 0; i < nimages; i++) {
labels[i] = "Image" + (i + 1);
}
return selectImages(addnull, nimages, labels);
}
public static void setManualThresholds(double[][] thresholds) {
manualTholds = thresholds;
}
}
class TurboRegJ {
// this is an adaptor class to provide access to TurboReg_ without scripting
public static final int AFFINE = 6;
public static final int RIGID_BODY = 3;
public static final int SCALED_ROTATION = 4;
public static final int TRANSLATION = 2;
public Object tr;
/*
* public TurboRegJ(){ tr=new TurboReg_(); }
*/
public TurboRegJ(Object tr) {
this.tr = tr;
}
public double[][] getSourcePoints() {
// return tr.getSourcePoints();
return (double[][]) getReflectionField(tr, "sourcePoints");
}
public double[][] getTargetPoints() {
// return tr.getTargetPoints();
return (double[][]) getReflectionField(tr, "targetPoints");
}
public void setSourcePoints(double[][] sourcePoints) {
double[][] temp = getSourcePoints();
for (int i = 0; i < sourcePoints.length; i++) {
for (int j = 0; j < sourcePoints[i].length; j++) {
temp[i][j] = sourcePoints[i][j];
}
}
}
public void setTargetPoints(double[][] targetPoints) {
double[][] temp = getTargetPoints();
for (int i = 0; i < targetPoints.length; i++) {
for (int j = 0; j < targetPoints[i].length; j++) {
temp[i][j] = targetPoints[i][j];
}
}
}
public ImagePlus initAlignment(final ImagePlus source, final ImagePlus target, final int transformation) {
int[] sourceCrop = { 0, 0, source.getWidth(), source.getHeight() };
Object[] args = { source, sourceCrop, target, sourceCrop, transformation, new Boolean(false) };
return (ImagePlus) runReflectionMethod(tr, "alignImages", args);
}
public ImagePlus transformImage(ImagePlus source, int width, int height, int transformation) {
Object[] args = { source, width, height, transformation, new Boolean(false) };
return (ImagePlus) runReflectionMethod(tr, "transformImage", args);
}
public static Object runReflectionMethod(Object obj, String method, Object[] args) {
// here we automatically assume that number types are primitive
if (args == null)
return runReflectionMethod(obj, method, null, null);
@SuppressWarnings("rawtypes")
Class[] argcs = new Class[args.length];
for (int i = 0; i < args.length; i++)
argcs[i] = args[i].getClass();
for (int i = 0; i < argcs.length; i++) {
if (argcs[i] == Integer.class)
argcs[i] = Integer.TYPE;
if (argcs[i] == Float.class)
argcs[i] = Float.TYPE;
if (argcs[i] == Double.class)
argcs[i] = Double.TYPE;
if (argcs[i] == Short.class)
argcs[i] = Short.TYPE;
if (argcs[i] == Byte.class)
argcs[i] = Byte.TYPE;
if (argcs[i] == Boolean.class)
argcs[i] = Boolean.TYPE;
}
return runReflectionMethod(obj, method, args, argcs);
}
@SuppressWarnings("rawtypes")
public static Object runReflectionMethod(Object obj, String method, Object[] args, Class[] argcs) {
try {
Class<?> temp = obj.getClass();
Method meth = temp.getDeclaredMethod(method, argcs);
meth.setAccessible(true);
try {
Object data = meth.invoke(obj, args);
return data;
} catch (IllegalAccessException e) {
IJ.log("illegal access exception");
} catch (InvocationTargetException e) {
IJ.log("invocation target exception");
} catch (ClassCastException e) {
IJ.log(e.getMessage());
}
} catch (NoSuchMethodException e) {
IJ.log("no such method exception");
}
return null;
}
public static Object getReflectionField(Object obj, String fieldname) {
try {
Class<?> temp = obj.getClass();
Field field = temp.getDeclaredField(fieldname);
field.setAccessible(true);
return field.get(obj);
} catch (NoSuchFieldException e) {
IJ.log("no such field exception");
} catch (IllegalArgumentException e) {
IJ.log("illegal argument exception");
} catch (IllegalAccessException e) {
IJ.log("illegal access exception");
}
return null;
}
}
| 31,587 | Java | .java | DrHanLim/EzColocalization | 10 | 2 | 3 | 2018-02-07T15:55:13Z | 2020-12-23T18:07:14Z |
ClientProxy.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/ClientProxy.java | package mchorse.blockbuster;
import mchorse.blockbuster.aperture.CameraHandler;
import mchorse.blockbuster.api.ModelClientHandler;
import mchorse.blockbuster.api.ModelHandler;
import mchorse.blockbuster.audio.AudioLibrary;
import mchorse.blockbuster.client.ActorsPack;
import mchorse.blockbuster.client.KeyboardHandler;
import mchorse.blockbuster.client.RenderingHandler;
import mchorse.blockbuster.client.gui.GuiRecordingOverlay;
import mchorse.blockbuster.client.gui.dashboard.GuiBlockbusterPanels;
import mchorse.blockbuster.client.render.GunMiscRender;
import mchorse.blockbuster.client.render.RenderActor;
import mchorse.blockbuster.client.render.RenderExpirableDummy;
import mchorse.blockbuster.client.render.RenderGunProjectile;
import mchorse.blockbuster.client.render.tileentity.TileEntityDirectorRenderer;
import mchorse.blockbuster.client.render.tileentity.TileEntityGunItemStackRenderer;
import mchorse.blockbuster.client.render.tileentity.TileEntityModelItemStackRenderer;
import mchorse.blockbuster.client.render.tileentity.TileEntityModelRenderer;
import mchorse.blockbuster.commands.CommandItemNBT;
import mchorse.blockbuster.commands.CommandModel;
import mchorse.blockbuster.common.block.BlockGreen.ChromaColor;
import mchorse.blockbuster.common.entity.EntityActor;
import mchorse.blockbuster.common.entity.EntityGunProjectile;
import mchorse.blockbuster.common.entity.ExpirableDummyEntity;
import mchorse.blockbuster.common.tileentity.TileEntityDirector;
import mchorse.blockbuster.common.tileentity.TileEntityModel;
import mchorse.blockbuster.recording.RecordManager;
import mchorse.blockbuster.recording.capturing.FrameHandler;
import mchorse.blockbuster.utils.mclib.BlockbusterJarTree;
import mchorse.blockbuster.utils.mclib.BlockbusterTree;
import mchorse.blockbuster_pack.client.gui.trackers.GuiMorphTracking;
import mchorse.blockbuster_pack.client.gui.trackers.GuiBaseTracker;
import mchorse.blockbuster_pack.client.render.RenderCustomActor;
import mchorse.blockbuster_pack.morphs.StructureMorph;
import mchorse.blockbuster_pack.morphs.structure.StructureRenderer;
import mchorse.blockbuster_pack.trackers.ApertureCamera;
import mchorse.blockbuster_pack.trackers.MorphTracker;
import mchorse.blockbuster_pack.trackers.BaseTracker;
import mchorse.blockbuster_pack.trackers.TrackerRegistry;
import mchorse.mclib.McLib;
import mchorse.mclib.utils.files.FileTree;
import mchorse.mclib.utils.files.GlobalTree;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.ItemMeshDefinition;
import net.minecraft.client.renderer.ItemModelMesher;
import net.minecraft.client.renderer.block.model.ModelBakery;
import net.minecraft.client.renderer.block.model.ModelResourceLocation;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.resources.IReloadableResourceManager;
import net.minecraft.client.resources.IResourceManager;
import net.minecraft.client.resources.IResourcePack;
import net.minecraft.client.resources.SimpleReloadableResourceManager;
import net.minecraft.item.Item;
import net.minecraftforge.client.ClientCommandHandler;
import net.minecraftforge.client.model.ModelLoader;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.client.FMLClientHandler;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.client.registry.IRenderFactory;
import net.minecraftforge.fml.client.registry.RenderingRegistry;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.io.File;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;
/**
* Client proxy
*
* This class is responsible for registering item models, block models, entity
* renders and injecting actor skin resource pack.
*/
@SideOnly(Side.CLIENT)
public class ClientProxy extends CommonProxy
{
public static ActorsPack actorPack;
public static GuiRecordingOverlay recordingOverlay;
public static GuiBlockbusterPanels panels;
public static RecordManager manager = new RecordManager();
public static RenderCustomActor actorRenderer;
public static TileEntityModelRenderer modelRenderer;
public static KeyboardHandler keys;
public static BlockbusterTree tree;
public static AudioLibrary audio;
public static File skinsFolder;
/**
* Register mod items, blocks, tile entites and entities, load item,
* block models and register entity renderer.
*/
@Override
public void preLoad(FMLPreInitializationEvent event)
{
super.preLoad(event);
/* Items */
this.registerItemModel(Blockbuster.playbackItem, Blockbuster.path("playback"));
this.registerItemModel(Blockbuster.registerItem, Blockbuster.path("register"));
this.registerItemModel(Blockbuster.actorConfigItem, Blockbuster.path("actor_config"));
this.registerItemModel(Blockbuster.gunItem, Blockbuster.path("gun"));
/* Blocks */
this.registerItemModel(Blockbuster.directorBlock, Blockbuster.path("director"));
final ModelResourceLocation modelStatic = new ModelResourceLocation(Blockbuster.path("model_static"), "inventory");
final ModelResourceLocation model = new ModelResourceLocation(Blockbuster.path("model"), "inventory");
/* Register model block's configurable render disable */
ItemMeshDefinition meshDefinition = (stack) -> Blockbuster.modelBlockDisableItemRendering.get() ? modelStatic : model;
TileEntityModelItemStackRenderer teModelItemSR = new TileEntityModelItemStackRenderer();
for (int i = 0; i < Blockbuster.modelBlockItems.length; i++)
{
Item modelBlockItem = Blockbuster.modelBlockItems[i];
ModelBakery.registerItemVariants(modelBlockItem, model, modelStatic);
ModelLoader.setCustomMeshDefinition(modelBlockItem, meshDefinition);
modelBlockItem.setTileEntityItemStackRenderer(teModelItemSR);
}
Blockbuster.gunItem.setTileEntityItemStackRenderer(new TileEntityGunItemStackRenderer());
/* Entities */
this.registerEntityRender(EntityActor.class, new RenderActor.FactoryActor());
//this.registerEntityRender(ExpirableDummyEntity.class, new RenderExpirableDummy.FactoryExpirableDummy());
this.registerEntityRender(EntityGunProjectile.class, new RenderGunProjectile.FactoryGunProjectile());
/* Tile entity */
ClientRegistry.bindTileEntitySpecialRenderer(TileEntityModel.class, modelRenderer = new TileEntityModelRenderer());
ClientRegistry.bindTileEntitySpecialRenderer(TileEntityDirector.class, new TileEntityDirectorRenderer());
this.injectResourcePack(CommonProxy.configFile.getAbsolutePath());
/* Structure morph */
StructureMorph.STRUCTURES = new HashMap<String, StructureRenderer>();
audio = new AudioLibrary(new File(CommonProxy.configFile, "audio"));
skinsFolder = new File(configFile, "skins");
skinsFolder.mkdirs();
}
/**
* Inject actors skin pack into FML's resource packs list
*
* It's done by accessing private FMLClientHandler list (via reflection) and
* appending actor pack.
*
* Thanks to diesieben07 for giving the idea.
*/
@SuppressWarnings("unchecked")
private void injectResourcePack(String path)
{
try
{
Field field = FMLClientHandler.class.getDeclaredField("resourcePackList");
field.setAccessible(true);
List<IResourcePack> packs = (List<IResourcePack>) field.get(FMLClientHandler.instance());
packs.add(actorPack = new ActorsPack());
IResourceManager manager = Minecraft.getMinecraft().getResourceManager();
if (manager instanceof SimpleReloadableResourceManager)
{
((SimpleReloadableResourceManager) manager).reloadResourcePack(actorPack);
}
/* File tree */
BlockbusterJarTree jarTree = new BlockbusterJarTree();
GlobalTree.TREE.register(tree = new BlockbusterTree(this.pack.folders.get(0)));
GlobalTree.TREE.register(jarTree);
FileTree.addBackEntry(jarTree.root);
/* Create steve, alex and fred skins folders */
new File(path + "/models/steve/skins").mkdirs();
new File(path + "/models/alex/skins").mkdirs();
new File(path + "/models/fred/skins").mkdirs();
new File(path + "/models/image/skins").mkdirs();
new File(path + "/models/cape/skins").mkdirs();
new File(path + "/models/eyes/3.0/skins").mkdirs();
}
catch (Exception e)
{
e.printStackTrace();
}
}
/**
* Subscribe all event listeners to EVENT_BUS and attach any client-side
* commands to the ClientCommandRegistry.
*/
@Override
public void load(FMLInitializationEvent event)
{
Minecraft mc = Minecraft.getMinecraft();
/* Register manually models for all chroma blocks */
Item green = Item.getItemFromBlock(Blockbuster.greenBlock);
Item dimGreen = Item.getItemFromBlock(Blockbuster.dimGreenBlock);
ItemModelMesher mesher = mc.getRenderItem().getItemModelMesher();
for (ChromaColor color : ChromaColor.values())
{
ModelResourceLocation location = new ModelResourceLocation("blockbuster:green", "color=" + color.name);
mesher.register(green, color.ordinal(), location);
mesher.register(dimGreen, color.ordinal(), location);
}
/* Initiate rendering overlay and renderer */
recordingOverlay = new GuiRecordingOverlay(mc);
actorRenderer = new RenderCustomActor(mc.getRenderManager(), null, 0);
super.load(event);
/* Event listeners */
MinecraftForge.EVENT_BUS.register(new FrameHandler());
MinecraftForge.EVENT_BUS.register(keys = new KeyboardHandler());
MinecraftForge.EVENT_BUS.register(new RenderingHandler(recordingOverlay));
MinecraftForge.EVENT_BUS.register(new GunMiscRender());
McLib.EVENT_BUS.register(panels = new GuiBlockbusterPanels());
CameraHandler.registerClient();
/* Client commands */
ClientCommandHandler.instance.registerCommand(new CommandModel());
ClientCommandHandler.instance.registerCommand(new CommandItemNBT());
((IReloadableResourceManager) mc.getResourceManager()).registerReloadListener((manager) ->
{
audio.reset();
if (Minecraft.getMinecraft().player != null)
{
StructureMorph.reloadStructures();
}
});
/* Tracker editors */
TrackerRegistry.CLIENT = new HashMap<Class<? extends BaseTracker>, GuiBaseTracker<? extends BaseTracker>>();
TrackerRegistry.CLIENT.put(MorphTracker.class, new GuiMorphTracking(mc));
TrackerRegistry.CLIENT.put(ApertureCamera.class, new GuiBaseTracker<>(mc));
}
protected void registerItemModel(Block block, String path)
{
this.registerItemModel(Item.getItemFromBlock(block), path);
}
protected void registerItemModel(Item item, String path)
{
ModelLoader.setCustomModelResourceLocation(item, 0, new ModelResourceLocation(path, "inventory"));
}
@SuppressWarnings({"unchecked", "rawtypes"})
protected void registerEntityRender(Class eclass, IRenderFactory factory)
{
RenderingRegistry.registerEntityRenderingHandler(eclass, factory);
}
@Override
public boolean isClient()
{
return true;
}
@Override
public ModelHandler getHandler()
{
return new ModelClientHandler();
}
/**
* Client version of get language string.
*/
@Override
public String getLanguageString(String key, String defaultComment)
{
String comment = I18n.format(key);
return comment.equals(key) ? defaultComment : comment;
}
} | 12,220 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
CommonProxy.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/CommonProxy.java | package mchorse.blockbuster;
import mchorse.blockbuster.aperture.CameraHandler;
import mchorse.blockbuster.api.ModelHandler;
import mchorse.blockbuster.api.ModelPack;
import mchorse.blockbuster.capabilities.CapabilityHandler;
import mchorse.blockbuster.capabilities.recording.IRecording;
import mchorse.blockbuster.capabilities.recording.Recording;
import mchorse.blockbuster.capabilities.recording.RecordingStorage;
import mchorse.blockbuster.client.particles.BedrockLibrary;
import mchorse.blockbuster.common.BlockbusterTab;
import mchorse.blockbuster.common.GuiHandler;
import mchorse.blockbuster.common.block.BlockDimGreen;
import mchorse.blockbuster.common.block.BlockDirector;
import mchorse.blockbuster.common.block.BlockGreen;
import mchorse.blockbuster.common.block.BlockModel;
import mchorse.blockbuster.common.entity.EntityActor;
import mchorse.blockbuster.common.entity.EntityGunProjectile;
import mchorse.blockbuster.common.item.ItemActorConfig;
import mchorse.blockbuster.common.item.ItemBlockGreen;
import mchorse.blockbuster.common.item.ItemBlockModel;
import mchorse.blockbuster.common.item.ItemGun;
import mchorse.blockbuster.common.item.ItemPlayback;
import mchorse.blockbuster.common.item.ItemRegister;
import mchorse.blockbuster.common.tileentity.TileEntityDirector;
import mchorse.blockbuster.common.tileentity.TileEntityModel;
import mchorse.blockbuster.events.GunShootHandler;
import mchorse.blockbuster.events.PlayerHandler;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.recording.RecordManager;
import mchorse.blockbuster.recording.capturing.ActionHandler;
import mchorse.blockbuster.recording.capturing.DamageControlManager;
import mchorse.blockbuster.recording.scene.SceneManager;
import mchorse.blockbuster.utils.mclib.BlockbusterResourceTransformer;
import mchorse.blockbuster_pack.BlockbusterFactory;
import mchorse.blockbuster_pack.MetamorphHandler;
import mchorse.blockbuster_pack.trackers.ApertureCamera;
import mchorse.blockbuster_pack.trackers.MorphTracker;
import mchorse.blockbuster_pack.trackers.TrackerRegistry;
import mchorse.mclib.utils.resources.RLUtils;
import mchorse.metamorph.api.MorphManager;
import net.minecraft.block.Block;
import net.minecraft.entity.Entity;
import net.minecraft.item.Item;
import net.minecraft.item.ItemBlock;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.common.capabilities.CapabilityManager;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.common.registry.EntityRegistry;
import net.minecraftforge.fml.common.registry.ForgeRegistries;
import net.minecraftforge.fml.common.registry.GameRegistry;
import java.io.File;
/**
* Common proxy
*
* This class is responsible for registering items, blocks, entities,
* capabilities and event listeners on both sides (that's why it's a common
* proxy).
*/
public class CommonProxy
{
/**
* Record manager for server side
*/
public static RecordManager manager = new RecordManager();
/**
* Damage control manager
*/
public static DamageControlManager damage = new DamageControlManager();
/**
* Remote scene manager
*/
public static SceneManager scenes = new SceneManager();
/**
* Incremented ID for entities
*/
protected int ID = 0;
/**
* Model manager, this class is responsible for managing domain custom
* models for custom actors
*/
public ModelHandler models;
/**
* Model pack
*/
public ModelPack pack;
/**
* Bedrock particle library
*/
public BedrockLibrary particles;
/**
* Blockbuster's morphing factory
*/
public BlockbusterFactory factory;
public static File configFile;
/**
* Registers network messages (and their handlers), items, blocks, director
* block tile entities and actor entity.
*/
public void preLoad(FMLPreInitializationEvent event)
{
Dispatcher.register();
NetworkRegistry.INSTANCE.registerGuiHandler(Blockbuster.instance, new GuiHandler());
/* Configuration */
configFile = new File(event.getModConfigurationDirectory(), "blockbuster");
this.particles = new BedrockLibrary(new File(configFile, "models/particles"));
/* Creative tab */
Blockbuster.blockbusterTab = new BlockbusterTab();
/* Items */
this.registerItem(Blockbuster.registerItem = new ItemRegister());
this.registerItem(Blockbuster.playbackItem = new ItemPlayback());
this.registerItem(Blockbuster.actorConfigItem = new ItemActorConfig());
this.registerItem(Blockbuster.gunItem = new ItemGun());
/* Blocks */
Block director = new BlockDirector();
Block model = new BlockModel();
Block green = new BlockGreen();
Block dimGreen = new BlockDimGreen();
green.setRegistryName("green").setUnlocalizedName("blockbuster.green");
dimGreen.setRegistryName("dim_green").setUnlocalizedName("blockbuster.dim_green");
ForgeRegistries.BLOCKS.register(Blockbuster.directorBlock = director);
ForgeRegistries.ITEMS.register(new ItemBlock(director).setRegistryName(director.getRegistryName()));
ForgeRegistries.BLOCKS.register(Blockbuster.modelBlock = model);
ForgeRegistries.ITEMS.register(Blockbuster.modelBlockItems[0] = new ItemBlock(model).setRegistryName(model.getRegistryName()));
for (int i = 1; i < Blockbuster.modelBlockItems.length; i++)
{
ForgeRegistries.ITEMS.register(Blockbuster.modelBlockItems[i] = new ItemBlockModel(model, i));
}
ForgeRegistries.BLOCKS.register(Blockbuster.greenBlock = green);
ForgeRegistries.ITEMS.register(new ItemBlockGreen(green, true).setRegistryName(green.getRegistryName()));
ForgeRegistries.BLOCKS.register(Blockbuster.dimGreenBlock = dimGreen);
ForgeRegistries.ITEMS.register(new ItemBlockGreen(dimGreen, true).setRegistryName(dimGreen.getRegistryName()));
/* Tile Entities */
GameRegistry.registerTileEntity(TileEntityDirector.class, "blockbuster_director_tile_entity");
GameRegistry.registerTileEntity(TileEntityModel.class, "blockbuster_model_tile_entity");
/* Capabilities */
CapabilityManager.INSTANCE.register(IRecording.class, new RecordingStorage(), Recording::new);
/* Models and morphing */
this.pack = new ModelPack();
this.models = this.getHandler();
this.factory = new BlockbusterFactory();
this.factory.models = this.models;
MorphManager.INSTANCE.factories.add(this.factory);
RLUtils.register(new BlockbusterResourceTransformer());
/* Aperture Modifiers */
CameraHandler.register();
/* Trackers */
TrackerRegistry.registerTracker("aperture_tracker", MorphTracker.class);
TrackerRegistry.registerTracker("apcam", ApertureCamera.class);
}
/**
* This method is responsible for registering Mocap's event handler which
* is responsible for capturing <s>pokemons</s> player actions.
*/
public void load(FMLInitializationEvent event)
{
/* Entities */
this.registerEntityWithEgg(EntityActor.class, new ResourceLocation("blockbuster:actor"), "blockbuster.Actor", 0xffc1ab33, 0xffa08d2b);
EntityRegistry.registerModEntity(new ResourceLocation("blockbuster:projectile"), EntityGunProjectile.class, "blockbuster.GunProjectile", this.ID++, Blockbuster.instance, Blockbuster.actorTrackingRange.get(), 10, true);
/* Event handlers */
MinecraftForge.EVENT_BUS.register(this.models);
MinecraftForge.EVENT_BUS.register(new ActionHandler());
MinecraftForge.EVENT_BUS.register(new GunShootHandler());
MinecraftForge.EVENT_BUS.register(new CapabilityHandler());
MinecraftForge.EVENT_BUS.register(new MetamorphHandler());
MinecraftForge.EVENT_BUS.register(new PlayerHandler());
}
/**
* Post load
*/
public void postLoad(FMLPostInitializationEvent event)
{}
/**
* Load models from given model pack
*
* This method is responsible only for loading domain models (in form of
* data).
*/
public void loadModels(boolean force)
{
this.models.loadModels(this.pack, force);
}
/**
* Register an item with Forge's game registry
*/
protected void registerItem(Item item)
{
ForgeRegistries.ITEMS.register(item);
}
/**
* Thanks to animal bikes mod for this wonderful example! Kids, wanna learn
* how to mod minecraft with forge? That's simple. Find mods for specific
* minecraft version and decompile the .jar files with JD-GUI. Isn't that
* simple?
*
* Or go to minecraft(forge/forum) and ask people to help you #smartass
*/
protected void registerEntityWithEgg(Class<? extends Entity> entity, ResourceLocation id, String name, int primary, int secondary)
{
EntityRegistry.registerModEntity(id, entity, name, this.ID++, Blockbuster.instance, Blockbuster.actorTrackingRange.get(), 3, false, primary, secondary);
}
/**
* Whether physical side is client
*/
public boolean isClient()
{
return false;
}
/**
* Get model handler
*/
public ModelHandler getHandler()
{
return new ModelHandler();
}
/**
* Get language string
*/
public String getLanguageString(String key, String defaultComment)
{
return defaultComment;
}
} | 9,868 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
Blockbuster.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/Blockbuster.java | package mchorse.blockbuster;
import mchorse.blockbuster.aperture.CameraHandler;
import mchorse.blockbuster.commands.CommandAction;
import mchorse.blockbuster.commands.CommandDamage;
import mchorse.blockbuster.commands.CommandModelBlock;
import mchorse.blockbuster.commands.CommandMount;
import mchorse.blockbuster.commands.CommandOnHead;
import mchorse.blockbuster.commands.CommandRecord;
import mchorse.blockbuster.commands.CommandScene;
import mchorse.blockbuster.commands.CommandSpectate;
import mchorse.blockbuster.common.BlockbusterPermissions;
import mchorse.blockbuster.utils.mclib.ValueAudioButtons;
import mchorse.blockbuster.utils.mclib.ValueMainButtons;
import mchorse.blockbuster_pack.morphs.StructureMorph;
import mchorse.mclib.McLib;
import mchorse.mclib.commands.utils.L10n;
import mchorse.mclib.config.ConfigBuilder;
import mchorse.mclib.config.values.ValueBoolean;
import mchorse.mclib.config.values.ValueFloat;
import mchorse.mclib.config.values.ValueInt;
import mchorse.mclib.config.values.ValueString;
import mchorse.mclib.events.RegisterConfigEvent;
import mchorse.mclib.events.RegisterPermissionsEvent;
import mchorse.mclib.permissions.McLibPermissions;
import mchorse.mclib.permissions.PermissionCategory;
import net.minecraft.block.Block;
import net.minecraft.client.resources.I18n;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.item.Item;
import net.minecraftforge.fml.common.Mod;
import net.minecraftforge.fml.common.Mod.EventHandler;
import net.minecraftforge.fml.common.SidedProxy;
import net.minecraftforge.fml.common.event.FMLInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPostInitializationEvent;
import net.minecraftforge.fml.common.event.FMLPreInitializationEvent;
import net.minecraftforge.fml.common.event.FMLServerStartingEvent;
import net.minecraftforge.fml.common.event.FMLServerStoppingEvent;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import net.minecraftforge.server.permission.DefaultPermissionLevel;
import org.apache.logging.log4j.Logger;
/**
* <p>Blockbuster's main entry</p>
*
* <p>
* This mod allows you to create machinimas in minecraft. Blockbuster provides
* you with the most needed tools to create machinimas alone (without bunch of
* complaining body actors).
* </p>
*
* <p>
* This mod is possible thanks to the following code/examples/resources/people:
* </p>
*
* <ul>
* <li>Jabelar's and TGG's minecraft modding tutorials</li>
* <li>AnimalBikes and Mocap mods (EchebKeso)</li>
* <li>MinecraftByExample</li>
* <li>Ernio for helping with camera attributes sync, sharing with his own
* network abstract layer code, and fixing the code so it would work on
* dedicated server</li>
* <li>diesieben07 for giving idea for actor skins</li>
* <li>Choonster for pointing out that processInteract triggers for each
* hand + TestMod3 config example</li>
* <li>Lightwave for porting some of the code to 1.9.4</li>
* <li>NlL5 for a lot of testing, giving lots of feedback and ideas for
* Blockbuster mod</li>
* <li>daipenger for giving me consultation on how to make cameras and
* actors frame-based</li>
* <li>TheImaginationCrafter for suggesting the OBJ feature which made
* Blockbuster super popular and also more customizable (in terms
* of custom models)</li>
* </ul>
*/
@Mod(modid = Blockbuster.MOD_ID, name = Blockbuster.MODNAME, version = Blockbuster.VERSION, dependencies = "after:minema@[%MINEMA%,);before:better_lights@[%BETTERLIGHTS%,);before:aperture@[%APERTURE%,);before:emoticons@[%EMOTICONS%,);required-after:metamorph@[%METAMORPH%,);required-after:mclib@[%MCLIB%,);required-after:forge@[14.23.2.2638,)", updateJSON = "https://raw.githubusercontent.com/mchorse/blockbuster/1.12/version.json")
public class Blockbuster
{
/* Mod info */
public static final String MOD_ID = "blockbuster";
public static final String MODNAME = "Blockbuster";
public static final String VERSION = "%VERSION%";
@SideOnly(Side.CLIENT)
public static String WIKI_URL()
{
return langOrDefault("blockbuster.gui.links.wiki", "https://github.com/mchorse/blockbuster/wiki");
}
@SideOnly(Side.CLIENT)
public static String DISCORD_URL()
{
return langOrDefault("blockbuster.gui.links.discord", "https://discord.gg/qfxrqUF");
}
@SideOnly(Side.CLIENT)
public static String CHANNEL_URL()
{
return langOrDefault("blockbuster.gui.links.channel", "https://www.youtube.com/c/McHorsesMods");
}
@SideOnly(Side.CLIENT)
public static String TWITTER_URL()
{
return langOrDefault("blockbuster.gui.links.twitter", "https://twitter.com/McHorsy");
}
@SideOnly(Side.CLIENT)
public static String TUTORIAL_URL()
{
return langOrDefault("blockbuster.gui.links.tutorial", "https://www.youtube.com/watch?v=qDPEjf2TxAc&list=PLLnllO8nnzE-xmqdymsLpxnXTaAbyIVjM&index=2");
}
@SideOnly(Side.CLIENT)
public static String langOrDefault(String lang, String orDefault)
{
String result = I18n.format(lang);
return result.equals(lang) ? orDefault : result;
}
/* Proxies */
public static final String CLIENT_PROXY = "mchorse.blockbuster.ClientProxy";
public static final String SERVER_PROXY = "mchorse.blockbuster.CommonProxy";
/* Creative tab */
public static CreativeTabs blockbusterTab;
/* Items */
public static Item playbackItem;
public static Item registerItem;
public static Item actorConfigItem;
public static Item[] modelBlockItems = new Item[16];
public static Item gunItem;
/* Blocks */
public static Block directorBlock;
public static Block modelBlock;
public static Block greenBlock;
public static Block dimGreenBlock;
/* Forge stuff */
@Mod.Instance
public static Blockbuster instance;
@SidedProxy(clientSide = CLIENT_PROXY, serverSide = SERVER_PROXY)
public static CommonProxy proxy;
public static Logger LOGGER;
public static L10n l10n = new L10n(MOD_ID);
/* Configuration */
public static ValueBoolean generalFirstTime;
public static ValueBoolean debugPlaybackTicks;
public static ValueBoolean chromaSky;
public static ValueInt chromaSkyColor;
public static ValueBoolean syncedURLTextureDownload;
public static ValueBoolean addUtilityBlocks;
public static ValueFloat bbGunSyncDistance;
public static ValueBoolean modelBlockDisableRendering;
public static ValueBoolean modelBlockDisableItemRendering;
public static ValueBoolean modelBlockRestore;
public static ValueBoolean modelBlockResetOnPlayback;
public static ValueBoolean modelBlockRenderMissingName;
public static ValueBoolean modelBlockRenderDebuginf1;
public static ValueFloat recordingCountdown;
public static ValueInt recordUnloadTime;
public static ValueBoolean recordUnload;
public static ValueInt recordSyncRate;
public static ValueBoolean recordAttackOnSwipe;
public static ValueBoolean recordCommands;
public static ValueString recordChatPrefix;
public static ValueBoolean recordPausePreview;
public static ValueBoolean recordRenderDebugPaths;
public static ValueBoolean sceneSaveUpdate;
public static ValueBoolean actorFallDamage;
public static ValueInt actorTrackingRange;
public static ValueInt actorRenderingRange;
public static ValueBoolean actorAlwaysRender;
public static ValueBoolean actorAlwaysRenderNames;
public static ValueBoolean actorSwishSwipe;
public static ValueBoolean actorFixY;
public static ValueBoolean actorDisableRiding;
public static ValueBoolean actorPlaybackBodyYaw;
public static ValueBoolean damageControl;
public static ValueInt damageControlDistance;
public static ValueBoolean damageControlMessage;
public static ValueString modelFolderPath;
public static ValueBoolean snowstormDepthSorting;
public static ValueBoolean audioWaveformVisible;
public static ValueInt audioWaveformDensity;
public static ValueFloat audioWaveformWidth;
public static ValueInt audioWaveformHeight;
public static ValueBoolean audioWaveformFilename;
public static ValueBoolean audioWaveformTime;
public static ValueBoolean audioSync;
public static ValueInt morphActionOnionSkinColor;
public static ValueInt seqOnionSkinPrev;
public static ValueInt seqOnionSkinPrevColor;
public static ValueInt seqOnionSkinNext;
public static ValueInt seqOnionSkinNextColor;
public static ValueInt seqOnionSkinLoopColor;
public static ValueBoolean immersiveModelBlock;
public static ValueBoolean immersiveRecordEditor;
public static ValueBoolean enableBetterLights;
/**
* "Macro" for getting resource location for Blockbuster mod items,
* entities, blocks, etc.
*/
public static String path(String path)
{
return MOD_ID + ":" + path;
}
/**
* Reloads server side models
*/
public static void reloadServerModels(boolean force)
{
proxy.loadModels(force);
}
@SubscribeEvent
public void onConfigRegister(RegisterConfigEvent event)
{
ConfigBuilder builder = event.createBuilder(MOD_ID);
/* General */
builder.category("general").register(new ValueMainButtons("buttons").clientSide());
generalFirstTime = builder.getBoolean("show_first_time_modal", true);
generalFirstTime.clientSide();
debugPlaybackTicks = builder.getBoolean("debug_playback_ticks", false);
chromaSky = builder.getBoolean("green_screen_sky", false);
chromaSky.clientSide();
chromaSkyColor = builder.getInt("green_screen_sky_color", 0xff00ff00).colorAlpha();
chromaSkyColor.clientSide();
syncedURLTextureDownload = builder.getBoolean("url_skins_sync_download", true);
syncedURLTextureDownload.clientSide();
addUtilityBlocks = builder.getBoolean("add_utility_blocks", false);
addUtilityBlocks.clientSide();
bbGunSyncDistance = builder.getFloat("bb_gun_sync_distance", 0, 0, 100);
bbGunSyncDistance.clientSide();
/* Model block */
modelBlockDisableRendering = builder.category("model_block").getBoolean("model_block_disable_rendering", false);
modelBlockDisableItemRendering = builder.getBoolean("model_block_disable_item_rendering", false);
modelBlockRestore = builder.getBoolean("restore", false);
modelBlockRenderMissingName = builder.getBoolean("model_block_missing_name_rendering", true);
modelBlockRenderDebuginf1 = builder.getBoolean("model_block_debug_rendering_f1", false);
builder.getCategory().markClientSide();
modelBlockResetOnPlayback = builder.getBoolean("reset_on_playback", false);
/* Recording */
recordingCountdown = builder.category("recording").getFloat("recording_countdown", 1.5F, 0, 10);
recordUnloadTime = builder.getInt("record_unload_time", 2400, 600, 72000);
recordUnload = builder.getBoolean("record_unload", true);
recordSyncRate = builder.getInt("record_sync_rate", 6, 1, 30);
recordAttackOnSwipe = builder.getBoolean("record_attack_on_swipe", true);
recordCommands = builder.getBoolean("record_commands", true);
recordChatPrefix = builder.getString("record_chat_prefix", "");
recordPausePreview = builder.getBoolean("record_pause_preview", true);
recordRenderDebugPaths = builder.getBoolean("record_render_debug_paths", true);
/* Scene */
sceneSaveUpdate = builder.category("scenes").getBoolean("save_update", true);
/* Actor */
actorFallDamage = builder.category("actor").getBoolean("actor_fall_damage", true);
actorTrackingRange = builder.getInt("actor_tracking_range", 256, 64, 1024);
actorRenderingRange = builder.getInt("actor_rendering_range", 256, 64, 1024);
actorRenderingRange.clientSide();
actorAlwaysRender = builder.getBoolean("actor_always_render", false);
actorAlwaysRender.clientSide();
actorAlwaysRenderNames = builder.getBoolean("actor_always_render_names", false);
actorAlwaysRenderNames.clientSide();
actorSwishSwipe = builder.getBoolean("actor_swish_swipe", false);
actorFixY = builder.getBoolean("actor_y", false);
actorFixY.clientSide();
actorDisableRiding = builder.getBoolean("actor_disable_riding", false);
actorPlaybackBodyYaw = builder.getBoolean("actor_playback_body_yaw", true);
actorPlaybackBodyYaw.clientSide();
/* Damage control */
damageControl = builder.category("damage_control").getBoolean("damage_control", true);
damageControlDistance = builder.getInt("damage_control_distance", 64, 1, 1024);
damageControlMessage = builder.getBoolean("damage_control_message", true);
/* Model Folder */
modelFolderPath = builder.category("model_folders").getString("path", "");
/* Snowstorm */
snowstormDepthSorting = builder.category("snowstorm").getBoolean("depth_sorting", false);
builder.getCategory().markClientSide();
/* Audio */
builder.category("audio").register(new ValueAudioButtons("buttons"));
audioWaveformVisible = builder.getBoolean("waveform_visible", true);
audioWaveformVisible.clientSide();
audioWaveformDensity = builder.getInt("waveform_density", 20, 10, 100);
audioWaveformDensity.clientSide();
audioWaveformWidth = builder.getFloat("waveform_width", 0.5F, 0F, 1F);
audioWaveformWidth.clientSide();
audioWaveformHeight = builder.getInt("waveform_height", 24, 10, 40);
audioWaveformHeight.clientSide();
audioWaveformFilename = builder.getBoolean("waveform_filename", true);
audioWaveformFilename.clientSide();
audioWaveformTime = builder.getBoolean("waveform_time", true);
audioWaveformTime.clientSide();
audioSync = builder.getBoolean("audio_sync", true);
/* Onion skin */
builder.category("onion_skin");
morphActionOnionSkinColor = builder.getInt("morph_action_color", 0x7FFFFF00).colorAlpha();
seqOnionSkinPrev = builder.getInt("seq_prev", 0);
seqOnionSkinPrevColor = builder.getInt("seq_prev_color", 0xCCFF0000).colorAlpha();
seqOnionSkinNext = builder.getInt("seq_next", 0);
seqOnionSkinNextColor = builder.getInt("seq_next_color", 0xCC00FF00).colorAlpha();
seqOnionSkinLoopColor = builder.getInt("seq_loop_color", 0xC07F7FFF).colorAlpha();
builder.getCategory().invisible().markClientSide();
/* Immersive editor */
builder.category("immersive_editor");
immersiveModelBlock = builder.getBoolean("model_block", true);
immersiveRecordEditor = builder.getBoolean("record_editor", true);
builder.getCategory().markClientSide();
builder.category("better_lights");
enableBetterLights = builder.getBoolean("enable_better_lights", true);
builder.getCategory().markClientSide();
CameraHandler.registerConfig(builder);
}
@SubscribeEvent
public void onPermissionRegister(RegisterPermissionsEvent event)
{
event.registerMod(MOD_ID, DefaultPermissionLevel.OP);
event.registerCategory(new PermissionCategory("model_block"));
event.registerPermission(BlockbusterPermissions.editModelBlock = new PermissionCategory("edit"));
event.endCategory();
event.registerCategory(new PermissionCategory("scenes"));
event.registerPermission(BlockbusterPermissions.openScene = new PermissionCategory("open"));
event.endMod();
}
@EventHandler
public void preLoad(FMLPreInitializationEvent event)
{
LOGGER = event.getModLog();
McLib.EVENT_BUS.register(this);
proxy.preLoad(event);
}
@EventHandler
public void load(FMLInitializationEvent event)
{
proxy.load(event);
}
@EventHandler
public void postLoad(FMLPostInitializationEvent event)
{
proxy.postLoad(event);
}
@EventHandler
public void serverStarting(FMLServerStartingEvent event)
{
StructureMorph.STRUCTURE_CACHE.clear();
proxy.loadModels(false);
/* Register commands */
event.registerServerCommand(new CommandAction());
event.registerServerCommand(new CommandDamage());
event.registerServerCommand(new CommandRecord());
event.registerServerCommand(new CommandOnHead());
event.registerServerCommand(new CommandSpectate());
event.registerServerCommand(new CommandScene());
event.registerServerCommand(new CommandModelBlock());
event.registerServerCommand(new CommandMount());
}
@EventHandler
public void serverStopping(FMLServerStoppingEvent event)
{
CommonProxy.manager.reset();
CommonProxy.damage.reset();
CommonProxy.scenes.reset();
}
}
| 17,139 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
OrientedBB.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/OrientedBB.java | package mchorse.blockbuster.common;
import javax.vecmath.Matrix4f;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Nullable;
import javax.vecmath.Matrix3d;
import javax.vecmath.Vector3d;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import mchorse.blockbuster.client.RenderingHandler;
import mchorse.mclib.utils.Color;
import mchorse.mclib.utils.ColorUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.entity.Entity;
import net.minecraftforge.client.event.RenderWorldLastEvent;
/**
* This is an implentation of an oriented bounding box.
*
* The implementation is specifically designed for the Minecraft Blockbuster
* mod, created by McHorse. Special attributes or functions that are used for
* the Blockbuster mod are for example: initial rotation (which can be
* changed in the GUI of the model editor), limb and anchor offsets.
* Limb offset defines the offset from a selected object part.
* The anchor offset is used for the initial rotation, to rotate around a certain point.
* <p>
* How it works (currently): Inside the render() method of ModelCustomRenderer
* the modelview of the limb is computated and calculates the relative offset to
* the main morph center. This data is passed to the offset attribute in OBB. In
* the applyRotations() method of RenderCustomModel the center of the entity is
* calculated which gets passed to the center variable here in the OBB. Then the
* method buildCorners() is being called, which uses offset and center to
* calculate the real centerpoint of this OBB.
*
* buildCorners() is the most important method, as it computes all the corners
* according to the offsets, rotations and other transformations. This should be
* called at least once somewhere before the collision is tested.
* <p>
* The learning sources that were used for the general concept
* of an OBB implementation:
*
* http://www.cie.bgu.tum.de/publications/bachelorthesis/2014_Engeser.pdf
* https://www.sciencedirect.com/topics/computer-science/oriented-bounding-box
* <p>
* @author Christian F. (known as Chryfi)
* @see https://github.com/Chryfi
* @see https://www.youtube.com/Chryfi
* @see https://twitter.com/Chryfi
*/
public class OrientedBB
{
/** local basis vector x */
private Vector3d w = new Vector3d(1, 0, 0);
/** local basis vector y */
private Vector3d u = new Vector3d(0, 1, 0);
/** local basis vector z */
private Vector3d v = new Vector3d(0, 0, 1);
/** global anchor point - mostly for rendering anchorpoints */
private Vector3d anchorPoint = new Vector3d();
public static Matrix4f modelView = new Matrix4f();
/** scale factor determined by modelView and other scaling factors */
public Matrix3d scale = new Matrix3d();
public Matrix3d rotation = new Matrix3d();
/** initial rotation defined at the beginning of model creation */
public double[] rotation0 = { 0, 0, 0 };
/** global center point (not the anchor) */
public Vector3d center = new Vector3d();
/** half-width */
public double hw;
/** half-height */
public double hu;
/** half-depth */
public double hv;
/** corners - starting from maxXYZ (1,1,1) going clockwise same thing for bottom - starting at maxXminYmaxZ */
public Corner[] corners = new Corner[8];
/** offset from limb (calculated through modelview) */
public Vector3d limbOffset = new Vector3d();
/** anchor of the obb - for initial rotation */
public Vector3d anchorOffset = new Vector3d();
/** offset from main entity */
public Vector3d offset = new Vector3d();
public OrientedBB(@Nullable Vector3d center, @Nullable double[] rotation0, float width, float height, float depth)
{
if (center == null)
{
center = new Vector3d();
}
if (rotation0 == null)
{
rotation0 = new double[3];
}
setup(rotation0, width, height, depth);
this.center.set(center);
}
public OrientedBB()
{
double[] rotation0 = new double[3];
rotation.setIdentity();
setup(rotation0, 0, 0, 0);
buildCorners();
}
public void setup(double[] rotation0, float width, float height, float depth)
{
this.center = new Vector3d();
this.hw = Math.abs(width) / 2;
this.hu = Math.abs(height) / 2;
this.hv = Math.abs(depth) / 2;
this.rotation0 = rotation0;
RenderingHandler.obbsToRender.add(this);
this.rotation.setIdentity();
this.scale.setIdentity();
}
public void render(RenderWorldLastEvent event)
{
int shader = GL11.glGetInteger(GL20.GL_CURRENT_PROGRAM);
if (shader != 0)
{
OpenGlHelper.glUseProgram(0);
}
Color color = ColorUtils.COLOR;
Entity player = Minecraft.getMinecraft().getRenderViewEntity();
double playerX = player.prevPosX + (player.posX - player.prevPosX) * event.getPartialTicks();
double playerY = player.prevPosY + (player.posY - player.prevPosY) * event.getPartialTicks();
double playerZ = player.prevPosZ + (player.posZ - player.prevPosZ) * event.getPartialTicks();
GlStateManager.glLineWidth(3F);
GlStateManager.disableLighting();
GlStateManager.disableTexture2D();
color.set(1F, 1F, 1F, 1F);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder builder = tessellator.getBuffer();
builder.setTranslation(-playerX, -playerY, -playerZ);
builder.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR);
Corner[] startCorners = { this.corners[0], this.corners[2], this.corners[5], this.corners[7] };
for (Corner start : startCorners)
{
for (Corner end : start.connections)
{
builder.pos(start.position.x, start.position.y, start.position.z).color(color.r, color.g, color.b, color.a).endVertex();
builder.pos(end.position.x, end.position.y, end.position.z).color(color.r, color.g, color.b, color.a).endVertex();
}
}
builder.setTranslation(0, 0, 0);
tessellator.draw();
renderAxes(new double[]{-playerX, -playerY, -playerZ}, color, this.anchorPoint, 4, true, false);
GlStateManager.enableTexture2D();
GlStateManager.enableLighting();
GlStateManager.glLineWidth(1F);
if (shader != 0)
{
OpenGlHelper.glUseProgram(shader);
}
}
/**
* This method renders 3 axes. If wanted, it can rotate according to the rotation matrices in the OBB.
*
* @param translation for OpenGL translation (usually player position)
* @param color the color of the axes
* @param center0 the center of the plain Axis
* @param length the half-length of the axis measured in Minecraft pixels
* @param rotate if true the plain axis will be rotated by rotation0 and rotation
* @param depth control GlStateManager depth
*/
public void renderAxes(double[] translation, Color color, Vector3d center0, double length, boolean rotate, boolean depth)
{
GlStateManager.glLineWidth(2F);
GlStateManager.disableLighting();
GlStateManager.disableTexture2D();
if(!depth)
{
GlStateManager.disableDepth();
}
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder builder = tessellator.getBuffer();
builder.setTranslation(translation[0], translation[1], translation[2]);
builder.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR);
Matrix3d rotation0 = anglesToMatrix(this.rotation0[0], this.rotation0[1], this.rotation0[2]);
length /= 32; // 1 <=> 1 pixel => divide by 16 and by 2 as it's half length
Vector3d axisX1 = new Vector3d(length, 0, 0);
Vector3d axisX2 = new Vector3d(0, length, 0);
Vector3d axisX3 = new Vector3d(0, 0, length);
if (rotate)
{
this.rotation.transform(axisX1);
rotation0.transform(axisX1);
this.rotation.transform(axisX2);
rotation0.transform(axisX2);
this.rotation.transform(axisX3);
rotation0.transform(axisX3);
}
builder.pos(center0.x + axisX1.x, center0.y + axisX1.y, center0.z + axisX1.z).color(color.r, color.g, color.b, color.a).endVertex();
builder.pos(center0.x - axisX1.x, center0.y - axisX1.y, center0.z - axisX1.z).color(color.r, color.g, color.b, color.a).endVertex();
builder.pos(center0.x + axisX2.x, center0.y + axisX2.y, center0.z + axisX2.z).color(color.r, color.g, color.b, color.a).endVertex();
builder.pos(center0.x - axisX2.x, center0.y - axisX2.y, center0.z - axisX2.z).color(color.r, color.g, color.b, color.a).endVertex();
builder.pos(center0.x + axisX3.x, center0.y + axisX3.y, center0.z + axisX3.z).color(color.r, color.g, color.b, color.a).endVertex();
builder.pos(center0.x - axisX3.x, center0.y - axisX3.y, center0.z - axisX3.z).color(color.r, color.g, color.b, color.a).endVertex();
builder.setTranslation(0, 0, 0);
tessellator.draw();
if(!depth)
{
GlStateManager.enableDepth();
}
}
/**
* This method calculates all the corners of the OBB according to rotation,
* anchor and other transformation. The corners are saved inside the attribute
* corners.
*/
public void buildCorners()
{
if (!RenderingHandler.obbsToRender.contains(this))
{
RenderingHandler.obbsToRender.add(this);
}
Vector3d width = new Vector3d(this.w);
Vector3d height = new Vector3d(this.u);
Vector3d depth = new Vector3d(this.v);
Matrix3d rotation0 = anglesToMatrix(this.rotation0[0], this.rotation0[1], this.rotation0[2]);
width.scale(this.hw);
height.scale(this.hu);
depth.scale(this.hv);
Vector3d limbOffset0 = new Vector3d(this.limbOffset);
Vector3d anchorOffset0 = new Vector3d(this.anchorOffset);
Vector3d offset0 = new Vector3d(this.offset);
Matrix3d rotscale = new Matrix3d(this.scale);
rotscale.mul(this.rotation);
rotscale.mul(rotation0);
this.rotation.transform(limbOffset0);
this.scale.transform(limbOffset0);
rotscale.transform(anchorOffset0); // not entirely sure if that is correct - testing later in gui
rotscale.transform(width);
rotscale.transform(height);
rotscale.transform(depth);
Vector3d center = new Vector3d(this.center);
center.add(offset0);
this.anchorPoint.set(center);
center.add(anchorOffset0);
center.add(limbOffset0);
/* calculate the corners */
Vector3d pos = new Vector3d(center);
pos.add(width);
pos.add(height);
pos.add(depth);
Corner maxXYZ = new Corner(pos);
this.corners[0] = maxXYZ;
pos.set(center);
pos.sub(width);
pos.add(height);
pos.add(depth);
Corner minXmaxYZ = new Corner(pos);
this.corners[1] = minXmaxYZ;
pos.set(center);
pos.sub(width);
pos.add(height);
pos.sub(depth);
Corner minXmaxYminZ = new Corner(pos);
this.corners[2] = minXmaxYminZ;
pos.set(center);
pos.add(width);
pos.add(height);
pos.sub(depth);
Corner maxXYminZ = new Corner(pos);
this.corners[3] = maxXYminZ;
pos.set(center);
pos.add(width);
pos.sub(height);
pos.add(depth);
Corner maxXminYmaxZ = new Corner(pos);
this.corners[4] = maxXminYmaxZ;
pos.set(center);
pos.sub(width);
pos.sub(height);
pos.add(depth);
Corner minXYmaxZ = new Corner(pos);
this.corners[5] = minXYmaxZ;
pos.set(center);
pos.sub(width);
pos.sub(height);
pos.sub(depth);
Corner minXYZ = new Corner(pos);
this.corners[6] = minXYZ;
pos.set(center);
pos.add(width);
pos.sub(height);
pos.sub(depth);
Corner maxXminYZ = new Corner(pos);
this.corners[7] = maxXminYZ;
/* connect the corners */
maxXYZ.connect(maxXYminZ);
maxXYZ.connect(minXmaxYZ);
maxXYZ.connect(maxXminYmaxZ);
minXmaxYminZ.connect(maxXYminZ);
minXmaxYminZ.connect(minXYZ);
minXmaxYminZ.connect(minXmaxYZ);
minXYmaxZ.connect(maxXminYmaxZ);
minXYmaxZ.connect(minXYZ);
minXYmaxZ.connect(minXmaxYZ);
maxXminYZ.connect(maxXYminZ);
maxXminYZ.connect(minXYZ);
maxXminYZ.connect(maxXminYmaxZ);
}
/**
* This method converts the given angles into one single 3x3 rotation matrix.
* The rotation mode is XYZ
*
* @param angleX rotation around X
* @param angleY rotation around Y (Minecraft height axis)
* @param angleZ rotation around Z
* @return the complete rotation Matrix3d
*/
public static Matrix3d anglesToMatrix(double angleX, double angleY, double angleZ)
{
double radX = Math.toRadians(angleX);
double radY = Math.toRadians(angleY);
double radZ = Math.toRadians(angleZ);
Matrix3d rotation = new Matrix3d();
Matrix3d rot = new Matrix3d();
rotation.setIdentity();
rot.rotX(radX);
rotation.mul(rot);
rot.rotY(radY);
rotation.mul(rot);
rot.rotZ(radZ);
rotation.mul(rot);
return rotation;
}
public OrientedBB clone()
{
OrientedBB d = new OrientedBB();
d.hu = this.hu;
d.hw = this.hw;
d.hv = this.hv;
d.anchorOffset.set(this.anchorOffset);
d.offset.set(this.offset);
d.center.set(this.center);
d.limbOffset.set(this.limbOffset);
d.rotation.set(this.rotation);
d.rotation0 = this.rotation0;
d.scale.set(this.scale);
return d;
}
@Override
public String toString()
{
return "OBB - center: " + this.center;
}
private class Corner
{
/** global position (could it be also local???) */
public Vector3d position;
/**
* List of corners that should be connected with this corner.
* Corners inside this list should also have a connection to this corner
*/
private List<Corner> connections;
public Corner(Vector3d pos)
{
this.position = new Vector3d(pos);
this.connections = new ArrayList<>();
}
/**
* This method connects the given corner with this corner.
* It adds given corner to this connection list and this corner to given corner's connection list.
*
* @param corner
* @return true if connection was established. False means that no connection was made as both lists contain already the corners
*/
public boolean connect(Corner corner)
{
if (!corner.connections.contains(this) && !this.connections.contains(corner))
{
corner.connections.add(this);
this.connections.add(corner);
return true;
}
else if (!corner.connections.contains(this))
{
corner.connections.add(this);
return true;
}
else if (!this.connections.contains(corner))
{
this.connections.add(corner);
return true;
}
return false;
}
/**
* This method removes the given corner and this corner from both connection lists.
*
* @param corner
* @return false if both connection lists don't have the corners.
*/
public boolean disconnect(Corner corner)
{
if (corner.connections.contains(this) && this.connections.contains(corner))
{
corner.connections.remove(this);
this.connections.remove(corner);
return true;
}
else if (corner.connections.contains(this))
{
corner.connections.remove(this);
return true;
}
else if (this.connections.contains(corner))
{
this.connections.remove(corner);
return true;
}
return false;
}
}
}
| 17,907 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BlockbusterPermissions.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/BlockbusterPermissions.java | package mchorse.blockbuster.common;
import mchorse.mclib.permissions.PermissionCategory;
public class BlockbusterPermissions
{
public static PermissionCategory editModelBlock;
public static PermissionCategory openScene;
}
| 232 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BlockbusterTab.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/BlockbusterTab.java | package mchorse.blockbuster.common;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.common.item.ItemBlockGreen;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemMonsterPlacer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.NonNullList;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Blockbuster creative tab
*
* This is a creative tab for Blockbuster mod. What it does, it basically
* provides the icon for this tab and also appends actor egg to this tab (since
* it's really annoying to find actor egg when it's in other tab).
*/
public class BlockbusterTab extends CreativeTabs
{
public BlockbusterTab()
{
super("blockbuster");
}
@Override
@SideOnly(Side.CLIENT)
public ItemStack getTabIconItem()
{
return new ItemStack(Item.getItemFromBlock(Blockbuster.directorBlock));
}
/**
* Display all items and also an actor egg
*/
@Override
@SideOnly(Side.CLIENT)
public void displayAllRelevantItems(NonNullList<ItemStack> items)
{
Item.getItemFromBlock(Blockbuster.greenBlock).getSubItems(this, items);
items.add(ItemStack.EMPTY);
Item.getItemFromBlock(Blockbuster.dimGreenBlock).getSubItems(this, items);
items.add(ItemStack.EMPTY);
for (int i = 0; i < 9; i ++)
{
items.add(ItemStack.EMPTY);
}
for (Item item : Item.REGISTRY)
{
if (item instanceof ItemBlockGreen)
{
continue;
}
item.getSubItems(this, items);
}
/*ItemStack modelBlockStack = new ItemStack(Blockbuster.modelBlockItems[0]);
items.add(modelBlockStack);*/
ItemStack stack = new ItemStack(Items.SPAWN_EGG);
ItemMonsterPlacer.applyEntityIdToItemStack(stack, new ResourceLocation("blockbuster", "actor"));
items.add(stack);
if (Blockbuster.addUtilityBlocks.get())
{
items.add(new ItemStack(Blocks.COMMAND_BLOCK));
items.add(new ItemStack(Blocks.STRUCTURE_BLOCK));
items.add(new ItemStack(Blocks.BARRIER));
}
}
} | 2,384 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GunProps.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/GunProps.java | package mchorse.blockbuster.common;
import mchorse.blockbuster.api.ModelTransform;
import mchorse.blockbuster.common.entity.EntityActor;
import mchorse.blockbuster.common.entity.EntityGunProjectile;
import mchorse.blockbuster.common.item.ItemGun;
import mchorse.metamorph.api.Morph;
import mchorse.metamorph.api.MorphManager;
import mchorse.metamorph.api.MorphUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTBase;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagFloat;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.world.World;
import net.minecraftforge.common.util.Constants.NBT;
import net.minecraftforge.fml.common.FMLCommonHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
/**
* Blockbuster gun properties
* <p>
* This savage fellow is responsible for keeping all of the properties
* that a gun can have. Those are including: gun properties itself,
* projectile that will be spawned from the gun, and projectile impact
* properties.
*/
public class GunProps
{
/* Gun properties */
public AbstractMorph defaultMorph;
public AbstractMorph firingMorph;
public String fireCommand;
public int delay;
public int projectiles;
public float scatterX;
public float scatterY;
public boolean launch;
public boolean useTarget;
public ItemStack ammoStack = ItemStack.EMPTY;
/* Evanechecssss' options */
public boolean staticRecoil;
public float recoilXMin;
public float recoilXMax;
public float recoilYMin;
public float recoilYMax;
public boolean enableArmsShootingPose;
public boolean alwaysArmsShootingPose;
public float shootingOffsetX;
public float shootingOffsetY;
public float shootingOffsetZ;
public AbstractMorph inventoryMorph;
public AbstractMorph crosshairMorph;
public AbstractMorph handsMorph;
public AbstractMorph reloadMorph;
public AbstractMorph zoomOverlayMorph;
public boolean hideCrosshairOnZoom;
public boolean useInventoryMorph;
public boolean hideHandsOnZoom;
public boolean useZoomOverlayMorph;
public float zoomFactor;
public int ammo;
public boolean useReloading;
public long reloadingTime;
public long shotDelay;
public boolean shootWhenHeld;
public String destroyCommand;
public String meleeCommand;
public String reloadCommand;
public String zoomOnCommand;
public String zoomOffCommand;
public float meleeDamage;
public float mouseZoom;
public int durability;
public boolean preventLeftClick;
public boolean preventRightClick;
public boolean preventEntityAttack;
public int storedAmmo;
public long storedReloadingTime;
public long storedShotDelay;
public int storedDurability;
public ItemGun.GunState state = ItemGun.GunState.READY_TO_SHOOT;
/* Projectile properties */
public AbstractMorph projectileMorph;
public String tickCommand;
public int ticking;
public int lifeSpan;
public boolean yaw;
public boolean pitch;
public boolean sequencer;
public boolean random;
public float hitboxX;
public float hitboxY;
public float speed;
public float friction;
public float gravity;
public int fadeIn;
public int fadeOut;
/* Impact properties */
public AbstractMorph impactMorph;
public String impactCommand;
public String impactEntityCommand;
public int impactDelay;
public boolean vanish;
public boolean bounce;
public boolean sticks;
public int hits;
public float damage;
public float knockbackHorizontal;
public float knockbackVertical;
public float bounceFactor;
public String vanishCommand;
public int vanishDelay;
public float penetration;
public boolean ignoreBlocks;
public boolean ignoreEntities;
/* Transforms */
public ModelTransform gunTransform = new ModelTransform();
public ModelTransform gunTransformFirstPerson = new ModelTransform();
public ModelTransform projectileTransform = new ModelTransform();
private int shoot = 0;
private Morph current = new Morph();
private Morph currentHands = new Morph();
private Morph currentInventory = new Morph();
private Morph currentZoomOverlay = new Morph();
public Morph currentCrosshair = new Morph();
private boolean renderLock;
public EntityLivingBase target;
public ItemGun.GunState lastState = ItemGun.GunState.READY_TO_SHOOT;
public GunProps()
{
this.reset();
}
public GunProps(NBTTagCompound tag)
{
this.fromNBT(tag);
}
public void setCurrent(AbstractMorph morph)
{
this.current.setDirect(morph);
}
public void setCurrentZoomOverlay(AbstractMorph morph)
{
this.currentZoomOverlay.setDirect(morph);
}
public void setHandsMorph(AbstractMorph morph)
{
this.currentHands.setDirect(morph);
}
public void setCrosshairMorph(AbstractMorph morph)
{
this.currentCrosshair.setDirect(morph);
}
public void setInventoryMorph(AbstractMorph morph)
{
this.currentInventory.setDirect(morph);
}
public void shot()
{
if (this.delay <= 0)
{
return;
}
this.shoot = this.delay;
this.current.set(MorphUtils.copy(this.firingMorph));
}
@SideOnly(Side.CLIENT)
public void createEntity()
{
this.createEntity(Minecraft.getMinecraft().world);
}
public void createEntity(World world)
{
if (this.target != null)
{
return;
}
this.target = new EntityActor(world);
this.target.onGround = true;
this.target.rotationYaw = this.target.prevRotationYaw = 0;
this.target.rotationYawHead = this.target.prevRotationYawHead = 0;
this.target.rotationPitch = this.target.prevRotationPitch = 0;
}
public EntityLivingBase getEntity(EntityGunProjectile entity)
{
if (this.target != null)
{
this.target.prevPosX = entity.prevPosX;
this.target.prevPosY = entity.prevPosY;
this.target.prevPosZ = entity.prevPosZ;
this.target.posX = entity.posX;
this.target.posY = entity.posY;
this.target.posZ = entity.posZ;
}
return this.target;
}
@SideOnly(Side.CLIENT)
public void update()
{
if (this.target != null)
{
this.target.ticksExisted++;
boolean lastReload = this.lastState == ItemGun.GunState.RELOADING;
boolean currentReload = this.state == ItemGun.GunState.RELOADING;
if (currentReload != lastReload)
{
if (currentReload)
{
this.current.set(this.reloadMorph);
}
else
{
this.current.set(this.defaultMorph);
}
}
this.lastState = this.state;
AbstractMorph morph = this.current.get();
if (morph != null)
{
morph.update(this.target);
}
if (!this.currentCrosshair.isEmpty())
{
this.currentCrosshair.get().update(this.target);
}
if (!this.currentHands.isEmpty())
{
this.currentHands.get().update(this.target);
}
if (!this.currentInventory.isEmpty())
{
this.currentInventory.get().update(this.target);
}
if (!this.currentZoomOverlay.isEmpty())
{
this.currentZoomOverlay.get().update(this.target);
}
}
if (this.shoot > 0)
{
this.shoot--;
if (this.shoot == 0)
{
this.current.set(MorphUtils.copy(this.defaultMorph));
}
}
}
@SideOnly(Side.CLIENT)
public void renderZoomOverlay(EntityLivingBase lastItemHolder, float partialTicks)
{
if (this.renderLock)
{
return;
}
this.renderLock = true;
if (this.target == null)
{
this.createEntity();
}
EntityLivingBase entity = this.useTarget ? target : this.target;
AbstractMorph morph = this.currentZoomOverlay.get();
if (morph != null && entity != null)
{
float rotationYaw = entity.renderYawOffset;
float prevRotationYaw = entity.prevRenderYawOffset;
float rotationYawHead = entity.rotationYawHead;
float prevRotationYawHead = entity.prevRotationYawHead;
entity.rotationYawHead -= entity.renderYawOffset;
entity.prevRotationYawHead -= entity.prevRenderYawOffset;
entity.renderYawOffset = entity.prevRenderYawOffset = 0.0F;
GL11.glPushMatrix();
GL11.glTranslatef(0.5F, 0, 0.5F);
this.setupEntity();
MorphUtils.render(morph, entity, 0, 0, 0, 0, partialTicks);
GL11.glPopMatrix();
entity.renderYawOffset = rotationYaw;
entity.prevRenderYawOffset = prevRotationYaw;
entity.rotationYawHead = rotationYawHead;
entity.prevRotationYawHead = prevRotationYawHead;
}
this.renderLock = false;
}
@SideOnly(Side.CLIENT)
public void render(EntityLivingBase target, float partialTicks, boolean firstPerson)
{
if (this.renderLock)
{
return;
}
this.renderLock = true;
if (this.target == null)
{
this.createEntity();
}
EntityLivingBase entity = this.useTarget ? target : this.target;
AbstractMorph morph = this.current.get();
if (morph != null && entity != null)
{
float rotationYaw = entity.renderYawOffset;
float prevRotationYaw = entity.prevRenderYawOffset;
float rotationYawHead = entity.rotationYawHead;
float prevRotationYawHead = entity.prevRotationYawHead;
entity.rotationYawHead -= entity.renderYawOffset;
entity.prevRotationYawHead -= entity.prevRenderYawOffset;
entity.renderYawOffset = entity.prevRenderYawOffset = 0.0F;
GL11.glPushMatrix();
GL11.glTranslatef(0.5F, 0, 0.5F);
(firstPerson ? this.gunTransformFirstPerson : this.gunTransform).transform();
this.setupEntity();
MorphUtils.render(morph, entity, 0, 0, 0, 0, partialTicks);
GL11.glPopMatrix();
entity.renderYawOffset = rotationYaw;
entity.prevRenderYawOffset = prevRotationYaw;
entity.rotationYawHead = rotationYawHead;
entity.prevRotationYawHead = prevRotationYawHead;
}
this.renderLock = false;
}
@SideOnly(Side.CLIENT)
public void renderInventoryMorph(EntityLivingBase target, float partialTicks)
{
if (this.renderLock)
{
return;
}
this.renderLock = true;
if (this.target == null)
{
this.createEntity();
}
EntityLivingBase entity = this.useTarget ? target : this.target;
AbstractMorph morph = this.currentInventory.get();
if (morph != null && entity != null)
{
GL11.glPushMatrix();
GL11.glTranslatef(0.5F, 0, 0.5F);
GlStateManager.enableDepth();
this.setupEntity();
MorphUtils.render(morph, entity, 0, 0, 0, 0, partialTicks);
GL11.glPopMatrix();
}
this.renderLock = false;
}
@SideOnly(Side.CLIENT)
public void renderHands(EntityLivingBase target, float partialTicks, boolean firstPerson)
{
if (this.renderLock)
{
return;
}
this.renderLock = true;
if (this.target == null)
{
this.createEntity();
}
EntityLivingBase entity = this.useTarget ? target : this.target;
AbstractMorph morph = this.currentHands.get();
if (morph != null && entity != null)
{
float rotationYaw = entity.renderYawOffset;
float prevRotationYaw = entity.prevRenderYawOffset;
float rotationYawHead = entity.rotationYawHead;
float prevRotationYawHead = entity.prevRotationYawHead;
entity.rotationYawHead -= entity.renderYawOffset;
entity.prevRotationYawHead -= entity.prevRenderYawOffset;
entity.renderYawOffset = entity.prevRenderYawOffset = 0.0F;
GL11.glPushMatrix();
GL11.glTranslatef(0.5F, 0, 0.5F);
(firstPerson ? this.gunTransformFirstPerson : this.gunTransform).transform();
this.setupEntity();
MorphUtils.render(morph, entity, 0, 0, 0, 0, partialTicks);
GL11.glPopMatrix();
entity.renderYawOffset = rotationYaw;
entity.prevRenderYawOffset = prevRotationYaw;
entity.rotationYawHead = rotationYawHead;
entity.prevRotationYawHead = prevRotationYawHead;
}
this.renderLock = false;
}
@SideOnly(Side.CLIENT)
private void setupEntity()
{
/* Reset entity's values, just in case some weird shit is going
* to happen in morph's update code*/
this.target.setPositionAndRotation(0, 0, 0, 0, 0);
this.target.setLocationAndAngles(0, 0, 0, 0, 0);
this.target.rotationYawHead = this.target.prevRotationYawHead = 0;
this.target.rotationYaw = this.target.prevRotationYaw = 0;
this.target.rotationPitch = this.target.prevRotationPitch = 0;
this.target.renderYawOffset = this.target.prevRenderYawOffset = 0;
this.target.setVelocity(0, 0, 0);
}
/**
* Reset properties to default values
*/
public void reset()
{
/* Gun properties */
this.defaultMorph = null;
this.handsMorph = null;
this.inventoryMorph = null;
this.reloadMorph = null;
this.crosshairMorph = null;
this.zoomOverlayMorph = null;
this.firingMorph = null;
this.fireCommand = "";
this.delay = 0;
this.projectiles = 1;
/* McHorse: screw organizing this */
this.storedAmmo = 1;
this.reloadingTime = 0;
this.storedShotDelay = 0;
this.shotDelay = 0;
this.ammo = 1;
this.storedReloadingTime = 0;
this.scatterX = this.scatterY = 0F;
this.launch = false;
this.useInventoryMorph = false;
this.useTarget = false;
this.ammoStack = ItemStack.EMPTY;
this.zoomFactor = 0;
this.recoilXMin = 0;
this.shootingOffsetX = 0;
this.mouseZoom = 0.5F;
this.meleeDamage = 0;
this.shootingOffsetY = 0;
this.shootingOffsetZ = 0;
this.staticRecoil = true;
this.recoilXMax = 0;
this.recoilYMin = 0;
this.recoilYMax = 0;
/* Projectile properties */
this.projectileMorph = null;
this.tickCommand = "";
this.zoomOffCommand = "";
this.zoomOnCommand = "";
this.reloadCommand = "";
this.meleeCommand = "";
this.destroyCommand = "";
this.ticking = 0;
this.durability = 0;
this.storedDurability = 0;
this.lifeSpan = 200;
this.yaw = true;
this.useZoomOverlayMorph = false;
this.hideHandsOnZoom = false;
this.hideCrosshairOnZoom = false;
this.enableArmsShootingPose = false;
this.preventRightClick = false;
this.preventLeftClick = false;
this.preventEntityAttack = false;
this.shootWhenHeld = true;
this.alwaysArmsShootingPose = false;
this.pitch = true;
this.sequencer = false;
this.random = false;
this.hitboxX = 0.25F;
this.hitboxY = 0.25F;
this.speed = 1.0F;
this.friction = 0.99F;
this.gravity = 0.03F;
this.fadeIn = this.fadeOut = 10;
/* Impact properties */
this.impactMorph = null;
this.impactCommand = "";
this.impactEntityCommand = "";
this.impactDelay = 0;
this.vanish = true;
this.bounce = false;
this.sticks = false;
this.hits = 1;
this.state = ItemGun.GunState.READY_TO_SHOOT;
this.damage = 0F;
this.knockbackHorizontal = 0F;
this.knockbackVertical = 0F;
this.bounceFactor = 1F;
this.vanishCommand = "";
this.vanishDelay = 0;
this.penetration = 0;
this.ignoreBlocks = false;
this.ignoreEntities = false;
/* Transforms */
this.gunTransform = new ModelTransform();
this.projectileTransform = new ModelTransform();
}
public void fromNBT(NBTTagCompound tag)
{
this.reset();
/* Gun properties */
this.defaultMorph = this.create(tag, "Morph");
this.handsMorph = this.create(tag, "HandsMorph");
this.inventoryMorph = this.create(tag, "InventoryMorph");
this.reloadMorph = this.create(tag, "ReloadMorph");
this.crosshairMorph = this.create(tag, "CrosshairMorph");
this.zoomOverlayMorph = this.create(tag, "ZoomOverlayMorph");
this.firingMorph = this.create(tag, "Fire");
if (tag.hasKey("FireCommand")) this.fireCommand = tag.getString("FireCommand");
if (tag.hasKey("Delay")) this.delay = tag.getInteger("Delay");
if (tag.hasKey("Projectiles")) this.projectiles = tag.getInteger("Projectiles");
if (tag.hasKey("StoredReloadingTime")) this.storedReloadingTime = tag.getInteger("StoredReloadingTime");
if (tag.hasKey("Scatter"))
{
NBTBase scatter = tag.getTag("Scatter");
if (scatter instanceof NBTTagList)
{
NBTTagList list = (NBTTagList) scatter;
if (list.tagCount() >= 2)
{
this.scatterX = list.getFloatAt(0);
this.scatterY = list.getFloatAt(1);
}
}
else
{
/* Old compatibility scatter */
this.scatterX = this.scatterY = tag.getFloat("Scatter");
}
}
if (tag.hasKey("ScatterY")) this.scatterY = tag.getFloat("ScatterY");
if (tag.hasKey("Launch")) this.launch = tag.getBoolean("Launch");
if (tag.hasKey("UseInventoryMorph")) this.useInventoryMorph = tag.getBoolean("UseInventoryMorph");
if (tag.hasKey("UseReloading")) this.useReloading = tag.getBoolean("UseReloading");
if (tag.hasKey("Target")) this.useTarget = tag.getBoolean("Target");
if (tag.hasKey("AmmoStack")) this.ammoStack = new ItemStack(tag.getCompoundTag("AmmoStack"));
/* Projectile properties */
this.projectileMorph = this.create(tag, "Projectile");
if (tag.hasKey("TickCommand")) this.tickCommand = tag.getString("TickCommand");
if (tag.hasKey("MeleeCommand")) this.meleeCommand = tag.getString("MeleeCommand");
if (tag.hasKey("DestroyCommand")) this.destroyCommand = tag.getString("DestroyCommand");
if (tag.hasKey("ReloadCommand")) this.reloadCommand = tag.getString("ReloadCommand");
if (tag.hasKey("ZoomOnCommand")) this.zoomOnCommand = tag.getString("ZoomOnCommand");
if (tag.hasKey("ZoomOffCommand")) this.zoomOffCommand = tag.getString("ZoomOffCommand");
if (tag.hasKey("Ticking")) this.ticking = tag.getInteger("Ticking");
if (tag.hasKey("StoredAmmo")) this.storedAmmo = tag.getInteger("StoredAmmo");
if (tag.hasKey("ReloadingTime")) this.reloadingTime = tag.getInteger("ReloadingTime");
if (tag.hasKey("StoredShotDelay")) this.storedShotDelay = tag.getLong("StoredShotDelay");
if (tag.hasKey("ShotDelay")) this.shotDelay = tag.getLong("ShotDelay");
if (tag.hasKey("Ammo")) this.ammo = tag.getInteger("Ammo");
if (tag.hasKey("LifeSpan")) this.lifeSpan = tag.getInteger("LifeSpan");
if (tag.hasKey("Yaw")) this.yaw = tag.getBoolean("Yaw");
if (tag.hasKey("UseZoomOverlayMorph")) this.useZoomOverlayMorph = tag.getBoolean("UseZoomOverlayMorph");
if (tag.hasKey("HideHandsOnZoom")) this.hideHandsOnZoom = tag.getBoolean("HideHandsOnZoom");
if (tag.hasKey("HideCrosshairOnZoom")) this.hideCrosshairOnZoom = tag.getBoolean("HideCrosshairOnZoom");
if (tag.hasKey("ShootWhenHeld")) this.shootWhenHeld = tag.getBoolean("ShootWhenHeld");
if (tag.hasKey("ArmPose")) this.enableArmsShootingPose = tag.getBoolean("ArmPose");
if (tag.hasKey("ArmPoseAlways")) this.alwaysArmsShootingPose = tag.getBoolean("ArmPoseAlways");
if (tag.hasKey("PreventLeftClick")) this.preventLeftClick = tag.getBoolean("PreventLeftClick");
if (tag.hasKey("PreventRightClick")) this.preventRightClick = tag.getBoolean("PreventRightClick");
if (tag.hasKey("PreventEntityAttack")) this.preventEntityAttack = tag.getBoolean("PreventEntityAttack");
if (tag.hasKey("Pitch")) this.pitch = tag.getBoolean("Pitch");
if (tag.hasKey("Sequencer")) this.sequencer = tag.getBoolean("Sequencer");
if (tag.hasKey("Random")) this.random = tag.getBoolean("Random");
if (tag.hasKey("HX")) this.hitboxX = tag.getFloat("HX");
if (tag.hasKey("HY")) this.hitboxY = tag.getFloat("HY");
if (tag.hasKey("Speed")) this.speed = tag.getFloat("Speed");
if (tag.hasKey("Zoom")) this.zoomFactor = tag.getFloat("Zoom");
if (tag.hasKey("RecoilMinX")) this.recoilXMin = tag.getFloat("RecoilMinX");
if (tag.hasKey("ShootingOffsetX")) this.shootingOffsetX = tag.getFloat("ShootingOffsetX");
if (tag.hasKey("MouseZoom")) this.mouseZoom = tag.getFloat("MouseZoom");
if (tag.hasKey("MeleeDamage")) this.meleeDamage = tag.getFloat("MeleeDamage");
if (tag.hasKey("ShootingOffsetY")) this.shootingOffsetY = tag.getFloat("ShootingOffsetY");
if (tag.hasKey("ShootingOffsetZ")) this.shootingOffsetZ = tag.getFloat("ShootingOffsetZ");
if (tag.hasKey("StaticRecoil")) this.staticRecoil = tag.getBoolean("StaticRecoil");
if (tag.hasKey("RecoilMaxX")) this.recoilXMax = tag.getFloat("RecoilMaxX");
if (tag.hasKey("RecoilMinY")) this.recoilYMin = tag.getFloat("RecoilMinY");
if (tag.hasKey("RecoilMaxY")) this.recoilYMax = tag.getFloat("RecoilMaxY");
if (tag.hasKey("Friction")) this.friction = tag.getFloat("Friction");
if (tag.hasKey("Gravity")) this.gravity = tag.getFloat("Gravity");
if (tag.hasKey("Durability")) this.durability = tag.getInteger("Durability");
if (tag.hasKey("StoredDurability")) this.storedDurability = tag.getInteger("StoredDurability");
if (tag.hasKey("FadeIn")) this.fadeIn = tag.getInteger("FadeIn");
if (tag.hasKey("FadeOut")) this.fadeOut = tag.getInteger("FadeOut");
/* Impact properties */
this.impactMorph = this.create(tag, "Impact");
if (tag.hasKey("ImpactCommand")) this.impactCommand = tag.getString("ImpactCommand");
if (tag.hasKey("ImpactEntityCommand")) this.impactEntityCommand = tag.getString("ImpactEntityCommand");
if (tag.hasKey("ImpactDelay")) this.impactDelay = tag.getInteger("ImpactDelay");
if (tag.hasKey("Vanish")) this.vanish = tag.getBoolean("Vanish");
if (tag.hasKey("Bounce")) this.bounce = tag.getBoolean("Bounce");
if (tag.hasKey("Stick")) this.sticks = tag.getBoolean("Stick");
if (tag.hasKey("Hits")) this.hits = tag.getInteger("Hits");
if (tag.hasKey("State")) this.state = ItemGun.GunState.values()[tag.getInteger("State")];
if (tag.hasKey("Damage")) this.damage = tag.getFloat("Damage");
if (tag.hasKey("KnockbackH")) this.knockbackHorizontal = tag.getFloat("KnockbackH");
if (tag.hasKey("KnockbackV")) this.knockbackVertical = tag.getFloat("KnockbackV");
if (tag.hasKey("BFactor")) this.bounceFactor = tag.getFloat("BFactor");
if (tag.hasKey("VanishCommand")) this.vanishCommand = tag.getString("VanishCommand");
if (tag.hasKey("VDelay")) this.vanishDelay = tag.getInteger("VDelay");
if (tag.hasKey("Penetration")) this.penetration = tag.getFloat("Penetration");
if (tag.hasKey("IBlocks")) this.ignoreBlocks = tag.getBoolean("IBlocks");
if (tag.hasKey("IEntities")) this.ignoreEntities = tag.getBoolean("IEntities");
/* Transforms */
if (tag.hasKey("Gun")) this.gunTransform.fromNBT(tag.getCompoundTag("Gun"));
if (tag.hasKey("GunFirstPerson")) this.gunTransformFirstPerson.fromNBT(tag.getCompoundTag("GunFirstPerson"));
if (tag.hasKey("Transform")) this.projectileTransform.fromNBT(tag.getCompoundTag("Transform"));
if (FMLCommonHandler.instance().getSide() == Side.CLIENT)
{
if (this.state == ItemGun.GunState.RELOADING)
{
/*
* Minecraft has been replacing the client's itemstack, so reloadMorph is never updated,
* and I think BBGun needs a big rewrite to counter Minecraft's own mechanism
*/
this.current.set(MorphUtils.copy(this.reloadMorph));
}
else
{
this.current.set(MorphUtils.copy(this.defaultMorph));
}
this.currentHands.set(MorphUtils.copy(this.handsMorph));
this.currentZoomOverlay.set(MorphUtils.copy(this.zoomOverlayMorph));
this.currentInventory.set(MorphUtils.copy(this.inventoryMorph));
this.currentCrosshair.set(MorphUtils.copy(this.crosshairMorph));
}
}
private AbstractMorph create(NBTTagCompound tag, String key)
{
if (tag.hasKey(key, NBT.TAG_COMPOUND))
{
return MorphManager.INSTANCE.morphFromNBT(tag.getCompoundTag(key));
}
return null;
}
public NBTTagCompound toNBT()
{
NBTTagCompound tag = new NBTTagCompound();
/* Gun properties */
if (this.defaultMorph != null) tag.setTag("Morph", this.to(this.defaultMorph));
if (this.firingMorph != null) tag.setTag("Fire", this.to(this.firingMorph));
if (!this.fireCommand.isEmpty()) tag.setString("FireCommand", this.fireCommand);
if (this.delay != 0) tag.setInteger("Delay", this.delay);
if (this.projectiles != 1) tag.setInteger("Projectiles", this.projectiles);
if (this.scatterX != 0F || this.scatterY != 0F)
{
NBTTagList scatter = new NBTTagList();
scatter.appendTag(new NBTTagFloat(this.scatterX));
scatter.appendTag(new NBTTagFloat(this.scatterY));
tag.setTag("Scatter", scatter);
}
if (this.launch) tag.setBoolean("Launch", this.launch);
if (this.useTarget) tag.setBoolean("Target", this.useTarget);
if (!this.ammoStack.isEmpty()) tag.setTag("AmmoStack", this.ammoStack.writeToNBT(new NBTTagCompound()));
/* Evanechecssss' options */
if (!this.staticRecoil) tag.setBoolean("StaticRecoil", this.staticRecoil);
if (this.recoilXMin != 0) tag.setFloat("RecoilMinX", this.recoilXMin);
if (this.recoilXMax != 0) tag.setFloat("RecoilMaxX", this.recoilXMax);
if (this.recoilYMin != 0) tag.setFloat("RecoilMinY", this.recoilYMin);
if (this.recoilYMax != 0) tag.setFloat("RecoilMaxY", this.recoilYMax);
if (this.enableArmsShootingPose) tag.setBoolean("ArmPose", this.enableArmsShootingPose);
if (this.alwaysArmsShootingPose) tag.setBoolean("ArmPoseAlways", this.alwaysArmsShootingPose);
if (this.shootingOffsetX != 0) tag.setFloat("ShootingOffsetX", this.shootingOffsetX);
if (this.shootingOffsetY != 0) tag.setFloat("ShootingOffsetY", this.shootingOffsetY);
if (this.shootingOffsetZ != 0) tag.setFloat("ShootingOffsetZ", this.shootingOffsetZ);
if (this.inventoryMorph != null) tag.setTag("InventoryMorph", this.to(this.inventoryMorph));
if (this.crosshairMorph != null) tag.setTag("CrosshairMorph", this.to(this.crosshairMorph));
if (this.handsMorph != null) tag.setTag("HandsMorph", this.to(this.handsMorph));
if (this.reloadMorph != null) tag.setTag("ReloadMorph", this.to(this.reloadMorph));
if (this.zoomOverlayMorph != null) tag.setTag("ZoomOverlayMorph", this.to(this.zoomOverlayMorph));
if (this.hideCrosshairOnZoom) tag.setBoolean("HideCrosshairOnZoom", this.hideCrosshairOnZoom);
if (this.useInventoryMorph) tag.setBoolean("UseInventoryMorph", this.useInventoryMorph);
if (this.hideHandsOnZoom) tag.setBoolean("HideHandsOnZoom", this.hideHandsOnZoom);
if (this.useZoomOverlayMorph) tag.setBoolean("UseZoomOverlayMorph", this.useZoomOverlayMorph);
if (this.zoomFactor != 0) tag.setFloat("Zoom", this.zoomFactor);
if (this.ammo != 1) tag.setInteger("Ammo", this.ammo);
if (this.useReloading) tag.setBoolean("UseReloading", this.useReloading);
if (this.reloadingTime != 0) tag.setLong("ReloadingTime", this.reloadingTime);
if (this.shotDelay != 0) tag.setLong("ShotDelay", this.shotDelay);
if (!this.shootWhenHeld) tag.setBoolean("ShootWhenHeld", this.shootWhenHeld);
if (!this.destroyCommand.isEmpty()) tag.setString("DestroyCommand", this.destroyCommand);
if (!this.meleeCommand.isEmpty()) tag.setString("MeleeCommand", this.meleeCommand);
if (!this.reloadCommand.isEmpty()) tag.setString("ReloadCommand", this.reloadCommand);
if (!this.zoomOnCommand.isEmpty()) tag.setString("ZoomOnCommand", this.zoomOnCommand);
if (!this.zoomOffCommand.isEmpty()) tag.setString("ZoomOffCommand", this.zoomOffCommand);
if (this.meleeDamage != 0) tag.setFloat("MeleeDamage", this.meleeDamage);
if (this.mouseZoom != 0.5F) tag.setFloat("MouseZoom", this.mouseZoom);
if (this.durability != 0) tag.setInteger("Durability", this.durability);
if (this.preventLeftClick) tag.setBoolean("PreventLeftClick", this.preventLeftClick);
if (this.preventRightClick) tag.setBoolean("PreventRightClick", this.preventRightClick);
if (this.preventEntityAttack) tag.setBoolean("PreventEntityAttack", this.preventEntityAttack);
if (this.storedAmmo != 1) tag.setInteger("StoredAmmo", this.storedAmmo);
if (this.storedReloadingTime != 0) tag.setLong("StoredReloadingTime", this.storedReloadingTime);
if (this.storedShotDelay != 0) tag.setLong("StoredShotDelay", this.storedShotDelay);
if (this.storedDurability != 0) tag.setInteger("StoredDurability", this.storedDurability);
if (this.state != ItemGun.GunState.READY_TO_SHOOT) tag.setInteger("State", this.state.ordinal());
/* Projectile properties */
if (this.projectileMorph != null) tag.setTag("Projectile", this.to(this.projectileMorph));
if (!this.tickCommand.isEmpty()) tag.setString("TickCommand", this.tickCommand);
if (this.ticking != 0) tag.setInteger("Ticking", this.ticking);
if (this.lifeSpan != 200) tag.setInteger("LifeSpan", this.lifeSpan);
if (!this.yaw) tag.setBoolean("Yaw", this.yaw);
if (!this.pitch) tag.setBoolean("Pitch", this.pitch);
if (this.sequencer) tag.setBoolean("Sequencer", this.sequencer);
if (this.random) tag.setBoolean("Random", this.random);
if (this.hitboxX != 0.25F) tag.setFloat("HX", this.hitboxX);
if (this.hitboxY != 0.25F) tag.setFloat("HY", this.hitboxY);
if (this.speed != 1.0F) tag.setFloat("Speed", this.speed);
if (this.friction != 0.99F) tag.setFloat("Friction", this.friction);
if (this.gravity != 0.03F) tag.setFloat("Gravity", this.gravity);
if (this.fadeIn != 10) tag.setInteger("FadeIn", this.fadeIn);
if (this.fadeOut != 10) tag.setInteger("FadeOut", this.fadeOut);
/* Impact properties */
if (this.impactMorph != null) tag.setTag("Impact", this.to(this.impactMorph));
if (!this.impactCommand.isEmpty()) tag.setString("ImpactCommand", this.impactCommand);
if (!this.impactEntityCommand.isEmpty()) tag.setString("ImpactEntityCommand", this.impactEntityCommand);
if (this.impactDelay != 0) tag.setInteger("ImpactDelay", this.impactDelay);
if (!this.vanish) tag.setBoolean("Vanish", this.vanish);
if (this.bounce) tag.setBoolean("Bounce", this.bounce);
if (this.sticks) tag.setBoolean("Stick", this.sticks);
if (this.hits != 1) tag.setInteger("Hits", this.hits);
if (this.damage != 0) tag.setFloat("Damage", this.damage);
if (this.knockbackHorizontal != 0F) tag.setFloat("KnockbackH", this.knockbackHorizontal);
if (this.knockbackVertical != 0F) tag.setFloat("KnockbackV", this.knockbackVertical);
if (this.bounceFactor != 1F) tag.setFloat("BFactor", this.bounceFactor);
if (!this.vanishCommand.isEmpty()) tag.setString("VanishCommand", this.vanishCommand);
if (this.vanishDelay != 0) tag.setInteger("VDelay", this.vanishDelay);
if (this.penetration != 0) tag.setFloat("Penetration", this.penetration);
if (this.ignoreBlocks) tag.setBoolean("IBlocks", this.ignoreBlocks);
if (this.ignoreEntities) tag.setBoolean("IEntities", this.ignoreEntities);
/* Transforms */
if (!this.gunTransform.isDefault()) tag.setTag("Gun", this.gunTransform.toNBT());
if (!this.gunTransformFirstPerson.isDefault()) tag.setTag("GunFirstPerson", this.gunTransformFirstPerson.toNBT());
if (!this.projectileTransform.isDefault()) tag.setTag("Transform", this.projectileTransform.toNBT());
return tag;
}
private NBTTagCompound to(AbstractMorph morph)
{
NBTTagCompound tag = new NBTTagCompound();
morph.toNBT(tag);
return tag;
}
} | 34,407 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiHandler.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/GuiHandler.java | package mchorse.blockbuster.common;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.aperture.CameraHandler;
import mchorse.blockbuster.aperture.gui.GuiPlayback;
import mchorse.blockbuster.client.gui.GuiActor;
import mchorse.blockbuster.client.gui.dashboard.GuiBlockbusterPanels;
import mchorse.blockbuster.common.entity.EntityActor;
import mchorse.blockbuster.common.tileentity.TileEntityModel;
import mchorse.mclib.client.gui.mclib.GuiDashboard;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.Optional.Method;
import net.minecraftforge.fml.common.network.IGuiHandler;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Gui handler class
*
* This class is responsible for opening GUIs.
*/
public class GuiHandler implements IGuiHandler
{
/* GUI ids */
public static final int PLAYBACK = 0;
public static final int ACTOR = 1;
public static final int MODEL_BLOCK = 3;
/**
* Shortcut for {@link EntityPlayer#openGui(Object, int, World, int, int, int)}
*/
public static void open(EntityPlayer player, int ID, int x, int y, int z)
{
player.openGui(Blockbuster.instance, ID, player.world, x, y, z);
}
/**
* There's two types of GUI are available right now:
*
* - Actor configuration GUI
* - Director block management GUIs
* - Playback button GUI
*
* IGuiHandler is used to centralize GUI invocations
*/
@Override
@SideOnly(Side.CLIENT)
public Object getClientGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
{
Entity entity = world.getEntityByID(x);
if (ID == PLAYBACK && CameraHandler.isApertureLoaded())
{
return this.getPlayback();
}
else if (ID == ACTOR && entity instanceof EntityActor)
{
return new GuiActor(Minecraft.getMinecraft(), (EntityActor) entity);
}
else if (ID == MODEL_BLOCK)
{
TileEntityModel model = (TileEntityModel) world.getTileEntity(new BlockPos(x, y, z));
GuiDashboard dashboard = GuiDashboard.get();
GuiBlockbusterPanels panels = ClientProxy.panels;
dashboard.panels.setPanel(panels.modelPanel);
panels.modelPanel.openModelBlock(model);
return dashboard;
}
return null;
}
/**
* Returns created playback GUI
*
* The reason behind creating it here, instead of in the
* getClientGuiElement method, is because it may get Aperture's classes get
* referenced which might cause I crash.
*
* So instead, I'm creating it here, so Method annotation would strip away
* reference to {@link GuiPlayback} (which in turn will reference
* Aperture's classes).
*/
@Method(modid = "aperture")
private Object getPlayback()
{
return new GuiPlayback();
}
/**
* This method is empty, because there's no need for this method to be
* filled with code. This mod doesn't seem to provide any interaction with
* Containers.
*/
@Override
public Object getServerGuiElement(int ID, EntityPlayer player, World world, int x, int y, int z)
{
return null;
}
} | 3,509 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
TileEntityModelSettings.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/tileentity/TileEntityModelSettings.java | package mchorse.blockbuster.common.tileentity;
import io.netty.buffer.ByteBuf;
import mchorse.mclib.client.gui.framework.elements.input.GuiTransformations.TransformOrientation;
import mchorse.mclib.config.values.ValueBoolean;
import mchorse.mclib.config.values.ValueFloat;
import mchorse.mclib.config.values.ValueInt;
import mchorse.mclib.config.values.ValueItemSlots;
import mchorse.mclib.config.values.ValueRotationOrder;
import mchorse.mclib.network.IByteBufSerializable;
import mchorse.mclib.network.INBTSerializable;
import mchorse.mclib.utils.ICopy;
import mchorse.mclib.utils.ITransformationObject;
import mchorse.mclib.utils.MatrixUtils;
import mchorse.mclib.utils.ValueSerializer;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector4f;
public class TileEntityModelSettings implements IByteBufSerializable, INBTSerializable, ITransformationObject, ICopy<TileEntityModelSettings>
{
private final ValueBoolean enabled = new ValueBoolean("enabled", true);
private final ValueInt lightValue = new ValueInt("lightValue");
private final ValueBoolean shadow = new ValueBoolean("shadow", true);
private final ValueBoolean global = new ValueBoolean("global");
private final ValueBoolean excludeResetPlayback = new ValueBoolean("excludeResetPlayback");
private final ValueBoolean renderLast = new ValueBoolean("renderLast");
private final ValueBoolean renderAlways = new ValueBoolean("renderAlways");
private final ValueBoolean enableBlockHitbox = new ValueBoolean("enableBlockHitbox");
private final ValueItemSlots slots = new ValueItemSlots("slots", 6);
/* Entity rotations */
private final ValueFloat rotateYawHead = new ValueFloat("rotateYawHead");
private final ValueFloat rotatePitch = new ValueFloat("rotatePitch");
private final ValueFloat rotateBody = new ValueFloat("rotateBody");
/* Translation */
private final ValueFloat x = new ValueFloat("x");
private final ValueFloat y = new ValueFloat("y");
private final ValueFloat z = new ValueFloat("z");
/* Rotation */
private final ValueRotationOrder order = new ValueRotationOrder("order", MatrixUtils.RotationOrder.ZYX);
private final ValueFloat rx = new ValueFloat("rx");
private final ValueFloat ry = new ValueFloat("ry");
private final ValueFloat rz = new ValueFloat("rz");
/* Scale */
private final ValueBoolean uniform = new ValueBoolean("uniform");
private final ValueFloat sx = new ValueFloat("sx",1);
private final ValueFloat sy = new ValueFloat("sy",1);
private final ValueFloat sz = new ValueFloat("sz",1);
private ValueSerializer serializer = new ValueSerializer();
public TileEntityModelSettings()
{
this.serializer.registerValue(this.enabled).serializeNBT("Enabled");
this.serializer.registerValue(this.order).serializeNBT("Order");
this.serializer.registerValue(this.rotateYawHead).serializeNBT("Yaw");
this.serializer.registerValue(this.rotatePitch).serializeNBT("Pitch");
this.serializer.registerValue(this.rotateBody).serializeNBT("Body");
this.serializer.registerValue(this.x).serializeNBT("ShiftX");
this.serializer.registerValue(this.y).serializeNBT("ShiftY");
this.serializer.registerValue(this.z).serializeNBT("ShiftZ");
this.serializer.registerValue(this.rx).serializeNBT("RotateX");
this.serializer.registerValue(this.ry).serializeNBT("RotateY");
this.serializer.registerValue(this.rz).serializeNBT("RotateZ");
this.serializer.registerValue(this.uniform).serializeNBT("Scale");
this.serializer.registerValue(this.sx).serializeNBT("ScaleX");
this.serializer.registerValue(this.sy).serializeNBT("ScaleY");
this.serializer.registerValue(this.sz).serializeNBT("ScaleZ");
this.serializer.registerValue(this.shadow).serializeNBT("Shadow");
this.serializer.registerValue(this.global).serializeNBT("Global");
this.serializer.registerValue(this.slots).serializeNBT("Items");
this.serializer.registerValue(this.lightValue).serializeNBT("LightValue");
this.serializer.registerValue(this.renderLast).serializeNBT("RenderLast");
this.serializer.registerValue(this.renderAlways).serializeNBT("RenderAlways");
this.serializer.registerValue(this.enableBlockHitbox).serializeNBT("Hitbox");
this.serializer.registerValue(this.excludeResetPlayback).serializeNBT("ExcludeResetPlayback");
}
public boolean isBlockHitbox()
{
return this.enableBlockHitbox.get();
}
public void setEnableBlockHitbox(boolean enableBlockHitbox)
{
this.enableBlockHitbox.set(enableBlockHitbox);
}
public int getLightValue()
{
return this.lightValue.get();
}
public void setLightValue(int lightValue)
{
this.lightValue.set(lightValue);
}
public boolean isExcludeResetPlayback()
{
return this.excludeResetPlayback.get();
}
public void setExcludeResetPlayback(boolean excludeResetPlayback)
{
this.excludeResetPlayback.set(excludeResetPlayback);
}
public boolean isRenderLast()
{
return this.renderLast.get();
}
public void setRenderLast(boolean renderLast)
{
this.renderLast.set(renderLast);
}
public boolean isRenderAlways()
{
return this.renderAlways.get();
}
public void setRenderAlways(boolean renderAlways)
{
this.renderAlways.set(renderAlways);
}
public ItemStack[] getSlots()
{
return slots.get();
}
public void setSlots(ItemStack[] slots)
{
this.slots.set(slots);
}
/**
* Calls {@link ValueItemSlots#set(ItemStack, int)}, which copies the provided ItemStack
* @param item
* @param slot
*/
public void setSlot(ItemStack item, int slot)
{
this.slots.set(item, slot);
}
public MatrixUtils.RotationOrder getOrder()
{
return this.order.get();
}
public void setOrder(MatrixUtils.RotationOrder order)
{
this.order.set(order);
}
public float getRotateYawHead()
{
return this.rotateYawHead.get();
}
public void setRotateYawHead(float rotateYawHead)
{
this.rotateYawHead.set(rotateYawHead);
}
public float getRotatePitch()
{
return rotatePitch.get();
}
public void setRotatePitch(float rotatePitch)
{
this.rotatePitch.set(rotatePitch);
}
public float getRotateBody()
{
return rotateBody.get();
}
public void setRotateBody(float rotateBody)
{
this.rotateBody.set(rotateBody);
}
public float getX()
{
return x.get();
}
public void setX(float x)
{
this.x.set(x);
}
public float getY()
{
return this.y.get();
}
public void setY(float y)
{
this.y.set(y);
}
public float getZ()
{
return this.z.get();
}
public void setZ(float z)
{
this.z.set(z);
}
/**
* Add a translation on top of this translation.
* @param x
* @param y
* @param z
*/
@Override
public void addTranslation(double x, double y, double z, TransformOrientation orientation)
{
Vector4f trans = new Vector4f((float) x, (float) y, (float) z, 1F);
if (orientation == TransformOrientation.LOCAL)
{
float rotX = (float) Math.toRadians(this.getRx());
float rotY = (float) Math.toRadians(this.getRy());
float rotZ = (float) Math.toRadians(this.getRz());
MatrixUtils.getRotationMatrix(rotX, rotY, rotZ, this.order.get()).transform(trans);
}
this.x.set(this.x.get() + trans.x);
this.y.set(this.y.get() + trans.y);
this.z.set(this.z.get() + trans.z);
}
public float getRx()
{
return this.rx.get();
}
public void setRx(float rx)
{
this.rx.set(rx);
}
public float getRy()
{
return this.ry.get();
}
public void setRy(float ry)
{
this.ry.set(ry);
}
public float getRz()
{
return this.rz.get();
}
public void setRz(float rz)
{
this.rz.set(rz);
}
public boolean isUniform()
{
return this.uniform.get();
}
public void setUniform(boolean uniform)
{
this.uniform.set(uniform);
}
public float getSx()
{
return this.sx.get();
}
public void setSx(float sx)
{
this.sx.set(sx);
}
public float getSy()
{
return this.sy.get();
}
public void setSy(float sy)
{
this.sy.set(sy);
}
public float getSz()
{
return this.sz.get();
}
public void setSz(float sz)
{
this.sz.set(sz);
}
public boolean isShadow()
{
return this.shadow.get();
}
public void setShadow(boolean shadow)
{
this.shadow.set(shadow);
}
public boolean isGlobal()
{
return this.global.get();
}
public void setGlobal(boolean global)
{
this.global.set(global);
}
public boolean isEnabled()
{
return this.enabled.get();
}
public void setEnabled(boolean enabled)
{
this.enabled.set(enabled);
}
@Override
public TileEntityModelSettings copy()
{
TileEntityModelSettings copy = new TileEntityModelSettings();
copy.copy(this);
return copy;
}
@Override
public void copy(TileEntityModelSettings settings)
{
this.serializer.copyValues(settings.serializer);
}
@Override
public void fromBytes(ByteBuf byteBuf)
{
this.serializer.fromBytes(byteBuf);
}
@Override
public void toBytes(ByteBuf byteBuf)
{
this.serializer.toBytes(byteBuf);
}
@Override
public void fromNBT(NBTTagCompound nbtTagCompound)
{
this.serializer.fromNBT(nbtTagCompound);
}
@Override
public NBTTagCompound toNBT(NBTTagCompound nbtTagCompound)
{
return this.serializer.toNBT(nbtTagCompound);
}
}
| 10,303 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
TileEntityDirector.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/tileentity/TileEntityDirector.java | package mchorse.blockbuster.common.tileentity;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.CommonProxy;
import mchorse.blockbuster.recording.scene.Scene;
import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.tileentity.TileEntityFlowerPot;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Director tile entity
*
* Goodbye director blocks...
*/
public class TileEntityDirector extends TileEntityFlowerPot
{
@Override
public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate)
{
return oldState.getBlock() != newSate.getBlock();
}
/* Read/write this TE to disk */
@Override
public void readFromNBT(NBTTagCompound compound)
{
super.readFromNBT(compound);
/* At least the data wouldn't be lost */
if (compound.hasKey("Actors"))
{
Scene scene = new Scene();
scene.fromNBT(compound);
scene.setId("director_block_" + this.pos.getX() + "_" + this.pos.getY() + "_" + this.pos.getZ());
try
{
CommonProxy.scenes.save(scene.getId(), scene);
}
catch (Exception e)
{}
}
}
@Override
@SideOnly(Side.CLIENT)
public AxisAlignedBB getRenderBoundingBox()
{
return TileEntity.INFINITE_EXTENT_AABB;
}
@Override
@SideOnly(Side.CLIENT)
public double getMaxRenderDistanceSquared()
{
float range = Blockbuster.actorRenderingRange.get();
return range * range;
}
} | 1,847 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
TileEntityModel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/tileentity/TileEntityModel.java | package mchorse.blockbuster.common.tileentity;
import io.netty.buffer.ByteBuf;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.client.RenderingHandler;
import mchorse.blockbuster.client.render.IRenderLast;
import mchorse.blockbuster.common.entity.EntityActor;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.PacketModifyModelBlock;
import mchorse.blockbuster.recording.scene.Scene;
import mchorse.mclib.network.IByteBufSerializable;
import mchorse.metamorph.api.Morph;
import mchorse.metamorph.api.MorphManager;
import mchorse.metamorph.api.MorphUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import net.minecraft.block.state.IBlockState;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.network.NetworkManager;
import net.minecraft.network.play.server.SPacketUpdateTileEntity;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.ITickable;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.NetworkRegistry;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.vecmath.Vector3d;
/**
* Model tile entity
*
* This little guy is responsible for storing visual data about model's
* rendering.
*/
public class TileEntityModel extends TileEntity implements ITickable, IRenderLast, IByteBufSerializable
{
private static AbstractMorph DEFAULT_MORPH;
public Morph morph = new Morph();
public EntityLivingBase entity;
private long lastModelUpdate;
private TileEntityModelSettings settings = new TileEntityModelSettings();
static
{
NBTTagCompound tag = new NBTTagCompound();
tag.setString("Name", "blockbuster.fred");
DEFAULT_MORPH = MorphManager.INSTANCE.morphFromNBT(tag);
}
public TileEntityModel()
{
this.morph.setDirect(MorphUtils.copy(getDefaultMorph()));
this.lastModelUpdate = Scene.lastUpdate;
}
public TileEntityModel(float yaw)
{
this();
this.settings.setRy(yaw);
}
/**
* @return reference to this {@link #settings} object.
*/
public TileEntityModelSettings getSettings()
{
return this.settings;
}
public static AbstractMorph getDefaultMorph()
{
return DEFAULT_MORPH;
}
@Override
public Vector3d getRenderLastPos()
{
BlockPos blockPos = this.getPos();
return new Vector3d(blockPos.getX() + this.settings.getX(),
blockPos.getY() + this.settings.getY(),
blockPos.getZ() + this.settings.getZ());
}
@Override
public boolean shouldRenderInPass(int pass)
{
return super.shouldRenderInPass(pass) && !(this.settings.isRenderLast() && RenderingHandler.addRenderLast(this));
}
public void setMorph(AbstractMorph morph)
{
this.morph.set(morph);
this.markDirty();
}
public void createEntity(World world)
{
if (world == null)
{
return;
}
this.entity = new EntityActor(world);
this.entity.onGround = true;
this.updateEntity();
}
public void updateEntity()
{
if (this.entity == null)
{
return;
}
for (int i = 0; i < this.settings.getSlots().length; i++)
{
this.entity.setItemStackToSlot(EntityEquipmentSlot.values()[i], this.settings.getSlots()[i]);
}
this.entity.posX = this.pos.getX() + this.settings.getX() + 0.5;
this.entity.posY = this.pos.getY() + this.settings.getY();
this.entity.posZ = this.pos.getZ() + this.settings.getZ() + 0.5;
}
@Override
public void update()
{
if (this.entity == null)
{
this.createEntity(this.world);
}
if (this.entity != null && this.settings.isEnabled())
{
this.entity.ticksExisted++;
this.entity.posX = this.pos.getX() + this.settings.getX() + 0.5;
this.entity.posY = this.pos.getY() + this.settings.getY();
this.entity.posZ = this.pos.getZ() + this.settings.getZ() + 0.5;
if (!this.morph.isEmpty())
{
this.morph.get().update(this.entity);
}
}
if (this.lastModelUpdate < Scene.lastUpdate && !this.settings.isExcludeResetPlayback())
{
if (this.world != null && !this.world.isRemote)
{
BlockPos pos = this.pos;
PacketModifyModelBlock message = new PacketModifyModelBlock(pos, this);
Dispatcher.DISPATCHER.get().sendToDimension(message, this.world.provider.getDimension());
}
this.lastModelUpdate = Scene.lastUpdate;
}
}
/**
* Infinite extend AABB allows to avoid frustum culling which can be
* used for some interesting things (like placing a whole OBJ level
* in the game)
*/
@Override
@SideOnly(Side.CLIENT)
public AxisAlignedBB getRenderBoundingBox()
{
return TileEntity.INFINITE_EXTENT_AABB;
}
@Override
@SideOnly(Side.CLIENT)
public double getMaxRenderDistanceSquared()
{
float range = Blockbuster.actorRenderingRange.get();
return range * range;
}
/**
* Dont refresh tile entity when blockstate changes - only when block changes
* @param world
* @param pos
* @param oldState
* @param newSate
* @return
*/
@Override
public boolean shouldRefresh(World world, BlockPos pos, IBlockState oldState, IBlockState newSate)
{
return (oldState.getBlock() != newSate.getBlock());
}
/* NBT methods */
/**
* That's important too for
* {@link #onDataPacket(NetworkManager, SPacketUpdateTileEntity)} to
* fix the flower pot thing.
*/
@Override
public NBTTagCompound getUpdateTag()
{
return this.writeToNBT(new NBTTagCompound());
}
@Override
public SPacketUpdateTileEntity getUpdatePacket()
{
return new SPacketUpdateTileEntity(this.pos, this.getBlockMetadata(), this.getUpdateTag());
}
/**
* This method fixes the old thing with flower pot thanks to asie!
*
* @link https://www.reddit.com/r/feedthebeast/comments/b7h6fb/modders_what_embarrassingdirty_trick_did_you_do/ejtdydo/?context=3
*/
@Override
public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt)
{
this.readFromNBT(pkt.getNbtCompound());
}
public void copyData(TileEntityModel model, boolean merge)
{
this.settings.copy(model.settings);
if (merge)
{
this.morph.set(model.morph.get());
}
else
{
this.morph.setDirect(model.morph.get());
}
this.updateEntity();
this.markDirty();
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound)
{
this.settings.toNBT(compound);
if (!this.morph.isEmpty())
{
compound.setTag("Morph", this.morph.toNBT());
}
return super.writeToNBT(compound);
}
@Override
public void readFromNBT(NBTTagCompound compound)
{
super.readFromNBT(compound);
this.settings.fromNBT(compound);
if (compound.hasKey("Morph", 10))
{
this.morph.setDirect(MorphManager.INSTANCE.morphFromNBT(compound.getCompoundTag("Morph")));
}
}
public void fromBytes(ByteBuf buf)
{
this.settings.fromBytes(buf);
this.morph.setDirect(MorphUtils.morphFromBuf(buf));
}
public void toBytes(ByteBuf buf)
{
this.settings.toBytes(buf);
MorphUtils.morphToBuf(buf, this.morph.get());
}
} | 8,056 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
EntityActor.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/entity/EntityActor.java | package mchorse.blockbuster.common.entity;
import com.google.common.collect.Queues;
import com.mojang.authlib.GameProfile;
import io.netty.buffer.ByteBuf;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.client.render.IRenderLast;
import mchorse.blockbuster.common.GuiHandler;
import mchorse.blockbuster.common.item.ItemActorConfig;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.PacketModifyActor;
import mchorse.blockbuster.network.common.recording.PacketRequestFrames;
import mchorse.blockbuster.network.common.recording.PacketSyncTick;
import mchorse.blockbuster.network.common.recording.actions.PacketRequestAction;
import mchorse.blockbuster.recording.RecordPlayer;
import mchorse.blockbuster.recording.data.Frame;
import mchorse.blockbuster.recording.data.Mode;
import mchorse.blockbuster.recording.data.Record;
import mchorse.blockbuster.recording.data.Record.MorphType;
import mchorse.blockbuster.recording.scene.Replay;
import mchorse.mclib.utils.Interpolations;
import mchorse.metamorph.api.Morph;
import mchorse.metamorph.api.MorphManager;
import mchorse.metamorph.api.MorphUtils;
import mchorse.metamorph.api.models.IMorphProvider;
import mchorse.metamorph.api.morphs.AbstractMorph;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityBodyHelper;
import net.minecraft.entity.EntityCreature;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.IEntityLivingData;
import net.minecraft.entity.MoverType;
import net.minecraft.entity.item.EntityItem;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.ContainerChest;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.inventory.IInventory;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.DifficultyInstance;
import net.minecraft.world.IInteractionObject;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.Objects;
import java.util.Queue;
import javax.annotation.Nullable;
import javax.vecmath.Vector3d;
/**
* Actor entity class
*
* Actor entity class is responsible for recording player's actions and execute
* them. I'm also thinking about giving them controllable AI settings so they
* could be used without recording (like during the battles between two or more
* actors).
*
* Also, it would be cool to add something like simple crowd control for bigger
* scenes (like one from Van Helsing in beginning with big crowd with torches,
* fire and stuff).
*/
public class EntityActor extends EntityCreature implements IEntityAdditionalSpawnData, IMorphProvider, IRenderLast
{
/**
* This field is needed to make actors invisible. This is helpful for
* scenes with different characters, which isn't needed to be seen.
*/
public boolean invisible = false;
/**
* Fake player used in some of methods like onBlockActivated to avoid
* NullPointerException (and some math like the direction in which to open
* the fence or something).
*/
public EntityFakePlayer fakePlayer;
/**
* In Soviet Russia, playback plays you
*/
public RecordPlayer playback;
/**
* Metamorph's morph for this actor
*/
public Morph morph = new Morph();
/* Elytra interpolated animated properties */
public float rotateElytraX = 0.0F;
public float rotateElytraY = 0.0F;
public float rotateElytraZ = 0.0F;
/**
* Whether this actor is mounted (used for hacking riding pose for
* 3rd party sit-able mods, such as CFM or Quark)
*/
public boolean isMounted;
/**
* Whether this actor was attached to director block
*/
public boolean wasAttached;
/**
* Whether the control of playback should be manual
*/
public boolean manual = false;
public int pauseOffset = -1;
public AbstractMorph pausePreviousMorph;
public int pausePreviousOffset = -1;
public boolean forceMorph = false;
public float prevRoll;
public float roll;
public boolean renderLast;
public boolean enableBurning;
public Queue<PacketModifyActor> modify = Queues.<PacketModifyActor>newArrayDeque();
public EntityActor(World worldIn)
{
super(worldIn);
this.fakePlayer = new EntityFakePlayer(worldIn, this, new GameProfile(null, "xXx_Fake_Player_420_xXx"));
this.fakePlayer.capabilities.isCreativeMode = true;
}
@Override
public AbstractMorph getMorph()
{
return this.morph.get();
}
@Override
public Vector3d getRenderLastPos()
{
float partialTicks = Minecraft.getMinecraft().getRenderPartialTicks();
return new Vector3d(Interpolations.lerp(this.prevPosX, this.posX, partialTicks), Interpolations.lerp(this.prevPosY, this.posY, partialTicks), Interpolations.lerp(this.prevPosZ, this.posZ, partialTicks));
}
@Override
public boolean isBurning()
{
return this.enableBurning && super.isBurning();
}
/**
* Check whether this actor is playing
*/
public boolean isPlaying()
{
return this.playback != null && this.playback.playing && !this.playback.isFinished();
}
/**
* Returns the Y Offset of this entity.
*
* Taken from EntityPlayer.
*/
@Override
public double getYOffset()
{
return -0.35D;
}
/**
* Can't despawn an actor
*/
@Override
protected boolean canDespawn()
{
return false;
}
/**
* Yes, this boy can be ridden!
*/
@Override
protected boolean canBeRidden(Entity entityIn)
{
return true;
}
/**
* No, this boy can't be steered!
*/
@Override
public boolean canBeSteered()
{
return false;
}
@Override
public boolean canPassengerSteer()
{
return false;
}
/**
* For vehicles, the first passenger is generally considered the controller and "drives" the vehicle. For example,
* Pigs, Horses, and Boats are generally "steered" by the controlling passenger.
*/
@Override
@Nullable
public Entity getControllingPassenger()
{
return this.getPassengers().isEmpty() ? null : (Entity) this.getPassengers().get(0);
}
/**
* Give a morph to an actor
*/
@Override
public IEntityLivingData onInitialSpawn(DifficultyInstance difficulty, IEntityLivingData livingdata)
{
NBTTagCompound tag = new NBTTagCompound();
tag.setString("Name", "blockbuster.steve");
this.morph.fromNBT(tag);
return super.onInitialSpawn(difficulty, livingdata);
}
/**
* Apply first frame for new actor.
*/
@Override
public void onEntityUpdate()
{
boolean spawn = this.world.isRemote && this.ticksExisted < 2;
Record record = this.playback == null ? null : this.playback.record;
spawn &= record != null && record.getFrame(0) != null;
if (spawn)
{
this.playback.applyFrame(this.playback.tick - 1, this, true);
Frame frame = record.getFrameSafe(this.playback.tick - record.preDelay - 1);
if (frame.hasBodyYaw)
{
this.renderYawOffset = frame.bodyYaw;
}
}
super.onEntityUpdate();
if (spawn && this.playback.playing)
{
playback.applyFrame(this.playback.tick, this, true);
Frame frame = record.getFrameSafe(this.playback.tick - record.preDelay);
if (frame.hasBodyYaw)
{
this.renderYawOffset = frame.bodyYaw;
}
}
}
/**
* Adjust the movement, limb swinging, and process action stuff.
*
* See process actions method for more information.
*/
@Override
public void onLivingUpdate()
{
if (!this.world.isRemote && this.playback != null && this.playback.playing && !this.manual)
{
int tick = this.playback.tick;
if (this.playback.isFinished() && !this.noClip)
{
this.playback.stopPlaying();
}
else if (tick != 0 && tick % Blockbuster.recordSyncRate.get() == 0)
{
Dispatcher.sendToTracked(this, new PacketSyncTick(this.getEntityId(), tick));
}
}
if (this.noClip && !this.world.isRemote)
{
if (this.playback != null)
{
this.playback.next();
}
return;
}
this.pickUpNearByItems();
if (this.playback != null)
{
if (this.manual)
{
this.playback.applyFrame(this.playback.tick, this, true);
this.playback.applyAction(this.playback.tick, this, true);
this.playback.tick++;
}
else
{
this.playback.next();
}
}
if (this.world.isRemote && this.newPosRotationIncrements > 0)
{
double d0 = this.posX + (this.interpTargetX - this.posX) / this.newPosRotationIncrements;
double d1 = this.posY + (this.interpTargetY - this.posY) / this.newPosRotationIncrements;
double d2 = this.posZ + (this.interpTargetZ - this.posZ) / this.newPosRotationIncrements;
this.newPosRotationIncrements--;
this.setPosition(d0, d1, d2);
}
else if (!this.isServerWorld())
{
this.motionX *= 0.98D;
this.motionY *= 0.98D;
this.motionZ *= 0.98D;
}
if (Math.abs(this.motionX) < 0.005D) this.motionX = 0.0D;
if (Math.abs(this.motionY) < 0.005D) this.motionY = 0.0D;
if (Math.abs(this.motionZ) < 0.005D) this.motionZ = 0.0D;
this.updateArmSwingProgress();
/* Make foot steps sound more player-like */
if (!this.world.isRemote && this.isPlaying() && this.playback.tick < this.playback.record.frames.size() - 1 && !this.isSneaking() && this.onGround)
{
Frame current = this.playback.record.frames.get(this.playback.tick);
Frame next = this.playback.record.frames.get(this.playback.tick + 1);
double dx = next.x - current.x;
double dy = next.y - current.y;
double dz = next.z - current.z;
this.distanceWalkedModified = this.distanceWalkedModified + MathHelper.sqrt(dx * dx + dz * dz) * 0.32F;
this.distanceWalkedOnStepModified = this.distanceWalkedOnStepModified + MathHelper.sqrt(dx * dx + dy * dy + dz * dz) * 0.32F;
}
if (this.playback != null)
{
double posX = this.posX;
double posY = this.posY;
double posZ = this.posZ;
double prevPosX = this.prevPosX;
double prevPosY = this.prevPosY;
double prevPosZ = this.prevPosZ;
/* Trigger pressure playback */
this.travel(this.moveStrafing, this.moveVertical, this.moveForward);
/* Restore the position from the playback which fixes weird sliding */
this.posX = posX;
this.posY = posY;
this.posZ = posZ;
this.prevPosX = prevPosX;
this.prevPosY = prevPosY;
this.prevPosZ = prevPosZ;
}
else
{
/* Trigger pressure playback */
this.travel(this.moveStrafing, this.moveVertical, this.moveForward);
}
}
/**
* Update fall state.
*
* This override is responsible for applying fall damage on the actor.
* {@link #move(MoverType, double, double, double)} seem to override onGround
* property wrongly on the server.
*/
@Override
protected void updateFallState(double y, boolean onGroundIn, IBlockState state, BlockPos pos)
{
if (!this.world.isRemote && Blockbuster.actorFallDamage.get() && this.playback != null)
{
int tick = this.playback.getTick();
/* Override onGround field */
if (tick >= 1 && tick < this.playback.record.frames.size())
{
this.onGround = onGroundIn = this.playback.record.frames.get(tick - 1).onGround;
}
}
super.updateFallState(y, onGroundIn, state, pos);
}
/**
* Destroy near by items
*
* Taken from super implementation of onLivingUpdate. You can't use
* super.onLivingUpdate() in onLivingUpdate(), because it will distort
* actor's movement (make it more laggy)
*/
private void pickUpNearByItems()
{
if (!this.world.isRemote && !this.dead)
{
for (EntityItem entityitem : this.world.getEntitiesWithinAABB(EntityItem.class, this.getEntityBoundingBox().expand(1.0D, 0.0D, 1.0D)))
{
if (!entityitem.isDead && entityitem.getItem() != null && !entityitem.cannotPickup())
{
this.onItemPickup(entityitem, 1);
entityitem.setDead();
}
}
}
}
/**
* Roll back to {@link EntityLivingBase}'s updateDistance methods.
*
* Its implementation supports much superior renderYawOffset animation.
* Well, at least that's what I think. I should check out
* {@link EntityBodyHelper} before making final decision.
*/
@Override
protected float updateDistance(float renderYawOffset, float distance)
{
boolean shouldAutoAlign = true;
if (Blockbuster.actorPlaybackBodyYaw.get() && this.playback != null && this.playback.record != null)
{
Frame previous = this.playback.record.getFrame(this.playback.getTick() - 1);
Frame frame = this.playback.getCurrentFrame();
if (frame != null && frame.hasBodyYaw)
{
this.renderYawOffset = frame.bodyYaw;
this.prevRenderYawOffset = previous == null || !this.playback.playing ? frame.bodyYaw : previous.bodyYaw;
shouldAutoAlign = false;
}
}
if (shouldAutoAlign)
{
float tempRenderYawOffset = MathHelper.wrapDegrees(renderYawOffset - this.renderYawOffset);
this.renderYawOffset += tempRenderYawOffset * 0.3F;
tempRenderYawOffset = MathHelper.wrapDegrees(this.rotationYaw - this.renderYawOffset);
boolean isBackwards = tempRenderYawOffset < -90.0F || tempRenderYawOffset >= 90.0F;
if (tempRenderYawOffset < -75.0F)
{
tempRenderYawOffset = -75.0F;
}
if (tempRenderYawOffset >= 75.0F)
{
tempRenderYawOffset = 75.0F;
}
this.renderYawOffset = this.rotationYaw - tempRenderYawOffset;
if (tempRenderYawOffset * tempRenderYawOffset > 2500.0F)
{
this.renderYawOffset += tempRenderYawOffset * 0.2F;
}
if (isBackwards)
{
distance *= -1.0F;
}
}
/* Explanation: Why do we update morph here? Because for some reason
* the EntityMorph morphs don't turn smoothly in onLivingUpdate method */
AbstractMorph morph = this.morph.get();
if (morph != null)
{
morph.update(this);
}
while (!this.modify.isEmpty())
{
this.applyModifyPacket(this.modify.poll());
}
return distance;
}
/* Processing interaction with player */
/**
* Process interact
*
* Inject UUID of actor to registering device, open GUI for changing actor's
* skin, or start recording him
*/
@Override
protected boolean processInteract(EntityPlayer player, EnumHand hand)
{
ItemStack item = player.getHeldItem(hand);
boolean empty = item.isEmpty();
if (empty)
{
if (!this.world.isRemote && !Blockbuster.actorDisableRiding.get())
{
if (!player.isSneaking())
{
player.startRiding(this);
}
}
return true;
}
else if (item.getItem() instanceof ItemActorConfig)
{
player.openGui(Blockbuster.instance, GuiHandler.ACTOR, player.world, this.getEntityId(), 0, 0);
return true;
}
return false;
}
/* Public API */
public void applyModifyPacket(PacketModifyActor message)
{
this.forceMorph = message.forceMorph;
if (message.offset >= 0)
{
this.invisible = message.invisible;
this.applyPause(message.morph, message.offset, message.previous, message.previousOffset, this.forceMorph);
if (this.forceMorph)
{
this.pauseOffset = -1;
this.pausePreviousMorph = null;
this.pausePreviousOffset = -1;
this.forceMorph = false;
}
}
else
{
this.modify(message.morph, message.invisible, false);
}
}
/**
* Configure this actor
*
* Takes four properties to modify: filename used as id for recording,
* displayed name, rendering skin and invulnerability flag
*/
public void modify(AbstractMorph morph, boolean invisible, boolean notify)
{
if (this.forceMorph)
{
this.morph.setDirect(morph);
}
else
{
this.morph.set(morph);
}
this.invisible = invisible;
if (!this.world.isRemote && notify)
{
this.notifyPlayers();
}
}
/**
* Morph this actor into given morph (used on the server side)
*/
public void morph(AbstractMorph morph, boolean force)
{
this.pauseOffset = -1;
this.pausePreviousMorph = null;
this.pausePreviousOffset = -1;
this.forceMorph = force;
this.morph.set(morph);
}
/**
* Stores the data for paused morph
*/
public void morphPause(AbstractMorph morph, int offset, AbstractMorph previous, int previousOffset, boolean resume)
{
this.pauseOffset = offset;
this.pausePreviousMorph = previous;
this.pausePreviousOffset = previousOffset;
this.forceMorph = resume;
this.morph.setDirect(morph);
}
/**
* Apply pause on the morph
*/
public void applyPause(AbstractMorph morph, int offset, AbstractMorph previous, int previousOffset, boolean resume)
{
this.morphPause(morph, offset, previous, previousOffset, resume);
MorphUtils.pause(previous, null, previousOffset);
MorphUtils.pause(morph, previous, offset);
if (resume)
{
MorphUtils.resume(morph);
}
}
/**
* Notify trackers of data changes happened in this actor
*/
public void notifyPlayers()
{
if (!this.manual && this.playback != null)
{
this.playback.sendToTracked(new PacketModifyActor(this));
}
}
/* Reading/writing to disk */
@Override
public void readEntityFromNBT(NBTTagCompound tag)
{
super.readEntityFromNBT(tag);
this.morph.setDirect(MorphManager.INSTANCE.morphFromNBT(tag.getCompoundTag("Morph")));
this.invisible = tag.getBoolean("Invisible");
this.enableBurning = tag.getBoolean("EnableBurning");
this.wasAttached = tag.getBoolean("WasAttached");
if (!this.world.isRemote)
{
this.notifyPlayers();
}
}
@Override
public void writeEntityToNBT(NBTTagCompound tag)
{
super.writeEntityToNBT(tag);
if (!this.morph.isEmpty())
{
tag.setTag("Morph", this.morph.get().toNBT());
}
tag.setBoolean("Invisible", this.invisible);
tag.setBoolean("EnableBurning", this.enableBurning);
tag.setBoolean("WasAttached", this.wasAttached);
}
/* IEntityAdditionalSpawnData implementation */
@Override
public void writeSpawnData(ByteBuf buffer)
{
if (this.wasAttached && this.playback == null)
{
this.setDead();
}
MorphUtils.morphToBuf(buffer, this.morph.get());
buffer.writeBoolean(this.invisible);
buffer.writeBoolean(this.enableBurning);
buffer.writeBoolean(this.noClip);
buffer.writeBoolean(this.playback != null);
if (this.playback != null)
{
buffer.writeBoolean(this.playback.playing);
buffer.writeInt(this.playback.tick);
ByteBufUtils.writeUTF8String(buffer, this.playback.record.filename);
buffer.writeBoolean(this.playback.getReplay() != null && this.playback.getReplay().morph != null);
if (this.playback.getReplay() != null && this.playback.getReplay().morph != null)
{
MorphUtils.morphToBuf(buffer, this.playback.getReplay().morph);
}
}
buffer.writeBoolean(this.isEntityInvulnerable(DamageSource.ANVIL));
buffer.writeBoolean(this.renderLast);
}
@Override
public void readSpawnData(ByteBuf buffer)
{
this.morph.setDirect(MorphUtils.morphFromBuf(buffer));
this.invisible = buffer.readBoolean();
this.enableBurning = buffer.readBoolean();
this.noClip = buffer.readBoolean();
if (buffer.readBoolean())
{
boolean playing = buffer.readBoolean();
int tick = buffer.readInt();
String filename = ByteBufUtils.readUTF8String(buffer);
Replay replay = null;
if (buffer.readBoolean())
{
replay = new Replay();
replay.morph = MorphUtils.morphFromBuf(buffer);
}
if (this.playback == null)
{
Record record = ClientProxy.manager.getClient(filename);
if (record != null)
{
this.playback = new RecordPlayer(record, Mode.FRAMES, this);
record.applyPreviousMorph(this, replay, tick - record.preDelay, playing ? MorphType.FORCE : MorphType.PAUSE);
}
else
{
this.playback = new RecordPlayer(null, Mode.FRAMES, this);
Dispatcher.sendToServer(new PacketRequestAction(filename, false));
Dispatcher.sendToServer(new PacketRequestFrames(this.getEntityId(), filename));
}
}
if (this.playback != null)
{
this.playback.tick = tick;
this.playback.playing = playing;
}
}
this.setEntityInvulnerable(buffer.readBoolean());
this.renderLast = buffer.readBoolean();
}
@Override
public boolean canBeLeashedTo(EntityPlayer player) {
return !this.getLeashed();
}
/**
* Used by playback code to set item animation thingy
*/
public void setItemStackInUse(int activeCount)
{
this.activeItemStackUseCount = activeCount;
}
/**
* Is actor in range in render distance
*
* This method is responsible for checking if this entity is
* available for rendering. Rendering range is configurable.
*/
@SideOnly(Side.CLIENT)
@Override
public boolean isInRangeToRenderDist(double distance)
{
double d0 = this.getEntityBoundingBox().getAverageEdgeLength();
if (Double.isNaN(d0))
{
d0 = 1.0D;
}
d0 = d0 * Blockbuster.actorRenderingRange.get();
return distance < d0 * d0;
}
public static class EntityFakePlayer extends EntityPlayer
{
public EntityActor actor;
public EntityFakePlayer(World world, EntityActor actor, GameProfile profile)
{
super(world, profile);
this.actor = actor;
}
@Override
public boolean isSpectator()
{
return false;
}
@Override
public boolean isCreative()
{
return false;
}
@Override
public void onUpdate()
{
if (this.actor.isDead)
{
this.setDead();
return;
}
this.width = this.actor.width;
this.height = this.actor.height;
this.eyeHeight = this.actor.getEyeHeight();
this.setEntityBoundingBox(this.actor.getEntityBoundingBox());
if (this.actor.getRidingEntity() != this)
{
this.posX = this.actor.posX;
this.posY = this.actor.posY;
this.posZ = this.actor.posZ;
}
this.rotationYaw = this.actor.rotationYaw;
this.rotationPitch = this.actor.rotationPitch;
if (!Objects.equals(this.getItemStackFromSlot(EntityEquipmentSlot.MAINHAND), this.actor.getHeldItemMainhand()))
{
this.setItemStackToSlot(EntityEquipmentSlot.MAINHAND, this.actor.getHeldItemMainhand());
}
if (!Objects.equals(this.getItemStackFromSlot(EntityEquipmentSlot.OFFHAND), this.actor.getHeldItemOffhand()))
{
this.setItemStackToSlot(EntityEquipmentSlot.OFFHAND, this.actor.getHeldItemOffhand());
}
}
@Override
public void displayGUIChest(IInventory chestInventory)
{
if (this.openContainer != this.inventoryContainer)
{
this.closeScreen();
}
if (chestInventory instanceof IInteractionObject)
{
this.openContainer = ((IInteractionObject)chestInventory).createContainer(this.inventory, this);
}
else
{
this.openContainer = new ContainerChest(this.inventory, chestInventory, this);
}
}
@Override
public void closeScreen()
{
this.openContainer.onContainerClosed(this);
super.closeScreen();
}
@Override
public void readFromNBT(NBTTagCompound compound)
{
this.setDead();
}
@Override
public NBTTagCompound writeToNBT(NBTTagCompound compound)
{
return compound;
}
}
} | 27,143 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BetterLightsDummyEntity.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/entity/BetterLightsDummyEntity.java | package mchorse.blockbuster.common.entity;
import dz.betterlights.BetterLightsMod;
import dz.betterlights.lighting.lightcasters.LightCaster;
import net.minecraft.world.World;
public class BetterLightsDummyEntity extends ExpirableDummyEntity
{
private LightCaster caster;
public BetterLightsDummyEntity(World worldIn, LightCaster caster, int lifetime)
{
this(worldIn, caster, lifetime, 0, 0);
}
public BetterLightsDummyEntity(World worldIn, LightCaster caster, int lifetime, float height, float width)
{
super(worldIn, lifetime, height, width);
this.caster = caster;
}
public LightCaster getLightCaster()
{
return this.caster;
}
@Override
public void onEntityUpdate()
{
super.onEntityUpdate();
if (!this.world.isRemote || this.caster == null) return;
if (this.isDead)
{
BetterLightsMod.getLightManager().removeLightCaster(this.world, this.caster, false);
}
}
}
| 1,008 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
EntityGunProjectile.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/entity/EntityGunProjectile.java | package mchorse.blockbuster.common.entity;
import io.netty.buffer.ByteBuf;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.common.GunProps;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.guns.PacketGunProjectile;
import mchorse.blockbuster.network.common.guns.PacketGunProjectileVanish;
import mchorse.blockbuster.network.common.guns.PacketGunStuck;
import mchorse.mclib.utils.NBTUtils;
import mchorse.metamorph.api.Morph;
import mchorse.metamorph.api.MorphUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLiving;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.MoverType;
import net.minecraft.entity.projectile.EntityThrowable;
import net.minecraft.init.Blocks;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.DamageSource;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumFacing.Axis;
import net.minecraft.util.EnumParticleTypes;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.util.math.RayTraceResult.Type;
import net.minecraft.util.math.Vec3d;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.ByteBufUtils;
import net.minecraftforge.fml.common.registry.IEntityAdditionalSpawnData;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
/**
* Gun projectile entity
* <p>
* This bad boy is responsible for being a gun projectile. It works in a
* similar fashion as a snowball, but holds a morph
*/
public class EntityGunProjectile extends EntityThrowable implements IEntityAdditionalSpawnData
{
public GunProps props;
public AbstractMorph original;
public Morph morph = new Morph();
public int hits;
public int impact;
public boolean vanish;
public int vanishDelay;
public boolean stuck;
/* Syncing on the client side the position */
public int updatePos;
public double targetX;
public double targetY;
public double targetZ;
public double initMX;
public double initMY;
public double initMZ;
public boolean setInit;
public EntityGunProjectile(World worldIn)
{
this(worldIn, null, null);
}
public EntityGunProjectile(World worldIn, GunProps props, AbstractMorph morph)
{
super(worldIn);
this.props = props;
this.morph.setDirect(morph);
this.original = this.morph.copy();
if (props != null)
{
this.setSize(props.hitboxX, props.hitboxY);
}
this.impact = -1;
}
@Override
public void shoot(Entity entityThrower, float rotationPitchIn, float rotationYawIn, float pitchOffset, float velocity, float inaccuracy)
{
if (entityThrower instanceof EntityActor.EntityFakePlayer)
{
this.thrower = ((EntityActor.EntityFakePlayer) entityThrower).actor;
}
else if (entityThrower instanceof EntityLivingBase)
{
this.thrower = (EntityLivingBase) entityThrower;
}
super.shoot(entityThrower, rotationPitchIn, rotationYawIn, pitchOffset, velocity, inaccuracy);
}
public void setInitialMotion()
{
this.initMX = this.motionX;
this.initMY = this.motionY;
this.initMZ = this.motionZ;
}
@Override
public void onUpdate()
{
if (this.vanish)
{
if (!this.world.isRemote && this.vanishDelay <= 0)
{
this.setDead();
}
if (this.vanishDelay > 0)
{
this.vanishDelay--;
}
}
if (!this.world.isBlockLoaded(this.getPosition(), false))
{
this.setDead();
}
this.lastTickPosX = this.posX;
this.lastTickPosY = this.posY;
this.lastTickPosZ = this.posZ;
if (!this.world.isRemote)
{
this.setFlag(6, this.isGlowing());
}
else if (!this.setInit)
{
this.setInit = true;
this.motionX = this.initMX;
this.motionY = this.initMY;
this.motionZ = this.initMZ;
}
this.onEntityUpdate();
if (!this.stuck)
{
/* Ray trace for impact */
Vec3d position = new Vec3d(this.posX, this.posY, this.posZ);
Vec3d next = new Vec3d(this.posX + this.motionX, this.posY + this.motionY, this.posZ + this.motionZ);
Entity entity = null;
RayTraceResult result = this.world.rayTraceBlocks(position, next, false, true, false);
if (result != null)
{
next = new Vec3d(result.hitVec.x, result.hitVec.y, result.hitVec.z);
}
if (!this.props.ignoreEntities)
{
List<Entity> list = this.world.getEntitiesWithinAABBExcludingEntity(this, this.getEntityBoundingBox().expand(this.motionX, this.motionY, this.motionZ).grow(1.0D));
double dist = 0.0D;
for (int i = 0; i < list.size(); ++i)
{
Entity current = list.get(i);
if (current.canBeCollidedWith())
{
AxisAlignedBB box = current.getEntityBoundingBox().grow(0.30000001192092896D);
RayTraceResult ray = box.calculateIntercept(position, next);
if (ray != null)
{
double d1 = position.squareDistanceTo(ray.hitVec);
if (!(current instanceof EntityGunProjectile) && current != this.thrower && (d1 < dist || dist == 0.0D))
{
entity = current;
dist = d1;
}
}
}
}
}
if (entity != null)
{
result = new RayTraceResult(entity);
}
/* Update position */
this.posX += this.motionX;
this.posY += this.motionY;
this.posZ += this.motionZ;
if (result != null)
{
if (result.typeOfHit == RayTraceResult.Type.BLOCK && this.world.getBlockState(result.getBlockPos()).getBlock() == Blocks.PORTAL)
{
this.setPortal(result.getBlockPos());
}
else
{
if (!net.minecraftforge.common.ForgeHooks.onThrowableImpact(this, result))
{
this.onImpact(result);
}
}
}
/* Update position, motion and rotation */
float distance = MathHelper.sqrt(this.motionX * this.motionX + this.motionZ * this.motionZ);
this.rotationYaw = (float) (MathHelper.atan2(this.motionX, this.motionZ) * (180D / Math.PI));
for (this.rotationPitch = (float) (MathHelper.atan2(this.motionY, distance) * (180D / Math.PI)); this.rotationPitch - this.prevRotationPitch < -180.0F; this.prevRotationPitch -= 360.0F)
{}
while (this.rotationPitch - this.prevRotationPitch >= 180.0F)
this.prevRotationPitch += 360.0F;
while (this.rotationYaw - this.prevRotationYaw < -180.0F)
this.prevRotationYaw -= 360.0F;
while (this.rotationYaw - this.prevRotationYaw >= 180.0F)
this.prevRotationYaw += 360.0F;
this.rotationPitch = this.prevRotationPitch + (this.rotationPitch - this.prevRotationPitch) * 0.2F;
this.rotationYaw = this.prevRotationYaw + (this.rotationYaw - this.prevRotationYaw) * 0.2F;
float friction = this.props == null ? 1 : this.props.friction;
if (this.isInWater())
{
for (int j = 0; j < 4; ++j)
{
this.world.spawnParticle(EnumParticleTypes.WATER_BUBBLE, this.posX - this.motionX * 0.25D, this.posY - this.motionY * 0.25D, this.posZ - this.motionZ * 0.25D, this.motionX, this.motionY, this.motionZ, new int[0]);
}
friction *= 0.8F;
}
if (this.onGround)
{
friction *= 0.9F;
}
this.motionX *= friction;
this.motionY *= friction;
this.motionZ *= friction;
if (!this.hasNoGravity())
{
this.motionY -= this.getGravityVelocity();
}
if (this.hits < this.props.hits)
{
double diff = this.motionX * this.motionX + this.motionY * this.motionY + this.motionZ * this.motionZ;
if (diff < 100 * 100)
{
this.noClip = this.props.ignoreBlocks;
this.move(MoverType.SELF, this.motionX, this.motionY, this.motionZ);
}
else
{
this.setDead();
}
}
else
{
this.setPosition(this.posX, this.posY, this.posZ);
}
}
this.updateProjectile();
}
/**
* Update projectile's properties
*/
private void updateProjectile()
{
if (this.world.isRemote && this.updatePos > 0)
{
double d0 = this.posX + (this.targetX - this.posX) / this.updatePos;
double d1 = this.posY + (this.targetY - this.posY) / this.updatePos;
double d2 = this.posZ + (this.targetZ - this.posZ) / this.updatePos;
this.updatePos--;
this.setPosition(d0, d1, d2);
}
AbstractMorph morph = this.morph.get();
if (morph != null)
{
this.props.createEntity(this.world);
this.props.target.posX = this.posX;
this.props.target.posY = this.posY;
this.props.target.posZ = this.posZ;
morph.update(this.props.getEntity(this));
}
if (this.props == null || this.world.isRemote)
{
return;
}
if (this.ticksExisted > this.props.lifeSpan)
{
this.setDead();
if (!this.props.vanishCommand.isEmpty())
{
this.getServer().commandManager.executeCommand(this, this.props.vanishCommand);
}
}
if (this.props.ticking > 0 && this.ticksExisted % this.props.ticking == 0 && !this.props.tickCommand.isEmpty())
{
this.getServer().commandManager.executeCommand(this, this.props.tickCommand);
}
if (this.impact >= 0)
{
if (this.impact == 0)
{
AbstractMorph original = MorphUtils.copy(this.original);
this.morph.set(original);
Dispatcher.sendToTracked(this, new PacketGunProjectile(this.getEntityId(), original));
}
this.impact--;
}
}
@Override
protected void onImpact(RayTraceResult result)
{
if (this.stuck || this.vanish || this.props == null)
{
return;
}
this.hits++;
boolean shouldDie = this.props.vanish && this.hits >= this.props.hits && !this.props.sticks;
boolean impactMorph = false;
if (result.typeOfHit == Type.BLOCK && !this.props.ignoreBlocks)
{
Axis axis = result.sideHit.getAxis();
float factor = (this.props.bounce && this.hits <= this.props.hits ? -1 : 0);
if (axis == Axis.X) this.motionX *= factor;
if (axis == Axis.Y) this.motionY *= factor;
if (axis == Axis.Z) this.motionZ *= factor;
this.motionX *= this.props.bounceFactor;
this.motionY *= this.props.bounceFactor;
this.motionZ *= this.props.bounceFactor;
this.posX = result.hitVec.x + this.width / 2 * result.sideHit.getFrontOffsetX();
this.posY = result.hitVec.y - this.height * (result.sideHit == EnumFacing.DOWN ? 1 : 0);
this.posZ = result.hitVec.z + this.width / 2 * result.sideHit.getFrontOffsetZ();
if (this.props.sticks)
{
this.stuck = true;
if (!this.world.isRemote)
{
if (result.sideHit == EnumFacing.WEST || result.sideHit == EnumFacing.EAST) this.posX += this.props.penetration * result.sideHit.getFrontOffsetX();
else if (result.sideHit == EnumFacing.UP || result.sideHit == EnumFacing.DOWN) this.posY += this.props.penetration * result.sideHit.getFrontOffsetY();
else if (result.sideHit == EnumFacing.NORTH || result.sideHit == EnumFacing.SOUTH) this.posZ += this.props.penetration * result.sideHit.getFrontOffsetZ();
Dispatcher.sendToTracked(this, new PacketGunStuck(this.getEntityId(), (float) this.posX, (float) this.posY, (float) this.posZ));
}
}
}
if (!this.world.isRemote)
{
if (result.typeOfHit == Type.BLOCK && !this.props.ignoreBlocks)
{
if (!this.props.impactCommand.isEmpty())
{
String command = this.props.impactCommand;
int x = Math.round((float) this.posX);
int y = Math.round((float) this.posY);
int z = Math.round((float) this.posZ);
if (result.typeOfHit == Type.BLOCK)
{
x = result.getBlockPos().getX();
y = result.getBlockPos().getY();
z = result.getBlockPos().getZ();
}
command = command.replaceAll("\\$\\{x\\}", String.valueOf(x));
command = command.replaceAll("\\$\\{y\\}", String.valueOf(y));
command = command.replaceAll("\\$\\{z\\}", String.valueOf(z));
if (this.getServer() != null)
{
this.getServer().commandManager.executeCommand(this, command);
}
}
impactMorph = true;
}
if (result.typeOfHit == Type.ENTITY && !this.props.ignoreEntities)
{
if (!this.props.impactEntityCommand.isEmpty())
{
this.getServer().commandManager.executeCommand(this, this.props.impactEntityCommand);
}
if (this.props.damage > 0)
{
if (result.entityHit instanceof EntityLiving)
{
EntityLiving living = (EntityLiving) result.entityHit;
result.entityHit.attackEntityFrom(DamageSource.causeThrownDamage(this, null), 0);
living.setHealth(living.getHealth() - this.props.damage);
}
else
{
result.entityHit.attackEntityFrom(DamageSource.causeThrownDamage(this, null), this.props.damage);
}
}
if (this.props.knockbackHorizontal != 0 && result.entityHit instanceof EntityLivingBase)
{
((EntityLivingBase) result.entityHit).knockBack(this, Math.abs(this.props.knockbackHorizontal), -this.motionX, -this.motionZ);
if (this.props.knockbackHorizontal < 0)
{
result.entityHit.motionX *= -1;
result.entityHit.motionZ *= -1;
}
}
result.entityHit.motionY += this.props.knockbackVertical;
impactMorph = true;
}
if (shouldDie)
{
this.vanish = true;
this.vanishDelay = this.props.vanishDelay;
if (this.vanishDelay > 0)
{
Dispatcher.sendToTracked(this, new PacketGunProjectileVanish(this.getEntityId(), this.vanishDelay));
}
return;
}
/* Change to impact morph */
if (impactMorph && this.props.impactDelay > 0)
{
AbstractMorph morph = MorphUtils.copy(this.props.impactMorph);
this.morph.set(morph);
this.impact = this.props.impactDelay;
Dispatcher.sendToTracked(this, new PacketGunProjectile(this.getEntityId(), morph));
}
}
}
@Override
protected float getGravityVelocity()
{
return this.props == null ? super.getGravityVelocity() : this.props.gravity;
}
/* NBT and ByteBuf read/write methods */
@Override
public void writeSpawnData(ByteBuf buffer)
{
buffer.writeBoolean(this.props != null);
if (this.props != null)
{
ByteBufUtils.writeTag(buffer, this.props.toNBT());
}
buffer.writeBoolean(this.morph.get() != null);
if (this.morph.get() != null)
{
ByteBufUtils.writeTag(buffer, this.morph.toNBT());
}
buffer.writeDouble(this.initMX);
buffer.writeDouble(this.initMY);
buffer.writeDouble(this.initMZ);
}
@Override
public void readSpawnData(ByteBuf additionalData)
{
if (additionalData.readBoolean())
{
this.props = new GunProps(NBTUtils.readInfiniteTag(additionalData));
this.setSize(this.props.hitboxX, this.props.hitboxY);
}
if (additionalData.readBoolean())
{
this.morph.fromNBT(NBTUtils.readInfiniteTag(additionalData));
}
this.initMX = additionalData.readDouble();
this.initMY = additionalData.readDouble();
this.initMZ = additionalData.readDouble();
}
/**
* Don't restore the entity from NBT, kill the projectile immediately
*/
@Override
public void readEntityFromNBT(NBTTagCompound compound)
{
super.readEntityFromNBT(compound);
this.setDead();
}
/* Client side methods */
/**
* Update position from the server, only in case if there is a big
* desync enough to be noticeable
*/
@Override
@SideOnly(Side.CLIENT)
public void setPositionAndRotationDirect(double x, double y, double z, float yaw, float pitch, int posRotationIncrements, boolean teleport)
{
if (this.stuck)
{
return;
}
double dx = this.posX - x;
double dy = this.posY - y;
double dz = this.posZ - z;
double dist = dx * dx + dy * dy + dz * dz;
double syncDistance = Blockbuster.bbGunSyncDistance.get();
if (syncDistance > 0 && dist > syncDistance * syncDistance)
{
this.updatePos = posRotationIncrements;
this.targetX = x;
this.targetY = y;
this.targetZ = z;
}
}
/**
* Is projectile in range in render distance
* <p>
* This method is responsible for checking if this entity is
* available for rendering. Rendering range is configurable.
*/
@SideOnly(Side.CLIENT)
@Override
public boolean isInRangeToRenderDist(double distance)
{
double d0 = Blockbuster.actorRenderingRange.get();
return distance < d0 * d0;
}
} | 19,745 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ExpirableDummyEntity.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/entity/ExpirableDummyEntity.java | package mchorse.blockbuster.common.entity;
import mchorse.mclib.utils.DummyEntity;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.world.World;
public class ExpirableDummyEntity extends DummyEntity
{
private int lifetime;
private int age;
/**
* Sets the height and width to 0
* @param worldIn
* @param lifetime
*/
public ExpirableDummyEntity(World worldIn, int lifetime)
{
this(worldIn, lifetime, 0, 0);
}
public ExpirableDummyEntity(World worldIn, int lifetime, float height, float width)
{
super(worldIn);
this.lifetime = lifetime;
this.height = height;
this.width = width;
}
public void setLifetime(int lifetime)
{
this.lifetime = lifetime;
}
public int getLifetime()
{
return this.lifetime;
}
public int getAge()
{
return this.age;
}
@Override
public void onEntityUpdate()
{
super.onEntityUpdate();
if (this.age >= this.lifetime)
{
this.setDead();
}
this.age++;
}
@Override
public boolean canBeCollidedWith()
{
return false;
}
@Override
public void onCollideWithPlayer(EntityPlayer entityIn) {}
@Override
public boolean canBePushed()
{
return false;
}
@Override
protected void collideWithEntity(Entity entityIn)
{
}
}
| 1,492 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ItemBlockModel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/item/ItemBlockModel.java | package mchorse.blockbuster.common.item;
import mchorse.blockbuster.Blockbuster;
import net.minecraft.advancements.CriteriaTriggers;
import net.minecraft.block.Block;
import net.minecraft.block.SoundType;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.Entity;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.server.MinecraftServer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.SoundCategory;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import javax.annotation.Nullable;
import java.util.List;
/**
* Item for Model Block with light strength.
* It cannot extend ItemBlock because it seems like Optifine does not
* recognise ItemBlock subclasses for dynamic_lighting.properties.
*
* Block items not extending ItemBlock do not seem to copy NBT on Spigot servers.
* This class is only for the ModelBlocks that have a light strength.
*/
public class ItemBlockModel extends Item
{
private int lightValue;
private Block block;
public ItemBlockModel(Block block, int lightValue)
{
String name = "model" + ((lightValue != 0) ? lightValue : "");
this.block = block;
this.lightValue = lightValue;
this.setRegistryName(name);
this.setUnlocalizedName("blockbuster." + name);
if (lightValue == 0)
{
this.setCreativeTab(Blockbuster.blockbusterTab);
}
}
@Override
/**
* Copied from ItemBlock class
*/
public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
{
IBlockState iblockstate = worldIn.getBlockState(pos);
Block block = iblockstate.getBlock();
if (!block.isReplaceable(worldIn, pos))
{
pos = pos.offset(facing);
}
ItemStack itemstack = player.getHeldItem(hand);
if (!itemstack.isEmpty() && player.canPlayerEdit(pos, facing, itemstack) && worldIn.mayPlace(this.block, pos, false, facing, (Entity)null))
{
/* The Model Block uses metadata for lightValue, the item should use its lightValue as "metadata" for that purpose */
int i = this.lightValue;
IBlockState iblockstate1 = this.block.getStateForPlacement(worldIn, pos, facing, hitX, hitY, hitZ, i, player, hand);
if (placeBlockAt(itemstack, player, worldIn, pos, facing, hitX, hitY, hitZ, iblockstate1))
{
iblockstate1 = worldIn.getBlockState(pos);
SoundType soundtype = iblockstate1.getBlock().getSoundType(iblockstate1, worldIn, pos, player);
worldIn.playSound(player, pos, soundtype.getPlaceSound(), SoundCategory.BLOCKS, (soundtype.getVolume() + 1.0F) / 2.0F, soundtype.getPitch() * 0.8F);
itemstack.shrink(1);
}
return EnumActionResult.SUCCESS;
}
else
{
return EnumActionResult.FAIL;
}
}
/**
* Copied from ItemBlock class
*/
public static boolean setTileEntityNBT(World worldIn, @Nullable EntityPlayer player, BlockPos pos, ItemStack stackIn)
{
MinecraftServer minecraftserver = worldIn.getMinecraftServer();
if (minecraftserver == null)
{
return false;
}
else
{
NBTTagCompound nbttagcompound = stackIn.getSubCompound("BlockEntityTag");
if (nbttagcompound != null)
{
TileEntity tileentity = worldIn.getTileEntity(pos);
if (tileentity != null)
{
if (!worldIn.isRemote && tileentity.onlyOpsCanSetNbt() && (player == null || !player.canUseCommandBlock()))
{
return false;
}
NBTTagCompound nbttagcompound1 = tileentity.writeToNBT(new NBTTagCompound());
NBTTagCompound nbttagcompound2 = nbttagcompound1.copy();
nbttagcompound1.merge(nbttagcompound);
nbttagcompound1.setInteger("x", pos.getX());
nbttagcompound1.setInteger("y", pos.getY());
nbttagcompound1.setInteger("z", pos.getZ());
if (!nbttagcompound1.equals(nbttagcompound2))
{
tileentity.readFromNBT(nbttagcompound1);
tileentity.markDirty();
return true;
}
}
}
return false;
}
}
/**
* allows items to add custom lines of information to the mouseover description
*/
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, @Nullable World worldIn, List<String> tooltip, ITooltipFlag flagIn)
{
super.addInformation(stack, worldIn, tooltip, flagIn);
this.block.addInformation(stack, worldIn, tooltip, flagIn);
}
/**
* Called to actually place the block, after the location is determined
* and all permission checks have been made.
*
* @param stack The item stack that was used to place the block. This can be changed inside the method.
* @param player The player who is placing the block. Can be null if the block is not being placed by a player.
* @param side The side the player (or machine) right-clicked on.
*/
public boolean placeBlockAt(ItemStack stack, EntityPlayer player, World world, BlockPos pos, EnumFacing side, float hitX, float hitY, float hitZ, IBlockState newState)
{
if (!world.setBlockState(pos, newState, 11))
{
return false;
}
IBlockState state = world.getBlockState(pos);
if (state.getBlock() == this.block)
{
this.setTileEntityNBT(world, player, pos, stack);
this.block.onBlockPlacedBy(world, pos, state, player, stack);
if (player instanceof EntityPlayerMP)
{
CriteriaTriggers.PLACED_BLOCK.trigger((EntityPlayerMP)player, pos, stack);
}
}
return true;
}
}
| 6,729 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ItemBlockGreen.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/item/ItemBlockGreen.java | package mchorse.blockbuster.common.item;
import net.minecraft.block.Block;
import net.minecraft.item.ItemColored;
public class ItemBlockGreen extends ItemColored
{
public ItemBlockGreen(Block block, boolean hasSubtypes)
{
super(block, hasSubtypes);
}
} | 274 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ItemRegister.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/item/ItemRegister.java | package mchorse.blockbuster.common.item;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.utils.EntityUtils;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
/**
* Register item
*
* Used to register an actor to director block (a scene) and
* open a director block remotely
*/
public class ItemRegister extends Item
{
public ItemRegister()
{
this.setMaxStackSize(1);
this.setRegistryName("register");
this.setUnlocalizedName("blockbuster.register");
this.setCreativeTab(Blockbuster.blockbusterTab);
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, World worldIn, List<String> tooltip, ITooltipFlag flagIn)
{
tooltip.add(I18n.format("blockbuster.info.register"));
}
/**
* On right click, show the director block GUI, if this item has attached
* director block, then we can show the director block GUI.
*/
@Override
public ActionResult<ItemStack> onItemRightClick(World world, EntityPlayer player, EnumHand hand)
{
if (!world.isRemote)
{
EntityUtils.sendStatusMessage((EntityPlayerMP) player, new TextComponentTranslation("blockbuster.bye_register_item"));
}
return new ActionResult<ItemStack>(EnumActionResult.PASS, player.getHeldItem(hand));
}
} | 1,949 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ItemGun.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/item/ItemGun.java | package mchorse.blockbuster.common.item;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.CommonProxy;
import mchorse.blockbuster.client.render.tileentity.TileEntityGunItemStackRenderer;
import mchorse.blockbuster.client.render.tileentity.TileEntityGunItemStackRenderer.GunEntry;
import mchorse.blockbuster.common.GunProps;
import mchorse.blockbuster.common.entity.EntityActor.EntityFakePlayer;
import mchorse.blockbuster.common.entity.EntityGunProjectile;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.guns.PacketGunInfo;
import mchorse.blockbuster.network.common.guns.PacketGunShot;
import mchorse.blockbuster.recording.actions.Action;
import mchorse.blockbuster.recording.actions.ShootGunAction;
import mchorse.blockbuster.utils.NBTUtils;
import mchorse.blockbuster_pack.morphs.SequencerMorph;
import mchorse.mclib.utils.Interpolation;
import mchorse.mclib.utils.OpHelper;
import mchorse.metamorph.api.MorphUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.init.Items;
import net.minecraft.item.EnumAction;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.math.MathHelper;
import net.minecraft.world.World;
import net.minecraftforge.fml.common.network.simpleimpl.IMessage;
import javax.vecmath.Matrix3f;
import javax.vecmath.Vector3f;
import java.util.List;
import java.util.Objects;
public class ItemGun extends Item
{
public static float getRandom(float a, float b)
{
return (float) Math.random() * (a - b) + b;
}
public ItemGun()
{
this.setMaxStackSize(1);
this.setRegistryName("gun");
this.setUnlocalizedName("blockbuster.gun");
this.setCreativeTab(Blockbuster.blockbusterTab);
}
@Override
public boolean shouldCauseReequipAnimation(ItemStack from, ItemStack to, boolean changed)
{
if (!changed && to.getItem() instanceof ItemGun)
{
GunEntry entry = TileEntityGunItemStackRenderer.models.get(from);
if (entry != null)
{
GunProps props = NBTUtils.getGunProps(to);
boolean same = true;
same &= Objects.equals(entry.props.defaultMorph, props.defaultMorph);
same &= Objects.equals(entry.props.firingMorph, props.firingMorph);
same &= Objects.equals(entry.props.crosshairMorph, props.crosshairMorph);
same &= Objects.equals(entry.props.handsMorph, props.handsMorph);
same &= Objects.equals(entry.props.reloadMorph, props.reloadMorph);
same &= Objects.equals(entry.props.zoomOverlayMorph, props.zoomOverlayMorph);
TileEntityGunItemStackRenderer.models.put(to, TileEntityGunItemStackRenderer.models.remove(from));
return same;
}
}
return true; // what animation to use when the player holds the "use" button
}
@Override
public boolean hitEntity(ItemStack stack, EntityLivingBase target, EntityLivingBase attacker)
{
GunProps props = NBTUtils.getGunProps(stack);
boolean result = super.hitEntity(stack, target, attacker);
if (props == null)
{
return result;
}
if (!result)
{
if (!props.meleeCommand.isEmpty())
{
if (attacker instanceof EntityPlayerMP)
{
EntityPlayerMP player = (EntityPlayerMP) attacker;
player.getServer().commandManager.executeCommand(player, props.meleeCommand);
}
}
target.setHealth(target.getHealth() - props.meleeDamage);
return false;
}
return true;
}
@Override
public EnumAction getItemUseAction(ItemStack stack)
{
return EnumAction.NONE;
}
@Override
public int getMaxItemUseDuration(ItemStack stack)
{
return 0;
}
public static void decreaseTime(ItemStack stack, EntityPlayer player)
{
GunProps props = NBTUtils.getGunProps(stack);
if (props == null)
{
return;
}
if (props.storedShotDelay > 0)
{
props.storedShotDelay = Math.max(props.storedShotDelay - 1, 0);
NBTUtils.saveGunProps(stack, props.toNBT());
if (!player.world.isRemote)
{
Dispatcher.sendTo(new PacketGunInfo(props.toNBT(), player.getEntityId()), (EntityPlayerMP) player);
Dispatcher.sendToTracked(player, new PacketGunInfo(props.toNBT(), player.getEntityId()));
}
}
}
private void resetTime(ItemStack stack, EntityPlayer player)
{
GunProps props = NBTUtils.getGunProps(stack);
if (props == null)
{
return;
}
props.storedShotDelay = props.shotDelay;
NBTUtils.saveGunProps(stack, props.toNBT());
}
public static void decreaseReload(ItemStack stack, EntityPlayer player)
{
GunProps props = NBTUtils.getGunProps(stack);
if (props == null)
{
return;
}
if (props.state == GunState.RELOADING)
{
props.storedReloadingTime = props.storedReloadingTime - 1;
if (props.storedReloadingTime <= 0)
{
props.storedReloadingTime = 0;
props.state = GunState.READY_TO_SHOOT;
}
NBTUtils.saveGunProps(stack, props.toNBT());
if (!player.world.isRemote)
{
Dispatcher.sendTo(new PacketGunInfo(props.toNBT(), player.getEntityId()), (EntityPlayerMP) player);
Dispatcher.sendToTracked(player, new PacketGunInfo(props.toNBT(), player.getEntityId()));
}
}
}
public void decreaseDurability(GunProps props, ItemStack stack, EntityPlayer player)
{
if (props == null)
{
return;
}
if (props.durability != 0)
{
int val = props.storedDurability - 1;
if (val <= 0)
{
if (!props.destroyCommand.isEmpty())
{
player.getServer().commandManager.executeCommand(player, props.destroyCommand);
}
player.getHeldItemMainhand().setCount(0);
}
props.storedDurability = val;
if (NBTUtils.saveGunProps(stack, props.toNBT()))
{
IMessage packet = new PacketGunInfo(props.toNBT(), player.getEntityId());
synchronize((EntityPlayerMP) player,props.toNBT());
Dispatcher.sendTo(packet, (EntityPlayerMP) player);
Dispatcher.sendToTracked(player, packet);
}
}
}
private void synchronize(EntityPlayerMP player, NBTTagCompound tag)
{
if (!OpHelper.isPlayerOp(player))
{
return;
}
ItemStack stack = player.getHeldItemMainhand();
if (NBTUtils.saveGunProps(stack, tag))
{
IMessage packet = new PacketGunInfo(tag, player.getEntityId());
Dispatcher.sendTo(packet, player);
Dispatcher.sendToTracked(player, packet);
}
}
@Override
public boolean onLeftClickEntity(ItemStack p_onLeftClickEntity_1_, EntityPlayer p_onLeftClickEntity_2_, Entity p_onLeftClickEntity_3_)
{
return false;
}
public void shootIt(ItemStack stack, EntityPlayer player, World world)
{
resetTime(stack, player);
GunProps props = NBTUtils.getGunProps(stack);
if (world.isRemote && props != null)
{
if (props.staticRecoil)
{
player.rotationPitch += Interpolation.QUINT_IN.interpolate(player.prevRotationPitch, player.prevRotationPitch + props.recoilXMin, 1F) - player.prevRotationPitch;
player.rotationYaw += Interpolation.QUINT_IN.interpolate(player.prevRotationYaw, player.prevRotationYaw + props.recoilYMin, 1F) - player.prevRotationYaw;
}
else
{
player.rotationPitch += Interpolation.SINE_IN.interpolate(player.prevRotationPitch, player.prevRotationPitch + getRandom(props.recoilXMin, props.recoilXMax), 1F) - player.prevRotationPitch;
player.rotationYaw += Interpolation.SINE_IN.interpolate(player.prevRotationYaw, player.prevRotationYaw + getRandom(props.recoilYMin, props.recoilYMax), 1F) - player.prevRotationYaw;
}
if (props.launch)
{
float pitch = player.rotationPitch + (float) ((Math.random() - 0.5) * props.scatterY);
float yaw = player.rotationYaw + (float) ((Math.random() - 0.5) * props.scatterX);
this.setThrowableHeading(player, pitch, yaw, 0, props.speed);
}
}
this.shoot(stack, props, player, world);
}
public boolean shoot(ItemStack stack, GunProps props, EntityPlayer player, World world)
{
if (props == null)
{
return false;
}
/* Launch the player is enabled */
if (props.launch)
{
float pitch = player.rotationPitch + (float) ((Math.random() - 0.5) * props.scatterY);
float yaw = player.rotationYaw + (float) ((Math.random() - 0.5) * props.scatterX);
this.setThrowableHeading(player, pitch, yaw, 0, props.speed);
if (!props.fireCommand.isEmpty())
{
player.getServer().commandManager.executeCommand(player, props.fireCommand);
}
}
else
{
/* Or otherwise launch bullets */
if (!this.consumeInnerAmmo(stack, player))
{
return false;
}
EntityGunProjectile last = null;
for (int i = 0; i < Math.max(props.projectiles, 1); i++)
{
AbstractMorph morph = props.projectileMorph;
if (props.sequencer && morph instanceof SequencerMorph)
{
SequencerMorph seq = ((SequencerMorph) morph);
morph = props.random ? seq.getRandom() : seq.get(i % seq.morphs.size());
}
morph = MorphUtils.copy(morph);
EntityGunProjectile projectile = new EntityGunProjectile(world, props, morph);
float pitch = player.rotationPitch + (float) ((Math.random() - 0.5) * props.scatterY);
float yaw = player.rotationYaw + (float) ((Math.random() - 0.5) * props.scatterX);
double x = player.posX;
double y = player.posY + player.getEyeHeight();
double z = player.posZ;
Vector3f offset = new Vector3f(props.shootingOffsetX, props.shootingOffsetY, props.shootingOffsetZ);
Vector3f vector = this.rotate(offset, player.rotationYaw, player.rotationPitch);
x += vector.x;
y += vector.y;
z += vector.z;
projectile.setPosition(x, y, z);
projectile.shoot(player, pitch, yaw, 0, props.speed, 0);
projectile.setInitialMotion();
if (props.projectiles > 0)
{
if (!world.isRemote)
{
world.spawnEntity(projectile);
}
}
last = projectile;
}
if (!props.fireCommand.isEmpty())
{
player.getServer().commandManager.executeCommand(last, props.fireCommand);
}
}
if (!world.isRemote)
{
Entity entity = player instanceof EntityFakePlayer ? ((EntityFakePlayer) player).actor : player;
int id = entity.getEntityId();
if (player instanceof EntityPlayerMP)
{
Dispatcher.sendTo(new PacketGunShot(id), (EntityPlayerMP) player);
}
Dispatcher.sendToTracked(entity, new PacketGunShot(id));
List<Action> events = CommonProxy.manager.getActions(player);
if (events != null)
{
events.add(new ShootGunAction(stack));
}
decreaseDurability(NBTUtils.getGunProps(stack), stack, player);
if (player instanceof EntityPlayerMP)
{
GunProps p = NBTUtils.getGunProps(stack);
NBTUtils.saveGunProps(stack, p.toNBT());
Dispatcher.sendTo(new PacketGunInfo(p.toNBT(), entity.getEntityId()), (EntityPlayerMP) player);
Dispatcher.sendToTracked(player, new PacketGunInfo(p.toNBT(), entity.getEntityId()));
}
}
return true;
}
private Vector3f rotate(Vector3f vector, float yaw, float pitch)
{
Matrix3f a = new Matrix3f();
Matrix3f b = new Matrix3f();
a.rotY((180 - yaw) / 180F * (float) Math.PI);
b.rotX(-pitch / 180F * (float) Math.PI);
a.mul(b);
a.transform(vector);
return vector;
}
public static void checkGunState(ItemStack stack, EntityPlayer player)
{
GunProps props = NBTUtils.getGunProps(stack);
if (props == null)
{
return;
}
if (props.storedAmmo <= 0 && props.useReloading && props.state == GunState.READY_TO_SHOOT)
{
props.state = GunState.NEED_TO_BE_RELOAD;
}
NBTUtils.saveGunProps(player.getHeldItemMainhand(), props.toNBT());
if (!player.world.isRemote)
{
Dispatcher.sendTo(new PacketGunInfo(props.toNBT(), player.getEntityId()), (EntityPlayerMP) player);
Dispatcher.sendToTracked(player, new PacketGunInfo(props.toNBT(), player.getEntityId()));
}
}
public static void checkGunReload(ItemStack stack, EntityPlayer player)
{
if (!player.world.isRemote)
{
GunProps props = NBTUtils.getGunProps(stack);
if (props.state == ItemGun.GunState.NEED_TO_BE_RELOAD && props.storedShotDelay == 0)
{
ItemGun gun = (ItemGun) stack.getItem();
gun.reload(player, stack);
}
}
}
private boolean consumeInnerAmmo(ItemStack stack, EntityPlayer player)
{
GunProps props = NBTUtils.getGunProps(stack);
if (props == null)
{
return false;
}
int ammo = props.storedAmmo;
if (ammo <= 0)
{
if (props.useReloading)
{
return false;
}
else
{
props.storedAmmo = props.ammo;
NBTUtils.saveGunProps(player.getHeldItemMainhand(), props.toNBT());
if (!player.capabilities.isCreativeMode && !props.ammoStack.isEmpty())
{
return this.consumeAmmoStack(player, props.ammoStack, props.ammoStack.getCount()) >= 0;
}
else
{
return true;
}
}
}
this.consumeAmmo(stack, player);
return true;
}
private void consumeAmmo(ItemStack stack, EntityPlayer player)
{
GunProps props = NBTUtils.getGunProps(stack);
if (props == null)
{
return;
}
props.storedAmmo -= 1;
NBTUtils.saveGunProps(player.getHeldItemMainhand(), props.toNBT());
}
public int consumeAmmoStack(EntityPlayer player, ItemStack ammo, int count)
{
return player.inventory.clearMatchingItems(ammo.getItem(), -1, count, ammo.getTagCompound());
}
private void setThrowableHeading(EntityLivingBase entityThrower, float rotationPitchIn, float rotationYawIn, float pitchOffset, float velocity)
{
float f = -MathHelper.sin(rotationYawIn * 0.017453292F) * MathHelper.cos(rotationPitchIn * 0.017453292F);
float f1 = -MathHelper.sin((rotationPitchIn + pitchOffset) * 0.017453292F);
float f2 = MathHelper.cos(rotationYawIn * 0.017453292F) * MathHelper.cos(rotationPitchIn * 0.017453292F);
this.setThrowableHeading(entityThrower, (double) f, (double) f1, (double) f2, velocity);
}
public void setThrowableHeading(EntityLivingBase entity, double x, double y, double z, float velocity)
{
float distance = MathHelper.sqrt(x * x + y * y + z * z);
entity.motionX = x / distance * velocity;
entity.motionY = y / distance * velocity;
entity.motionZ = z / distance * velocity;
}
public void reload(EntityPlayer player, ItemStack stack)
{
GunProps props = NBTUtils.getGunProps(stack);
if (props == null)
{
return;
}
int count = 0;
if (!player.capabilities.isCreativeMode && !props.ammoStack.isEmpty())
{
ItemStack ammo = props.ammoStack;
count = this.consumeAmmoStack(player, ammo, props.ammo - props.storedAmmo);
}
else
{
count = props.ammo - props.storedAmmo;
}
if (count > 0)
{
props.state = ItemGun.GunState.RELOADING;
props.storedAmmo += count;
props.storedReloadingTime = props.reloadingTime;
if (!props.reloadCommand.isEmpty())
{
player.getServer().commandManager.executeCommand(player, props.reloadCommand);
}
NBTUtils.saveGunProps(stack, props.toNBT());
Dispatcher.sendTo(new PacketGunInfo(props.toNBT(), player.getEntityId()), (EntityPlayerMP) player);
Dispatcher.sendToTracked(player, new PacketGunInfo(props.toNBT(), player.getEntityId()));
}
}
@Override
public boolean showDurabilityBar(ItemStack stack)
{
GunProps props = NBTUtils.getGunProps(stack);
if (props != null)
{
return props.state == GunState.RELOADING || props.ammo > 1 || props.durability > 0;
}
return super.showDurabilityBar(stack);
}
@Override
public double getDurabilityForDisplay(ItemStack stack)
{
GunProps props = NBTUtils.getGunProps(stack);
if (props != null)
{
if (props.state != GunState.READY_TO_SHOOT)
{
if (props.state == GunState.RELOADING && props.reloadingTime > 0)
{
return ((double) props.storedReloadingTime / props.reloadingTime);
}
else
{
return 1.0;
}
}
else if (props.ammo > 1)
{
return 1.0 - ((double) props.storedAmmo / props.ammo);
}
else if (props.durability > 0)
{
return 1.0 - ((double) props.storedDurability / props.durability);
}
}
return super.getDurabilityForDisplay(stack);
}
@Override
public int getRGBDurabilityForDisplay(ItemStack stack)
{
GunProps props = NBTUtils.getGunProps(stack);
if (props != null)
{
if (props.state != GunState.READY_TO_SHOOT)
{
return 0xFFFF0000;
}
else if (props.ammo > 1)
{
return 0xFF2FC0FF;
}
}
return super.getRGBDurabilityForDisplay(stack);
}
public enum GunState
{
READY_TO_SHOOT,
RELOADING,
NEED_TO_BE_RELOAD
}
} | 20,156 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ItemPlayback.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/item/ItemPlayback.java | package mchorse.blockbuster.common.item;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.CommonProxy;
import mchorse.blockbuster.aperture.CameraHandler;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.PacketPlaybackButton;
import mchorse.blockbuster.recording.scene.SceneLocation;
import mchorse.mclib.utils.OpHelper;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.util.ActionResult;
import net.minecraft.util.EnumActionResult;
import net.minecraft.util.EnumHand;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
/**
* Playback button item
*
* Push to start playing back the scene
*/
public class ItemPlayback extends Item
{
/* ItemPlayback */
public ItemPlayback()
{
this.setMaxStackSize(1);
this.setRegistryName("playback");
this.setUnlocalizedName("blockbuster.playback");
this.setCreativeTab(Blockbuster.blockbusterTab);
}
/**
* Adds information about camera profile and the location of director block
* to which it's attached
*/
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, World worldIn, List<String> tooltip, ITooltipFlag flagIn)
{
tooltip.add(I18n.format("blockbuster.info.playback_button"));
NBTTagCompound tag = stack.getTagCompound();
if (tag == null)
{
return;
}
if (tag.hasKey("CameraProfile"))
{
tooltip.add(I18n.format("blockbuster.info.playback_profile", tag.getString("CameraProfile")));
}
else if (tag.hasKey("CameraPlay"))
{
tooltip.add(I18n.format("blockbuster.info.playback_play"));
}
if (tag.hasKey("Scene"))
{
tooltip.add(I18n.format("blockbuster.info.playback_scene", tag.getString("Scene")));
}
}
/**
* This method starts playback of the director block's actors (if the
* director block is attached to this item stack).
*/
@Override
public ActionResult<ItemStack> onItemRightClick(World worldIn, EntityPlayer player, EnumHand handIn)
{
ItemStack stack = player.getHeldItem(handIn);
if (!worldIn.isRemote)
{
NBTTagCompound tag = stack.getTagCompound();
if (player.isSneaking() && OpHelper.isPlayerOp((EntityPlayerMP) player))
{
if (tag == null)
{
tag = new NBTTagCompound();
}
String profile = tag.getString("CameraProfile");
String scene = tag.getString("Scene");
Dispatcher.sendTo(new PacketPlaybackButton(new SceneLocation(scene), CameraHandler.getModeFromNBT(tag), profile).withScenes(CommonProxy.scenes.sceneFiles()), ((EntityPlayerMP) player));
return new ActionResult<ItemStack>(EnumActionResult.SUCCESS, stack);
}
if (tag == null)
{
return new ActionResult<ItemStack>(EnumActionResult.PASS, stack);
}
String scene = tag.getString("Scene");
if (!scene.isEmpty() && CommonProxy.scenes.toggle(scene, player.world) && CameraHandler.isApertureLoaded())
{
CameraHandler.handlePlaybackItem(player, tag);
}
}
return new ActionResult<ItemStack>(EnumActionResult.SUCCESS, stack);
}
} | 3,819 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ItemActorConfig.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/item/ItemActorConfig.java | package mchorse.blockbuster.common.item;
import java.util.List;
import mchorse.blockbuster.Blockbuster;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* This item is used for opening actor's configuration GUI.
*
* I really like the icon, it looks badass!
*/
public class ItemActorConfig extends Item
{
public ItemActorConfig()
{
this.setMaxStackSize(1);
this.setRegistryName("actor_config");
this.setUnlocalizedName("blockbuster.actor_config");
this.setCreativeTab(Blockbuster.blockbusterTab);
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, World worldIn, List<String> tooltip, ITooltipFlag flagIn)
{
tooltip.add(I18n.format("blockbuster.info.actor_config"));
}
} | 1,024 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BlockDimGreen.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/block/BlockDimGreen.java | package mchorse.blockbuster.common.block;
import net.minecraft.block.BlockSlab;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.List;
public class BlockDimGreen extends BlockGreen
{
public BlockDimGreen()
{
super();
this.setLightLevel(0.0F);
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, World player, List<String> tooltip, ITooltipFlag advanced)
{
super.addInformation(stack, player, tooltip, advanced);
tooltip.add(I18n.format("blockbuster.info.dim_green_block"));
}
@Override
@SideOnly(Side.CLIENT)
public float getAmbientOcclusionLightValue(IBlockState state)
{
return 1;
}
@SideOnly(Side.CLIENT)
@Override
public int getPackedLightmapCoords(IBlockState state, IBlockAccess source, BlockPos pos)
{
int i = source.getCombinedLight(pos, state.getLightValue(source, pos));
if (i == 0 && state.getBlock() instanceof BlockSlab)
{
pos = pos.down();
state = source.getBlockState(pos);
return source.getCombinedLight(pos, state.getLightValue(source, pos));
}
else
{
return i;
}
}
} | 1,637 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BlockModel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/block/BlockModel.java | package mchorse.blockbuster.common.block;
import java.util.List;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.common.BlockbusterPermissions;
import mchorse.blockbuster.common.GuiHandler;
import mchorse.blockbuster.common.tileentity.TileEntityModel;
import mchorse.blockbuster.recording.capturing.ActionHandler;
import mchorse.mclib.permissions.PermissionUtils;
import mchorse.mclib.utils.EntityUtils;
import mchorse.mclib.utils.OpHelper;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.PropertyInteger;
import net.minecraft.block.state.BlockFaceShape;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.particle.ParticleManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Block model
*
* This block is responsible for providing a tile entity which is
* responsible for rendering a morph.
*/
public class BlockModel extends Block implements ITileEntityProvider
{
public static final PropertyInteger LIGHT = PropertyInteger.create("light",0,15);
/**
* Used to setup the yaw for the tile entity
*/
private float lastYaw;
public BlockModel()
{
super(Material.ROCK);
this.setCreativeTab(Blockbuster.blockbusterTab);
this.setResistance(6000000.0F);
this.setRegistryName("model");
this.setUnlocalizedName("blockbuster.model");
this.setDefaultState(this.getDefaultState().withProperty(LIGHT, 0));
}
public static ItemStack getItemStack(int meta)
{
Item modelBlockItem = Blockbuster.modelBlockItems[0];
if (meta >= 0 && meta <= 15)
{
modelBlockItem = Blockbuster.modelBlockItems[meta];
}
return new ItemStack(modelBlockItem, 1);
}
/**
* Get the itemstack containing one item of this block according to the blockstate
* @param state
* @return itemstack with the metadata returned by {@link #damageDropped(IBlockState)}
*/
public ItemStack getItemStack(IBlockState state)
{
int meta = this.damageDropped(state);
return getItemStack(meta);
}
@Override
public int getLightValue(IBlockState state, IBlockAccess world, BlockPos pos)
{
return state.getValue(LIGHT);
}
@Override
public ItemStack getItem(World worldIn, BlockPos pos, IBlockState state)
{
ItemStack stack = this.getItemStack(state);
TileEntityModel model = new TileEntityModel();
model.getSettings().setLightValue(this.damageDropped(state));
this.setTENBTtoStack(stack, model);
return stack;
}
/**
* Gets the metadata of the item this Block can drop.
* This method is called when the block gets destroyed.
* It returns the metadata of the dropped item based on the old metadata of the block.
*/
@Override
public int damageDropped(IBlockState state)
{
return this.getMetaFromState(state);
}
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, LIGHT);
}
@Override
public int getMetaFromState(IBlockState state)
{
return state.getValue(LIGHT);
}
@Override
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(LIGHT, meta);
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, World player, List<String> tooltip, ITooltipFlag advanced)
{
tooltip.add(I18n.format("blockbuster.info.model_block"));
}
@Override
public void getDrops(NonNullList<ItemStack> drops, IBlockAccess world, BlockPos pos, IBlockState state, int fortune)
{
ItemStack stack = this.getItemStack(state);
TileEntity te = ActionHandler.lastTE;
if (te instanceof TileEntityModel)
{
TileEntityModel model = (TileEntityModel) te;
this.setTENBTtoStack(stack, model);
}
drops.add(stack);
}
/**
* Set the NBT tag of the provided TileEntityModel to the given stack.
* @param stack
* @param teModel
* @return
*/
public ItemStack setTENBTtoStack(ItemStack stack, TileEntityModel teModel)
{
NBTTagCompound tag = teModel.writeToNBT(new NBTTagCompound());
NBTTagCompound block = new NBTTagCompound();
tag.removeTag("x");
tag.removeTag("y");
tag.removeTag("z");
block.setTag("BlockEntityTag", tag);
if (!(tag.getSize() == 2 && tag.hasKey("id") && tag.hasKey("Morph") && tag.getTag("Morph").equals(TileEntityModel.getDefaultMorph().toNBT())))
{
stack.setTagCompound(block);
}
return stack;
}
@Override
public boolean addDestroyEffects(World world, BlockPos pos, ParticleManager manager)
{
return true;
}
@Override
public boolean canHarvestBlock(IBlockAccess world, BlockPos pos, EntityPlayer player)
{
return true;
}
@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
{
if (worldIn.isRemote && !EntityUtils.isAdventureMode(playerIn))
{
PermissionUtils.hasPermission(playerIn, BlockbusterPermissions.editModelBlock, (bool) ->
{
if (bool)
{
GuiHandler.open(playerIn, GuiHandler.MODEL_BLOCK, pos.getX(), pos.getY(), pos.getZ());
}
});
}
return true;
}
@Override
public IBlockState getStateForPlacement(World world, BlockPos pos, EnumFacing facing, float hitX, float hitY, float hitZ, int meta, EntityLivingBase placer, EnumHand hand)
{
this.lastYaw = placer.isSneaking() ? MathHelper.wrapDegrees(180 - placer.rotationYaw) : 0;
return super.getStateForPlacement(world, pos, facing, hitX, hitY, hitZ, meta, placer, hand);
}
@Override
public void onBlockPlacedBy(World world, BlockPos pos, IBlockState state, EntityLivingBase placer, ItemStack stack)
{
if (world.isRemote && stack.hasTagCompound() && hasTileEntity(state) && stack.getTagCompound().hasKey("BlockEntityTag"))
{
TileEntity tileEntity = world.getTileEntity(pos);
if (tileEntity != null)
{
tileEntity.handleUpdateTag(stack.getTagCompound().getCompoundTag("BlockEntityTag"));
}
}
}
@Override
public TileEntity createNewTileEntity(World worldIn, int meta)
{
TileEntity entity = new TileEntityModel(this.lastYaw);
this.lastYaw = 0;
return entity;
}
/* Setting up visual properties and collision box */
/**
* Don't connect to fences
*/
@Override
public BlockFaceShape getBlockFaceShape(IBlockAccess worldIn, IBlockState state, BlockPos pos, EnumFacing face)
{
return BlockFaceShape.UNDEFINED;
}
public boolean isOpaqueCube(IBlockState state)
{
return false;
}
public boolean isFullCube(IBlockState state)
{
return false;
}
@Override
public boolean canSpawnInBlock()
{
return true;
}
public EnumBlockRenderType getRenderType(IBlockState state)
{
return EnumBlockRenderType.ENTITYBLOCK_ANIMATED;
}
@Override
public AxisAlignedBB getCollisionBoundingBox(IBlockState blockState, IBlockAccess worldIn, BlockPos pos)
{
TileEntity te = worldIn.getTileEntity(pos);
if (te instanceof TileEntityModel && ((TileEntityModel) te).getSettings().isBlockHitbox())
{
return super.getCollisionBoundingBox(blockState, worldIn, pos);
}
return null;
}
} | 8,827 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BlockGreen.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/block/BlockGreen.java | package mchorse.blockbuster.common.block;
import java.util.List;
import mchorse.blockbuster.Blockbuster;
import net.minecraft.block.Block;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyEnum;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.creativetab.CreativeTabs;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.Item;
import net.minecraft.item.ItemStack;
import net.minecraft.util.IStringSerializable;
import net.minecraft.util.NonNullList;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.math.RayTraceResult;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
public class BlockGreen extends Block
{
public static final PropertyEnum<ChromaColor> COLOR = PropertyEnum.<ChromaColor>create("color", ChromaColor.class);
public BlockGreen()
{
super(Material.CLAY);
this.setCreativeTab(Blockbuster.blockbusterTab);
this.setResistance(6000000.0F);
this.setLightLevel(1.0F / 15.0F);
this.setDefaultState(this.getDefaultState().withProperty(COLOR, ChromaColor.GREEN));
}
@Override
public IBlockState getStateFromMeta(int meta)
{
ChromaColor[] values = ChromaColor.values();
if (meta >= values.length || meta < 0)
{
return this.getDefaultState();
}
return this.getDefaultState().withProperty(COLOR, values[meta]);
}
@Override
public int getMetaFromState(IBlockState state)
{
return state.getValue(COLOR).ordinal();
}
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, new IProperty[] {COLOR});
}
@Override
public ItemStack getPickBlock(IBlockState state, RayTraceResult target, World world, BlockPos pos, EntityPlayer player)
{
int meta = state.getValue(COLOR).ordinal();
return new ItemStack(Item.getItemFromBlock(this), 1, meta);
}
@Override
@SideOnly(Side.CLIENT)
public void getSubBlocks(CreativeTabs itemIn, NonNullList<ItemStack> items)
{
for (ChromaColor color : ChromaColor.values())
{
items.add(new ItemStack(this, 1, color.ordinal()));
}
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, World player, List<String> tooltip, ITooltipFlag advanced)
{
tooltip.add(I18n.format("blockbuster.info.green_block", I18n.format("blockbuster.chroma_blocks." + stack.getMetadata())));
}
@Override
@SideOnly(Side.CLIENT)
public float getAmbientOcclusionLightValue(IBlockState state)
{
return 1;
}
@SideOnly(Side.CLIENT)
@Override
public int getPackedLightmapCoords(IBlockState state, IBlockAccess source, BlockPos pos) {
return 15728880; // 15 << 20 | 15 << 4
}
public static enum ChromaColor implements IStringSerializable
{
GREEN("green"), BLUE("blue"), RED("red"), YELLOW("yellow"), CYAN("cyan"), PURPLE("purple"), WHITE("white"), BLACK("black");
public final String name;
private ChromaColor(String name)
{
this.name = name;
}
@Override
public String getName()
{
return this.name;
}
}
} | 3,649 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
BlockDirector.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/common/block/BlockDirector.java | package mchorse.blockbuster.common.block;
import java.lang.reflect.Field;
import java.util.List;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.aperture.CameraHandler;
import mchorse.blockbuster.common.GuiHandler;
import mchorse.blockbuster.common.item.ItemPlayback;
import mchorse.blockbuster.common.item.ItemRegister;
import mchorse.blockbuster.common.tileentity.TileEntityDirector;
import mchorse.blockbuster.utils.EntityUtils;
import net.minecraft.block.Block;
import net.minecraft.block.ITileEntityProvider;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.BlockStateContainer;
import net.minecraft.block.state.IBlockState;
import net.minecraft.client.resources.I18n;
import net.minecraft.client.util.ITooltipFlag;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumBlockRenderType;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.EnumHand;
import net.minecraft.util.math.AxisAlignedBB;
import net.minecraft.util.math.BlockPos;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextComponentTranslation;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.util.text.event.HoverEvent;
import net.minecraft.world.IBlockAccess;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Director block
*
* This block is the one that responsible for machinimas creation.
*/
public class BlockDirector extends Block implements ITileEntityProvider
{
/**
* The playing state property of director block
*/
public static final PropertyBool PLAYING = PropertyBool.create("playing");
/**
* The hidden state property of director block
*/
public static final PropertyBool HIDDEN = PropertyBool.create("hidden");
public BlockDirector()
{
super(Material.ROCK);
this.setDefaultState(this.getDefaultState().withProperty(PLAYING, false).withProperty(HIDDEN, false));
this.setCreativeTab(Blockbuster.blockbusterTab);
this.setBlockUnbreakable();
this.setResistance(6000000.0F);
this.setRegistryName("director");
this.setUnlocalizedName("blockbuster.director");
}
@Override
@SideOnly(Side.CLIENT)
public void addInformation(ItemStack stack, World player, List<String> tooltip, ITooltipFlag advanced)
{
tooltip.add(I18n.format("blockbuster.info.director_block"));
}
@Override
public boolean canHarvestBlock(IBlockAccess world, BlockPos pos, EntityPlayer player)
{
return true;
}
@Override
public boolean isOpaqueCube(IBlockState state)
{
return !state.getValue(HIDDEN);
}
@Override
public boolean isFullCube(IBlockState state)
{
return !state.getValue(HIDDEN);
}
@Override
public EnumBlockRenderType getRenderType(IBlockState state)
{
return state.getValue(HIDDEN) ? EnumBlockRenderType.ENTITYBLOCK_ANIMATED : super.getRenderType(state);
}
@Override
public AxisAlignedBB getCollisionBoundingBox(IBlockState state, IBlockAccess worldIn, BlockPos pos)
{
return state.getValue(HIDDEN) ? null : super.getCollisionBoundingBox(state, worldIn, pos);
}
/* States */
@Override
public int getMetaFromState(IBlockState state)
{
int meta = state.getValue(PLAYING) ? 0 : 1;
meta |= state.getValue(HIDDEN) ? 0b10 : 0;
return meta;
}
@Override
public IBlockState getStateFromMeta(int meta)
{
return this.getDefaultState().withProperty(PLAYING, (meta & 0b1) == 0b1).withProperty(HIDDEN, (meta & 0b10) == 0b10);
}
@Override
protected BlockStateContainer createBlockState()
{
return new BlockStateContainer(this, PLAYING, HIDDEN);
}
/* Redstone */
@Override
public boolean canProvidePower(IBlockState state)
{
return true;
}
/**
* Power west side of the block while block is playing and power east side
* of the block while isn't playback actors.
*/
@Override
public int getWeakPower(IBlockState blockState, IBlockAccess blockAccess, BlockPos pos, EnumFacing side)
{
boolean isPlaying = blockState.getValue(PLAYING);
return (isPlaying && side == EnumFacing.WEST) || (!isPlaying && side == EnumFacing.EAST) ? 15 : 0;
}
/* Player interaction */
@Override
public boolean onBlockActivated(World worldIn, BlockPos pos, IBlockState state, EntityPlayer playerIn, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ)
{
if (!worldIn.isRemote)
{
EntityUtils.sendStatusMessage((EntityPlayerMP) playerIn, new TextComponentTranslation("blockbuster.bye_director_block"));
ITextComponent link = new TextComponentTranslation("blockbuster.bye_director_block_guide");
ITextComponent youtube = new TextComponentTranslation("blockbuster.bye_director_block_guide_watch");
String url = getUrl(playerIn);
youtube.getStyle().setClickEvent(new ClickEvent(ClickEvent.Action.OPEN_URL, url));
youtube.getStyle().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString(url)));
youtube.getStyle().setColor(TextFormatting.GRAY).setUnderlined(true);
playerIn.sendMessage(link.appendSibling(youtube).appendSibling(new TextComponentString(".")));
}
return true;
}
/**
* Get video URL based on language, for Chinese users it uses Bilibili video link
*/
private String getUrl(EntityPlayer playerIn)
{
Field field = null;
for (Field member : EntityPlayerMP.class.getDeclaredFields())
{
if (member.getType() == String.class)
{
field = member;
break;
}
}
if (field != null)
{
try
{
field.setAccessible(true);
String language = (String) field.get(playerIn);
if (language.startsWith("zh_"))
{
return "https://bilibili.com/video/BV1SV41117Pm";
}
}
catch (Exception e)
{}
}
return "https://youtu.be/nMOb8RnuyuE";
}
@Override
public TileEntity createNewTileEntity(World worldIn, int meta)
{
return new TileEntityDirector();
}
} | 6,895 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
SkinHandler.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/SkinHandler.java | package mchorse.blockbuster.client;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.CommonProxy;
import net.minecraft.client.Minecraft;
import org.apache.commons.io.FilenameUtils;
import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import javax.imageio.stream.ImageInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
public class SkinHandler
{
/**
* Check general skins folder, and move these files to appropriate
* skins folders
*/
public static void checkSkinsFolder()
{
if (!ClientProxy.skinsFolder.exists())
{
return;
}
File[] files = ClientProxy.skinsFolder.listFiles();
if (files == null)
{
return;
}
for (File file : files)
{
if (file.isFile())
{
tryReadingMovingSkinFile(file);
}
}
}
private static void tryReadingMovingSkinFile(File file)
{
try
{
FileInputStream stream = new FileInputStream(file);
try (ImageInputStream in = ImageIO.createImageInputStream(stream))
{
final Iterator<ImageReader> readers = ImageIO.getImageReaders(in);
if (readers.hasNext())
{
ImageReader reader = readers.next();
try
{
reader.setInput(in);
int w = reader.getWidth(0);
int h = reader.getHeight(0);
reader.dispose();
stream.close();
reader = null;
tryMovingSkin(file, w, h);
}
finally
{
if (reader != null)
{
reader.dispose();
stream.close();
}
}
}
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
private static void tryMovingSkin(File file, int w, int h)
{
float aspect = w / (float) h;
/* Must be 1 to 1 or 2 to 1 aspect ratio */
if (!(aspect == 2F || aspect == 1F))
{
return;
}
int hf = aspect == 1F ? 64 : 32;
if (!(w % 64 == 0 || h % hf == 0))
{
return;
}
moveToDestination(hf == 64 ? "fred" : "steve", file);
}
private static void moveToDestination(String folder, File input)
{
String name = input.getName();
File file = new File(CommonProxy.configFile, "models/" + folder + "/skins/" + name);
for (int i = 1; file.exists() && i < 1000; i++)
{
file = new File(CommonProxy.configFile, "models/" + folder + "/skins/" + FilenameUtils.getBaseName(name) + "_" + i + "." + FilenameUtils.getExtension(name));
}
if (!file.exists())
{
boolean moved = input.renameTo(file);
if (moved)
{
Blockbuster.l10n.success(Minecraft.getMinecraft().player, "model.skin_moved", name, "blockbuster." + folder, file.getName());
}
}
}
} | 3,417 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
KeyboardHandler.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/KeyboardHandler.java | package mchorse.blockbuster.client;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.client.gui.GuiGun;
import mchorse.blockbuster_pack.morphs.StructureMorph;
import mchorse.mclib.utils.OpHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.settings.KeyBinding;
import net.minecraft.item.ItemStack;
import net.minecraftforge.fml.client.registry.ClientRegistry;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.InputEvent;
import net.minecraftforge.fml.common.network.FMLNetworkEvent.ClientDisconnectionFromServerEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard;
/**
* Separate event handler for keyboard events
*/
@SideOnly(Side.CLIENT)
public class KeyboardHandler
{
/* Misc. */
private KeyBinding plause;
private KeyBinding record;
private KeyBinding pause;
private KeyBinding openGun;
public static KeyBinding zoom;
public static KeyBinding gunReload;
public static KeyBinding gunShoot;
/**
* Create and register key bindings for mod
*/
public KeyboardHandler()
{
/* Key categories */
String category = "key.blockbuster.category";
/* Misc */
this.plause = new KeyBinding("key.blockbuster.plause_director", Keyboard.KEY_RCONTROL, category);
this.record = new KeyBinding("key.blockbuster.record_director", Keyboard.KEY_RMENU, category);
this.pause = new KeyBinding("key.blockbuster.pause_director", Keyboard.KEY_RSHIFT, category);
this.openGun = new KeyBinding("key.blockbuster.open_gun", Keyboard.KEY_END, category);
this.zoom = new KeyBinding("key.blockbuster.zoom", 0, category);
this.gunReload = new KeyBinding("key.blockbuster.gun_reload", 19, category);
this.gunShoot = new KeyBinding("key.blockbuster.gun_shoot", -100, category);
ClientRegistry.registerKeyBinding(this.plause);
ClientRegistry.registerKeyBinding(this.record);
ClientRegistry.registerKeyBinding(this.pause);
ClientRegistry.registerKeyBinding(this.openGun);
ClientRegistry.registerKeyBinding(this.zoom);
ClientRegistry.registerKeyBinding(this.gunReload);
ClientRegistry.registerKeyBinding(this.gunShoot);
}
@SubscribeEvent
public void onUserLogOut(ClientDisconnectionFromServerEvent event)
{
ClientProxy.manager.reset();
ClientProxy.recordingOverlay.setVisible(false);
RenderingHandler.resetEmitters();
Minecraft.getMinecraft().addScheduledTask(StructureMorph::cleanUp);
}
@SubscribeEvent
public void onKey(InputEvent.KeyInputEvent event)
{
if (this.plause.isPressed())
{
if (ClientProxy.panels.scenePanel != null)
{
ClientProxy.panels.scenePanel.plause();
}
}
if (this.record.isPressed())
{
if (ClientProxy.panels.scenePanel != null)
{
ClientProxy.panels.scenePanel.record();
}
}
if (this.pause.isPressed())
{
if (ClientProxy.panels.scenePanel != null)
{
ClientProxy.panels.scenePanel.pause();
}
}
Minecraft mc = Minecraft.getMinecraft();
if (this.openGun.isPressed() && mc.player.capabilities.isCreativeMode && OpHelper.isPlayerOp())
{
ItemStack stack = mc.player.getHeldItemMainhand();
if (stack.getItem() == Blockbuster.gunItem)
{
mc.displayGuiScreen(new GuiGun(stack));
}
}
}
} | 3,784 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
RenderingHandler.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/RenderingHandler.java | package mchorse.blockbuster.client;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.aperture.CameraHandler;
import mchorse.blockbuster.audio.AudioRenderer;
import mchorse.blockbuster.client.gui.GuiRecordingOverlay;
import mchorse.blockbuster.client.model.parsing.ModelExtrudedLayer;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.blockbuster.client.render.IRenderLast;
import mchorse.blockbuster.client.render.tileentity.TileEntityGunItemStackRenderer;
import mchorse.blockbuster.client.render.tileentity.TileEntityModelItemStackRenderer;
import mchorse.blockbuster.client.render.tileentity.TileEntityModelRenderer;
import mchorse.blockbuster.client.textures.GifTexture;
import mchorse.blockbuster.common.GunProps;
import mchorse.blockbuster.common.OrientedBB;
import mchorse.blockbuster.common.entity.EntityActor;
import mchorse.blockbuster.common.item.ItemGun;
import mchorse.blockbuster.common.tileentity.TileEntityModel;
import mchorse.blockbuster.recording.RecordPlayer;
import mchorse.blockbuster.recording.RecordRecorder;
import mchorse.blockbuster.recording.data.Frame;
import mchorse.blockbuster.recording.data.Record;
import mchorse.blockbuster.utils.EntityUtils;
import mchorse.blockbuster.utils.NBTUtils;
import mchorse.mclib.utils.Color;
import mchorse.mclib.utils.ColorUtils;
import mchorse.mclib.utils.Interpolations;
import mchorse.mclib.utils.OptifineHelper;
import net.minecraft.client.Minecraft;
import net.minecraft.client.entity.AbstractClientPlayer;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.client.model.ModelBiped;
import net.minecraft.client.model.ModelPlayer;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.OpenGlHelper;
import net.minecraft.client.renderer.RenderGlobal;
import net.minecraft.client.renderer.RenderHelper;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.block.model.ItemCameraTransforms;
import net.minecraft.client.renderer.tileentity.TileEntityRendererDispatcher;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import net.minecraft.entity.Entity;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EntitySelectors;
import net.minecraft.util.EnumHandSide;
import net.minecraft.util.ResourceLocation;
import net.minecraft.util.math.MathHelper;
import net.minecraftforge.client.MinecraftForgeClient;
import net.minecraftforge.client.event.EntityViewRenderEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.client.event.RenderHandEvent;
import net.minecraftforge.client.event.RenderLivingEvent;
import net.minecraftforge.client.event.RenderWorldLastEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.GL20;
import org.objectweb.asm.tree.MethodNode;
import scala.Int;
import javax.vecmath.Vector3d;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import java.util.Random;
import java.util.Set;
/**
* Rendering handler
*
* This handler is another handler in this mod that responsible for rendering.
* Currently this handler only renders recording overlay
*/
@SideOnly(Side.CLIENT)
public class RenderingHandler
{
private static EntityLivingBase lastItemHolder;
public static Set<Record> recordsToRender = new HashSet<Record>();
public static Set<OrientedBB> obbsToRender = new HashSet<OrientedBB>();
private static final List<EntityActor> renderedEntityActors = new ArrayList<>();
private static final List<IRenderLast> renderLasts = new ArrayList<>();
/** Runnables to be executed at the end of renderlast event */
private static final List<Runnable> renderLastBus = new ArrayList<>();
private static ListIterator<Runnable> renderLastBusIterator = renderLastBus.listIterator();
/**
* is true when renderLasts List is being iterated
*/
private static boolean isRenderingLast;
private boolean wasPaused;
/**
* Bedrock particle emitters
*/
private static final List<BedrockEmitter> emitters = new ArrayList<BedrockEmitter>();
private static final List<BedrockEmitter> emittersAdd = new ArrayList<BedrockEmitter>();
private static boolean emitterIsIterating;
private GuiRecordingOverlay overlay;
/**
* The transformType of the item currently rendered like TransformType.GUI, TransformType.GROUND, TransformType.THIRD_PERSON_RIGHT_HAND etc.
* This variable is set by {@link #setTSRTTransform(ItemCameraTransforms.TransformType)} which is called by ASM.
*/
public static ItemCameraTransforms.TransformType itemTransformType;
/**
* Add a renderLast object to the renderLast List. They will be rendered after entities.
* This method only adds the given object if the renderLast List is not being iterated
* @param renderLast
* @return true if added to the list, false if not added, for example, when RenderingHandler is currently rendering last.
*/
public static boolean addRenderLast(IRenderLast renderLast)
{
/* only add a render last object when the renderLasts List is not iterated */
if (!isRenderingLast)
{
renderLasts.add(renderLast);
return true;
}
return false;
}
/**
* Called by ASM in RenderGlobal.renderEntities() {@link mchorse.blockbuster.core.transformers.RenderGlobalTransformer}
* @param entity
*/
public static void addRenderedEntity(Entity entity)
{
if (entity instanceof EntityActor)
{
renderedEntityActors.add((EntityActor) entity);
}
}
/**
* Add a runnable that will be executed at the end of {@link #onRenderLast(RenderWorldLastEvent)}
*/
public static void registerRenderLastEvent(Runnable runnable)
{
renderLastBusIterator.add(runnable);
}
/**
* Render green sky, this is getting invoked from the ASM patched
* code in {@link RenderGlobal}
*/
public static void renderGreenSky()
{
int color = Blockbuster.chromaSkyColor.get();
float skyR = (color >> 16 & 0xff) / 255F;
float skyG = (color >> 8 & 0xff) / 255F;
float skyB = (color & 0xff) / 255F;
float skyA = (color >> 24 & 0xff) / 255F;
GlStateManager.clearColor(skyR, skyG, skyB, skyA);
GlStateManager.clear(GL11.GL_COLOR_BUFFER_BIT);
GL11.glDisable(GL11.GL_FOG);
}
/**
* Check whether it's time to render green sky, this is getting
* invoked from ASM patched code in {@link RenderGlobal}
*/
public static boolean isGreenSky()
{
return Blockbuster.chromaSky.get();
}
/**
* Render lit particles (call by ASM, but not used for anything yet...
* I might use it for morph based Snowstorm system)...
*/
public static void renderLitParticles(float partialTicks)
{}
/**
* Render BB gun рands
*/
public static void changePlayerHand(AbstractClientPlayer player, ModelPlayer modelPlayer)
{
ItemStack itemstack = player.getHeldItemMainhand();
ModelBiped.ArmPose armPose = ModelBiped.ArmPose.EMPTY;
if (!itemstack.isEmpty() && itemstack.getItem() instanceof ItemGun)
{
GunProps props = NBTUtils.getGunProps(itemstack);
if (props.alwaysArmsShootingPose)
{
armPose = ModelBiped.ArmPose.BOW_AND_ARROW;
}
else
{
if (props.enableArmsShootingPose)
{
if (KeyboardHandler.gunShoot.isKeyDown())
{
armPose = ModelBiped.ArmPose.BOW_AND_ARROW;
}
}
}
}
if (player.getPrimaryHand() == EnumHandSide.RIGHT)
{
modelPlayer.rightArmPose = armPose;
}
else
{
modelPlayer.leftArmPose = armPose;
}
}
/**
* Render particle emitters (called by ASM)
*/
public static void renderParticles(float partialTicks)
{
if (!emitters.isEmpty())
{
if (Blockbuster.snowstormDepthSorting.get())
{
emitters.sort((a, b) ->
{
double ad = a.getDistanceSq();
double bd = b.getDistanceSq();
if (ad < bd)
{
return 1;
}
else if (ad > bd)
{
return -1;
}
return 0;
});
}
emitterIsIterating = true;
for (BedrockEmitter emitter : emitters)
{
emitter.render(partialTicks);
emitter.running = emitter.sanityTicks < 2;
}
addEmitters();
emitterIsIterating = false;
}
}
public static void addEmitter(BedrockEmitter emitter, EntityLivingBase target)
{
if (!emitter.added)
{
if (emitterIsIterating)
{
emittersAdd.add(emitter);
}
else
{
emitters.add(emitter);
}
emitter.added = true;
emitter.setTarget(target);
}
}
private static void addEmitters()
{
if (!emittersAdd.isEmpty())
{
emitters.addAll(emittersAdd);
emittersAdd.clear();
}
}
public static void updateEmitters()
{
List<BedrockEmitter> emittersRemove = new ArrayList<>();
emitterIsIterating = true;
for(BedrockEmitter emitter : emitters)
{
emitter.update();
if (emitter.isFinished())
{
emittersRemove.add(emitter);
emitter.added = false;
}
}
if (!emittersRemove.isEmpty())
{
emitters.removeAll(emittersRemove);
}
addEmitters();
emitterIsIterating = false;
}
public static void resetEmitters()
{
emitters.clear();
}
/**
* Called by ASM {@link mchorse.blockbuster.core.transformers.RenderGlobalTransformer}
* to render the entities that should be depth sorted after tileentities and entities have been rendered
*/
public static void renderLastEntities()
{
if (MinecraftForgeClient.getRenderPass() != 0)
{
renderLasts.clear();
renderedEntityActors.clear();
return;
}
Minecraft mc = Minecraft.getMinecraft();
Entity camera = mc.getRenderViewEntity();
/* render always actors that have not been rendered */
if (Blockbuster.actorAlwaysRender.get())
{
List<EntityActor> actors = mc.world.getEntities(EntityActor.class, EntitySelectors.IS_ALIVE);
actors.removeAll(renderedEntityActors);
actors.removeAll(renderLasts);
/*
* Add them to renderLast
* because renderLast entities that are out of range won't be added to renderLast
*/
renderLasts.addAll(actors);
}
/* render entities and tileEntities last */
renderLasts.sort((a, b) ->
{
Vector3d aPos = a.getRenderLastPos();
Vector3d bPos = b.getRenderLastPos();
double dist1 = camera.getDistanceSq(aPos.x, aPos.y, aPos.z);
double dist2 = camera.getDistanceSq(bPos.x, bPos.y, bPos.z);
return dist1 == dist2 ? 0 : (dist2 - dist1 > 0 ? 1 : -1);
});
isRenderingLast = true;
for (IRenderLast renderLast : renderLasts)
{
if (renderLast instanceof EntityActor)
{
/*
* Optifine calls net.optifine.shaders.Shaders.nextEntity before entity is rendered
* Without this the lighting / shadows are weird on renderLast models
*/
OptifineHelper.nextEntity((EntityActor) renderLast);
mc.getRenderManager().renderEntityStatic((EntityActor) renderLast, mc.getRenderPartialTicks(), false);
}
else if (renderLast instanceof TileEntityModel)
{
/*
* Optifine calls net.optifine.shaders.Shaders.nextBlockEntity before tileEntity is rendered
* Without this the lighting / shadows are weird on renderLast models
*/
OptifineHelper.nextBlockEntity((TileEntityModel) renderLast);
TileEntityRendererDispatcher.instance.render((TileEntityModel) renderLast, mc.getRenderPartialTicks(), -1);
}
}
isRenderingLast = false;
renderLasts.clear();
renderedEntityActors.clear();
}
/**
* Called by ASM
*/
public static void setLastItemHolder(EntityLivingBase entity)
{
if (lastItemHolder == null)
{
lastItemHolder = entity;
}
}
/**
* Called by ASM {@link mchorse.blockbuster.core.transformers.RenderItemTransformer}
* and sets the transform type of the currently rendered item
* Called in renderItem, renderItemModel and renderItemModelIntoGUI method of Minecraft.
*/
public static void setTSRTTransform(ItemCameraTransforms.TransformType type)
{
itemTransformType = type;
}
/**
* Called by ASM {@link mchorse.blockbuster.core.transformers.RenderItemTransformer}.
* This method sets the entity that is holding the item which is currently rendered.
* Called in renderItem method of RenderItem class.
*/
public static void resetLastItemHolder(EntityLivingBase entity)
{
if (lastItemHolder == entity)
{
lastItemHolder = null;
}
}
public static EntityLivingBase getLastItemHolder()
{
return lastItemHolder;
}
public RenderingHandler(GuiRecordingOverlay overlay)
{
this.overlay = overlay;
}
/**
* Fixes lightmap for TEISR
*/
@SubscribeEvent
public void onHUDRender(RenderGameOverlayEvent.Pre event)
{
if (event.getType() == RenderGameOverlayEvent.ElementType.ALL)
{
Minecraft.getMinecraft().entityRenderer.enableLightmap();
OpenGlHelper.setLightmapTextureCoords(OpenGlHelper.lightmapTexUnit, 240, 240);
Minecraft.getMinecraft().entityRenderer.disableLightmap();
}
}
/**
* Renders recording overlay during HUD rendering
*/
@SubscribeEvent
public void onHUDRender(RenderGameOverlayEvent.Post event)
{
ScaledResolution resolution = event.getResolution();
if (event.getType() == RenderGameOverlayEvent.ElementType.ALL)
{
int w = resolution.getScaledWidth();
int h = resolution.getScaledHeight();
this.overlay.draw(w, h);
if (!CameraHandler.isCameraEditorOpen())
{
int width = (int) (w * Blockbuster.audioWaveformWidth.get());
AudioRenderer.renderAll((w - width) / 2, h / 2 + h / 4, width, Blockbuster.audioWaveformHeight.get(), w, h);
}
}
}
/**
* Add Blockbuster debug strings, such as length of client records and
* recording information, to the debug overlay.
*/
@SubscribeEvent
public void onHUDRender(RenderGameOverlayEvent.Text event)
{
if (!Minecraft.getMinecraft().gameSettings.showDebugInfo)
{
return;
}
List<String> list = event.getLeft();
list.add("");
list.add(ClientProxy.manager.records.size() + " client records");
RecordRecorder recorder = ClientProxy.manager.recorders.get(Minecraft.getMinecraft().player);
if (recorder != null)
{
list.add("Recording frame " + recorder.tick);
}
}
/**
* On render last world event, this bad boy will tick all of the GIF
* textures which were registered, and will keep track of audio
*/
@SubscribeEvent
public void onRenderLast(RenderWorldLastEvent event)
{
ModelExtrudedLayer.tickCache();
Minecraft mc = Minecraft.getMinecraft();
boolean isPaused = mc.isGamePaused();
if (this.wasPaused != isPaused)
{
ClientProxy.audio.pause(isPaused);
this.wasPaused = isPaused;
}
/* render actor paths */
if (mc.gameSettings.showDebugInfo && !recordsToRender.isEmpty() && Blockbuster.recordRenderDebugPaths.get())
{
renderPaths(event, recordsToRender);
}
recordsToRender.clear();
/* TODO render OBB outlines (move this code to limb renderer or so, later)*/
if (mc.gameSettings.showDebugInfo && !obbsToRender.isEmpty())
{
for (OrientedBB obb : this.obbsToRender)
{
obb.render(event);
}
}
obbsToRender.clear();
renderLastBusIterator = renderLastBus.listIterator();
while (renderLastBusIterator.hasNext())
{
Runnable runnable = renderLastBusIterator.next();
runnable.run();
}
renderLastBus.clear();
renderLastBusIterator = renderLastBus.listIterator();
}
private void renderPaths(RenderWorldLastEvent event, Set<Record> recordsToRender)
{
int shader = GL11.glGetInteger(GL20.GL_CURRENT_PROGRAM);
if (shader != 0)
{
OpenGlHelper.glUseProgram(0);
}
final int delta = 2;
Color color = ColorUtils.COLOR;
Entity player = Minecraft.getMinecraft().getRenderViewEntity();
Random random = new Random();
double playerX = player.prevPosX + (player.posX - player.prevPosX) * event.getPartialTicks();
double playerY = player.prevPosY + (player.posY - player.prevPosY) * event.getPartialTicks();
double playerZ = player.prevPosZ + (player.posZ - player.prevPosZ) * event.getPartialTicks();
GlStateManager.glLineWidth(2F);
GlStateManager.disableLighting();
GlStateManager.disableTexture2D();
for (Record record : recordsToRender)
{
int length = record.frames.size();
if (length < delta + 1)
{
continue;
}
random.setSeed(record.filename.hashCode());
random.setSeed(random.nextLong());
int hex = MathHelper.hsvToRGB(random.nextFloat(), 1F, 1F);
color.set(hex, false);
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder builder = tessellator.getBuffer();
builder.setTranslation(-playerX, -playerY, -playerZ);
builder.begin(GL11.GL_LINES, DefaultVertexFormats.POSITION_COLOR);
for (int i = delta; i < length; i += delta)
{
Frame prev = record.frames.get(i - delta);
Frame current = record.frames.get(i);
builder.pos(prev.x, prev.y + 1F, prev.z).color(color.r, color.g, color.b, color.a).endVertex();
builder.pos(current.x, current.y + 1F, current.z).color(color.r, color.g, color.b, color.a).endVertex();
}
builder.setTranslation(0, 0, 0);
tessellator.draw();
}
GlStateManager.enableTexture2D();
GlStateManager.enableLighting();
GlStateManager.glLineWidth(1F);
if (shader != 0)
{
OpenGlHelper.glUseProgram(shader);
}
}
@SubscribeEvent
public void onOrientCamera(EntityViewRenderEvent.CameraSetup event)
{
EntityPlayer thePlayer = Minecraft.getMinecraft().player;
RecordPlayer player = EntityUtils.getRecordPlayer(thePlayer);
if (player != null && player.record != null && !player.record.frames.isEmpty())
{
Frame frame = player.record.getFrameSafe(player.tick);
Frame prev = player.record.getFrameSafe(player.tick - 1);
float partial = (float) event.getRenderPartialTicks();
event.setYaw(Interpolations.lerp(prev.yawHead, frame.yawHead, partial) - 180);
event.setPitch(Interpolations.lerp(prev.pitch, frame.pitch, partial));
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onRenderHand(RenderHandEvent event)
{
EntityPlayer thePlayer = Minecraft.getMinecraft().player;
RecordPlayer player = EntityUtils.getRecordPlayer(thePlayer);
if (player != null && player.record != null && !player.record.frames.isEmpty())
{
Frame frame = player.record.getFrameSafe(player.tick);
Frame prev = player.record.getFrameSafe(player.tick - 1);
float partial = event.getPartialTicks();
float yaw = Interpolations.lerp(prev.yaw, frame.yaw, partial);
float pitch = Interpolations.lerp(prev.pitch, frame.pitch, partial);
thePlayer.rotationYaw = yaw;
thePlayer.rotationPitch = pitch;
thePlayer.prevRotationYaw = yaw;
thePlayer.prevRotationPitch = pitch;
}
}
@SubscribeEvent
public void onPreRenderEntity(RenderLivingEvent.Pre event)
{
GifTexture.entityTick = event.getEntity().ticksExisted;
}
@SubscribeEvent
public void onPostRenderEntity(RenderLivingEvent.Post event)
{
GifTexture.entityTick = -1;
}
} | 22,473 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
ActorsPack.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/ActorsPack.java | package mchorse.blockbuster.client;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.imageio.ImageIO;
import com.google.common.collect.ImmutableSet;
import jdk.nashorn.internal.ir.Block;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.CommonProxy;
import mchorse.blockbuster.api.ModelPack;
import mchorse.blockbuster.client.textures.GifProcessThread;
import mchorse.blockbuster.client.textures.URLDownloadThread;
import mchorse.blockbuster.utils.mclib.GifFolder;
import mchorse.blockbuster.utils.mclib.GifFrameFile;
import mchorse.mclib.utils.resources.RLUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.IResourcePack;
import net.minecraft.client.resources.data.IMetadataSection;
import net.minecraft.client.resources.data.MetadataSerializer;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Actors pack
*
* This class allows players to customize their actors with custom models and
* skins.
*
* This class is used both on server and on client. I just realized that you
* can't use IResourcePack on server...
*/
@SideOnly(Side.CLIENT)
public class ActorsPack implements IResourcePack
{
private static final Pattern GifFrameNSPattern = Pattern.compile("^(.*)\\.gif>\\/frame(\\d+)(_n|_s)\\.png$");
/**
* Cached last file from {@link #resourceExists(ResourceLocation)}
* method
*/
private File lastFile;
/* IResourcePack implementation */
/**
* Read a resource from model pack
*/
@Override
public InputStream getInputStream(ResourceLocation location) throws IOException
{
String domain = location.getResourceDomain();
String path = location.getResourcePath();
if ((domain.equals("http") || domain.equals("https")) && path.startsWith("//") && !path.endsWith(".mcmeta"))
{
return this.hanldeURLSkins(location);
}
File fileFile = this.lastFile;
/* In case this pack was used without checking for resource
* in other method first, find the file */
if (fileFile == null)
{
for (File file : Blockbuster.proxy.pack.folders)
{
File packFile = null;
if (path.contains(".gif>/"))
{
Matcher matcher = GifFrameNSPattern.matcher(path);
if (matcher.find())
{
String pathPart = matcher.group(1);
String index = matcher.group(2);
String type = matcher.group(3);
File gifNS = new File(file, pathPart + type + ".gif");
if (gifNS.exists())
{
packFile = new GifFrameFile(file, pathPart + type + ".gif>/frame" + index + ".png");
}
else
{
/* This is what Optifine will to do without this mod. */
packFile = new File(file, pathPart + ".gif" + type + ".png");
}
}
else
{
packFile = new GifFrameFile(file, path);
}
}
else
{
packFile = new File(file, path);
}
if (packFile.exists())
{
fileFile = packFile;
break;
}
}
}
if (fileFile != null)
{
this.lastFile = null;
if (fileFile instanceof GifFrameFile)
{
GifFrameFile frame = (GifFrameFile) fileFile;
GifFolder image = frame.parent;
if (image.exists())
{
String gifPath = location.getResourcePath();
gifPath = gifPath.substring(0, gifPath.lastIndexOf('>'));
this.handleGif(RLUtils.create(location.getResourceDomain(), gifPath), image);
}
return new FileInputStream(new File(image.getFilePath()));
}
else
{
if (path.toLowerCase().endsWith(".gif"))
{
GifFolder gifFile = new GifFolder(fileFile.getPath());
if (gifFile.exists())
{
this.handleGif(location, gifFile);
}
}
return new FileInputStream(fileFile);
}
}
throw new FileNotFoundException(location.toString());
}
/**
* Handle creation of GIF texture
*/
private void handleGif(ResourceLocation location, GifFolder gif)
{
if (GifProcessThread.THREADS.containsKey(location))
{
return;
}
new Thread(() ->
{
Minecraft.getMinecraft().addScheduledTask(() -> GifProcessThread.create(location, gif));
}).start();
}
/**
* Handle URL skins
*/
private InputStream hanldeURLSkins(ResourceLocation location)
{
try
{
if (Blockbuster.syncedURLTextureDownload.get())
{
InputStream stream = URLDownloadThread.downloadImage(location);
if (stream == null)
{
throw new IOException("Couldn't download image...");
}
return stream;
}
else
{
new Thread(new URLDownloadThread(location)).start();
}
}
catch (IOException e)
{}
/* Make it a black pixel in case it fails */
return ActorsPack.class.getResourceAsStream("/assets/blockbuster/textures/blocks/black.png");
}
/**
* Check if resource is available in the model pack. This method
* also supports old mapping method for model skins
*/
@Override
public boolean resourceExists(ResourceLocation location)
{
/* Handle skin URLs */
String domain = location.getResourceDomain();
String path = location.getResourcePath();
/* Only actual HTTP URL can go here, also ignore mcmeta data */
if ((domain.equals("http") || domain.equals("https")) && path.startsWith("//") && !path.endsWith(".mcmeta"))
{
return true;
}
/* Handle models path */
for (File file : Blockbuster.proxy.pack.folders)
{
if (path.contains(".gif>/"))
{
Matcher matcher = GifFrameNSPattern.matcher(path);
if (matcher.find())
{
String pathPart = matcher.group(1);
String index = matcher.group(2);
String type = matcher.group(3);
File gifNS = new File(file, pathPart + type + ".gif");
if (gifNS.exists())
{
this.lastFile = new GifFrameFile(file, pathPart + type + ".gif>/frame" + index + ".png");
}
else
{
this.lastFile = new File(file, pathPart + ".gif" + type + ".png");
}
}
else
{
this.lastFile = new GifFrameFile(file, path);
}
}
else
{
this.lastFile = new File(file, path);
}
if (this.lastFile.exists())
{
return true;
}
}
this.lastFile = null;
return false;
}
/**
* Get resource domains
*
* Having multiple domains seems like a nice idea for aliases.
* I'm totally using it for URL skins
*/
@Override
public Set<String> getResourceDomains()
{
return ImmutableSet.<String>of("b.a", "http", "https");
}
@Override
public String getPackName()
{
return "Blockbuster's Actor Pack";
}
/**
* Get pack metadata
*
* This method is returns null, because it isn't an actual resource pack, but
* just a way to pass resources into minecraft core.
*
* Either Jabelar or TheGreyGhost mentioned that returning null in this
* method, disable listing of this resource pack in the resource pack menu.
* Seems legit to me.
*/
@Override
public <T extends IMetadataSection> T getPackMetadata(MetadataSerializer metadataSerializer, String metadataSectionName) throws IOException
{
return null;
}
/**
* I don't think that my actor resources pack should have an icon.
* However that icon would look really badass/sexy.
*/
@Override
public BufferedImage getPackImage() throws IOException
{
return null;
}
} | 9,439 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiRecordingOverlay.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/GuiRecordingOverlay.java | package mchorse.blockbuster.client.gui;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.recording.RecordRecorder;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.FontRenderer;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.ResourceLocation;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Recording GUI overlay
*
* This class is responsible for rendering red circle (like the icon that
* represents recording in progress) and name of the recording file.
*/
@SideOnly(Side.CLIENT)
public class GuiRecordingOverlay extends Gui
{
public static final ResourceLocation TEXTURE = new ResourceLocation(Blockbuster.MOD_ID, "textures/gui/recording.png");
protected Minecraft mc;
protected String caption;
protected boolean isVisible = false;
protected boolean recording = false;
public GuiRecordingOverlay(Minecraft mc)
{
this.mc = mc;
}
/* Public API */
public void setCaption(String caption, boolean recording)
{
this.caption = recording ? I18n.format("blockbuster.recording", caption) : caption;
this.recording = recording;
}
public void setVisible(boolean isVisible)
{
this.isVisible = isVisible;
}
/* Rendering code */
/**
* Draw recording overlay if the recording in the process in top-left corner
* of the screen.
*
* Thanks to coolAlias and to his tutorial github repo for this rendering
* code.
*/
public void draw(int width, int height)
{
if (!this.isVisible)
{
return;
}
FontRenderer font = this.mc.fontRenderer;
String caption = this.caption;
if (this.recording)
{
RecordRecorder recorder = ClientProxy.manager.recorders.get(Minecraft.getMinecraft().player);
if (recorder != null)
{
caption += "§r (§l" + (recorder.tick + recorder.offset) + "§r)";
}
}
this.mc.renderEngine.bindTexture(TEXTURE);
GlStateManager.pushAttrib();
GlStateManager.color(1.0F, 1.0F, 1.0F, 1.0F);
this.drawTexturedModalRect(4, 4, 0, 0, 16, 16);
font.drawStringWithShadow(caption, 22, 8, 0xffffffff);
GlStateManager.popAttrib();
}
} | 2,512 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiImmersiveMorphMenu.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/GuiImmersiveMorphMenu.java | package mchorse.blockbuster.client.gui;
import java.util.Stack;
import java.util.function.Consumer;
import java.util.function.Function;
import javax.vecmath.Matrix4f;
import javax.vecmath.Vector3f;
import org.lwjgl.input.Keyboard;
import mchorse.blockbuster.common.entity.EntityActor;
import mchorse.blockbuster.recording.data.Frame;
import mchorse.blockbuster_pack.client.gui.GuiSequencerMorph.GuiSequencerMorphRenderer;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.GuiModelRenderer;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.MathUtils;
import mchorse.metamorph.api.EntityUtils;
import mchorse.metamorph.api.MorphAPI;
import mchorse.metamorph.api.MorphUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import mchorse.metamorph.client.gui.creative.GuiCreativeMorphsMenu;
import mchorse.metamorph.client.gui.creative.GuiMorphRenderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraftforge.client.event.EntityViewRenderEvent.FOVModifier;
import net.minecraftforge.client.event.EntityViewRenderEvent;
import net.minecraftforge.client.event.RenderGameOverlayEvent;
import net.minecraftforge.fml.common.eventhandler.EventPriority;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.common.gameevent.TickEvent.Phase;
import net.minecraftforge.fml.common.gameevent.TickEvent.RenderTickEvent;
/**
* Immersive morph menu
*
* It is the actual executor that synchronizes the model editing process to the game world
*/
public class GuiImmersiveMorphMenu extends GuiCreativeMorphsMenu
{
public boolean immersionMode = true;
public EntityLivingBase target;
public Consumer<GuiImmersiveMorphMenu> updateCallback;
public boolean hideGuiModel = true;
public Function<Integer, Frame> frameProvider;
public Consumer<GuiContext> beforeRender;
public Consumer<GuiContext> afterRender;
private PreviewMorph preview = new PreviewMorph();
private AbstractMorph lastMorph;
private Stack<Boolean> stack = new Stack<>();
public GuiImmersiveMorphMenu(Minecraft mc)
{
super(mc, true, null);
GuiButtonElement close = new GuiButtonElement(mc, IKey.str("X"), (b) -> this.exit());
close.flex().w(20);
this.bar.add(close);
this.keys().register(IKey.lang("blockbuster.gui.morphs.keys.toggle_gui_model"), Keyboard.KEY_F3, () -> this.hideGuiModel = !this.hideGuiModel)
.category(GuiImmersiveEditor.CATEGORY).active(() -> this.isImmersionMode());
}
@Override
public void nestEdit(AbstractMorph selected, boolean editing, boolean keepViewport, Consumer<AbstractMorph> callback)
{
this.stack.add(this.immersionMode);
this.immersionMode &= keepViewport;
super.nestEdit(selected, editing, keepViewport, callback);
}
@Override
public void restoreEdit()
{
super.restoreEdit();
this.immersionMode = this.stack.pop();
}
@Override
public void exit()
{
if (this.isEditMode() || this.isNested())
{
if (this.isEditMode())
{
this.editor.delegate.renderer.fov = 70F;
}
super.exit();
}
else
{
((GuiImmersiveEditor) mc.currentScreen).closeThisScreen();
}
}
@Override
public void finish()
{
super.finish();
this.frameProvider = null;
this.beforeRender = null;
this.afterRender = null;
this.pickMorph(getSelected());
}
@Override
public void draw(GuiContext context)
{
if (!this.isImmersionMode())
{
Gui.drawRect(this.area.x, this.area.y, this.area.ex(), this.area.ey(), 0x33000000);
}
if (this.isEditMode())
{
this.refreshImmersive();
}
super.draw(context);
}
@Override
protected void beforeRenderModel(GuiContext context)
{
super.beforeRenderModel(context);
if (this.isImmersionMode() && this.beforeRender != null)
{
this.beforeRender.accept(context);
}
}
@Override
protected void afterRenderModel(GuiContext context)
{
super.afterRenderModel(context);
if (this.isImmersionMode() && this.afterRender != null)
{
this.afterRender.accept(context);
}
}
public Frame getFrame(int tick)
{
if (this.frameProvider != null && !this.isNested())
{
return this.frameProvider.apply(tick);
}
else
{
return null;
}
}
@SubscribeEvent
public void onRenderTick(RenderTickEvent event)
{
if (this.isEditMode() && this.immersionMode && event.phase == Phase.START)
{
this.preview.renderComplete = false;
if (this.updateCallback != null)
{
this.updateCallback.accept(this);
}
}
if (this.isImmersionMode())
{
if (event.phase == Phase.START)
{
this.lastMorph = EntityUtils.getMorph(this.target);
if (this.target instanceof EntityActor)
{
((EntityActor) this.target).morph.setDirect(this.preview);
}
else if (this.target instanceof EntityPlayer)
{
MorphAPI.morph((EntityPlayer) this.target, this.preview, true);
}
GuiModelRenderer renderer = this.editor.delegate.renderer;
Vector3f temp = new Vector3f(renderer.pos);
Vector3f vec = new Vector3f();
vec.set(0.0F, 0.0F, (renderer.flight ? 0F : -renderer.scale) - 0.05F);
renderer.pitch = MathUtils.clamp(renderer.pitch, -90F, 90F);
Matrix4f mat = new Matrix4f();
mat.rotX(renderer.pitch / 180.0F * 3.1415927F);
mat.transform(vec);
mat.rotY((180.0F - renderer.yaw) / 180.0F * 3.1415927F);
mat.transform(vec);
temp.x += vec.x;
temp.y += vec.y;
temp.z += vec.z;
mat.rotY(-target.rotationYaw / 180.0F * 3.1415927F);
mat.transform(temp);
temp.x += this.target.posX;
temp.y += this.target.posY;
temp.z += this.target.posZ;
EntityPlayer camera = this.mc.player;
camera.setPositionAndRotation(temp.x, Math.max(temp.y - camera.getEyeHeight(), -64.0), temp.z, renderer.yaw + target.rotationYaw + 180, renderer.pitch);
camera.setLocationAndAngles(temp.x, Math.max(temp.y - camera.getEyeHeight(), -64.0), temp.z, renderer.yaw + target.rotationYaw + 180, renderer.pitch);
camera.motionX = camera.motionY = camera.motionZ = 0;
}
else
{
if (this.target instanceof EntityActor)
{
((EntityActor) this.target).morph.setDirect(this.lastMorph);
}
else if (this.target instanceof EntityPlayer)
{
MorphAPI.morph((EntityPlayer) this.target, this.lastMorph, true);
}
}
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onFovModifierEvent(FOVModifier event)
{
if (this.isImmersionMode())
{
event.setFOV(this.editor.delegate.renderer.fov);
}
}
@SubscribeEvent(priority = EventPriority.LOWEST)
public void onCameraOrient(EntityViewRenderEvent.CameraSetup event)
{
if (this.isImmersionMode())
{
event.setRoll(0F);
}
}
@SubscribeEvent
public void onRenderGameOverlayEvent(RenderGameOverlayEvent event)
{
event.setCanceled(true);
}
public void refreshImmersive()
{
GuiModelRenderer renderer = this.editor.delegate.renderer;
renderer.hideModel = this.isImmersionMode() && this.preview.renderComplete && this.hideGuiModel && (!this.doRenderOnionSkin || !this.haveOnionSkin());
renderer.customEntity = this.isImmersionMode();
renderer.fullScreen = this.isImmersionMode();
if (renderer.customEntity)
{
renderer.entityPitch = this.target.rotationPitch;
renderer.entityYawHead = this.target.rotationYawHead - this.target.rotationYaw;
renderer.entityYawBody = this.target.renderYawOffset - this.target.rotationYaw;
renderer.entityTicksExisted = this.target.ticksExisted;
}
}
public boolean isImmersionMode()
{
return this.isEditMode() && this.immersionMode && this.target != null;
}
public class PreviewMorph extends AbstractMorph
{
public boolean renderComplete;
@Override
public void renderOnScreen(EntityPlayer player, int x, int y, float scale, float alpha)
{}
@Override
public void render(EntityLivingBase entity, double x, double y, double z, float entityYaw, float partialTicks)
{
this.renderComplete = true;
GuiImmersiveMorphMenu menu = GuiImmersiveMorphMenu.this;
AbstractMorph morph = menu.editor.delegate.morph;
GuiModelRenderer renderer = menu.editor.delegate.renderer;
if (renderer instanceof GuiSequencerMorphRenderer)
{
GuiContext context = GuiBase.getCurrent();
context.partialTicks = GuiImmersiveMorphMenu.this.mc.getRenderPartialTicks();
((GuiSequencerMorphRenderer) renderer).doRender(GuiBase.getCurrent(), entity, x, y, z);
morph = null;
}
else if (renderer instanceof GuiMorphRenderer)
{
morph = ((GuiMorphRenderer) renderer).morph;
}
if (morph != null)
{
MorphUtils.render(morph, entity, x, y, z, entityYaw, partialTicks);
}
}
@Override
public AbstractMorph create()
{
return null;
}
@Override
public float getWidth(EntityLivingBase target)
{
return 0;
}
@Override
public float getHeight(EntityLivingBase target)
{
return 0;
}
}
}
| 10,832 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiActor.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/GuiActor.java | package mchorse.blockbuster.client.gui;
import mchorse.blockbuster.common.entity.EntityActor;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.PacketModifyActor;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.metamorph.client.gui.creative.GuiCreativeMorphsMenu;
import mchorse.metamorph.client.gui.creative.GuiMorphRenderer;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
public class GuiActor extends GuiBase
{
public GuiMorphRenderer renderer;
public GuiButtonElement pick;
public GuiCreativeMorphsMenu morphs;
private EntityActor actor;
public GuiActor(Minecraft mc, EntityActor actor)
{
this.actor = actor;
this.renderer = new GuiMorphRenderer(mc);
this.renderer.morph = actor.morph.get();
this.renderer.flex().reset().relative(this.viewport).wh(1F, 1F);
this.pick = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.pick"), (button) ->
{
this.morphs.resize();
this.morphs.setSelected(this.renderer.morph);
this.root.add(this.morphs);
});
this.pick.flex().relative(this.viewport).x(0.5F).y(1F, -10).w(100).anchor(0.5F, 1F);
this.morphs = new GuiCreativeMorphsMenu(mc, (morph) -> this.renderer.morph = morph);
this.morphs.flex().reset().relative(this.viewport).wh(1F, 1F);
this.root.add(this.renderer, this.pick);
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
@Override
protected void closeScreen()
{
this.actor.morph.setDirect(this.renderer.morph);
Dispatcher.sendToServer(new PacketModifyActor(this.actor));
super.closeScreen();
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
this.drawDefaultBackground();
this.drawCenteredString(this.context.font, I18n.format("blockbuster.gui.actor.title"), this.width / 2, 16, 0xffffff);
super.drawScreen(mouseX, mouseY, partialTicks);
}
} | 2,224 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiGun.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/GuiGun.java | package mchorse.blockbuster.client.gui;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.GuiPoseTransformations;
import mchorse.blockbuster.client.render.tileentity.TileEntityGunItemStackRenderer;
import mchorse.blockbuster.common.GunProps;
import mchorse.blockbuster.common.entity.EntityGunProjectile;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.guns.PacketGunInfo;
import mchorse.blockbuster.utils.NBTUtils;
import mchorse.blockbuster.utils.mclib.BBIcons;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.GuiModelRenderer;
import mchorse.mclib.client.gui.framework.elements.GuiPanelBase;
import mchorse.mclib.client.gui.framework.elements.GuiScrollElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiSlotElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.client.gui.utils.Area;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.ScrollDirection;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.ColorUtils;
import mchorse.mclib.utils.MathUtils;
import mchorse.metamorph.api.MorphManager;
import mchorse.metamorph.api.MorphUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import mchorse.metamorph.client.gui.creative.GuiCreativeMorphsMenu;
import mchorse.metamorph.client.gui.creative.GuiMorphRenderer;
import mchorse.metamorph.client.gui.creative.GuiNestedEdit;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.inventory.EntityEquipmentSlot;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.JsonToNBT;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import org.lwjgl.input.Keyboard;
import org.lwjgl.opengl.GL11;
@SideOnly(Side.CLIENT)
public class GuiGun extends GuiBase
{
public GunProps props;
public int index;
public GuiPanelBase<GuiElement> panel;
/* Morphs configuration */
public GuiCreativeMorphsMenu morphs;
/* Gun options */
public GuiElement gunOptions;
public GuiNestedEdit pickDefault;
public GuiNestedEdit pickFiring;
public GuiTextElement fireCommand;
public GuiTrackpadElement delay;
public GuiTrackpadElement projectiles;
public GuiTrackpadElement scatterX;
public GuiTrackpadElement scatterY;
public GuiToggleElement launch;
public GuiToggleElement useTarget;
public GuiSlotElement ammoStack;
/* Projectile options */
public GuiElement projectileOptions;
public GuiNestedEdit pickProjectile;
public GuiTextElement tickCommand;
public GuiTrackpadElement ticking;
public GuiTrackpadElement lifeSpan;
public GuiToggleElement yaw;
public GuiToggleElement pitch;
public GuiToggleElement sequencer;
public GuiToggleElement random;
public GuiTrackpadElement hitboxX;
public GuiTrackpadElement hitboxY;
public GuiTrackpadElement speed;
public GuiTrackpadElement friction;
public GuiTrackpadElement gravity;
public GuiTrackpadElement fadeIn;
public GuiTrackpadElement fadeOut;
/* Evanechecssss' options */
public GuiElement aimOptions;
public GuiToggleElement staticRecoil;
public GuiTrackpadElement recoilXMin;
public GuiTrackpadElement recoilXMax;
public GuiTrackpadElement recoilYMin;
public GuiTrackpadElement recoilYMax;
public GuiToggleElement enableArmsShootingPose;
public GuiToggleElement alwaysArmsShootingPose;
public GuiTrackpadElement shootOffsetX;
public GuiTrackpadElement shootOffsetY;
public GuiTrackpadElement shootOffsetZ;
public GuiNestedEdit pickCrosshairMorph;
public GuiNestedEdit pickInventoryMorph;
public GuiNestedEdit pickHandsMorph;
public GuiNestedEdit pickReloadMorph;
public GuiNestedEdit pickZoomOverlayMorph;
public GuiToggleElement hideCrosshairOnZoom;
public GuiToggleElement useInventoryMorph;
public GuiToggleElement hideHandsOnZoom;
public GuiToggleElement useZoomOverlayMorph;
public GuiTrackpadElement zoomFactor;
public GuiTrackpadElement ammo;
public GuiToggleElement useReloading;
public GuiTrackpadElement reloadingTime;
public GuiToggleElement shootWhenHeld;
public GuiTrackpadElement shotDelay;
/* Evanechecssss's options (page 2) */
public GuiElement aimOptionsSecond;
public GuiTextElement destroyCommand;
public GuiTextElement meleeCommand;
public GuiTextElement reloadCommand;
public GuiTextElement zoomOnCommand;
public GuiTextElement zoomOffCommand;
public GuiTrackpadElement meleeDamage;
public GuiTrackpadElement mouseZoom;
public GuiTrackpadElement durability;
public GuiToggleElement preventLeftClick;
public GuiToggleElement preventRightClick;
public GuiToggleElement preventEntityAttack;
/* Impact options */
public GuiElement impactOptions;
public GuiNestedEdit pickImpact;
public GuiTextElement impactCommand;
public GuiTextElement impactEntityCommand;
public GuiTrackpadElement impactDelay;
public GuiToggleElement vanish;
public GuiToggleElement bounce;
public GuiToggleElement sticks;
public GuiTrackpadElement hits;
public GuiTrackpadElement damage;
public GuiTrackpadElement knockbackHorizontal;
public GuiTrackpadElement knockbackVertical;
public GuiTrackpadElement bounceFactor;
public GuiTextElement vanishCommand;
public GuiTrackpadElement vanishDelay;
public GuiTrackpadElement penetration;
public GuiToggleElement ignoreBlocks;
public GuiToggleElement ignoreEntities;
/* Transforms */
public GuiElement transformOptions;
public GuiPoseTransformations gun;
public GuiPoseTransformations projectile;
public GuiMorphRenderer arms;
public GuiProjectileModelRenderer bullet;
/* First person transform */
public GuiElement transformFirstPersonOptions;
public GuiPoseTransformations gunFirstPerson;
public GuiGun(ItemStack stack)
{
TileEntityGunItemStackRenderer.GunEntry entry = TileEntityGunItemStackRenderer.models.get(stack);
if (entry == null)
{
this.props = NBTUtils.getGunProps(stack);
}
else
{
this.props = entry.props;
}
Minecraft mc = Minecraft.getMinecraft();
/* Initialization of GUI elements */
this.gunOptions = new GuiElement(mc);
this.projectileOptions = new GuiElement(mc);
this.aimOptions = new GuiElement(mc);
this.aimOptionsSecond = new GuiElement(mc);
this.transformOptions = new GuiElement(mc);
this.transformFirstPersonOptions = new GuiElement(mc);
this.impactOptions = new GuiElement(mc);
this.panel = new GuiGunPanels(mc);
this.panel.setPanel(this.gunOptions);
this.panel.registerPanel(this.gunOptions, IKey.lang("blockbuster.gui.gun.fire_props"), Icons.GEAR);
this.panel.registerPanel(this.projectileOptions, IKey.lang("blockbuster.gui.gun.projectile_props"), BBIcons.BULLET);
this.panel.registerPanel(this.aimOptions, IKey.lang("blockbuster.gui.gun.aim_options_second"), Icons.SOUND);
this.panel.registerPanel(this.aimOptionsSecond, IKey.lang("blockbuster.gui.gun.aim_options"), Icons.CURSOR);
this.panel.registerPanel(this.impactOptions, IKey.lang("blockbuster.gui.gun.impact_props"), Icons.DOWNLOAD);
this.panel.registerPanel(this.transformOptions, IKey.lang("blockbuster.gui.gun.transforms"), Icons.POSE);
this.panel.registerPanel(this.transformFirstPersonOptions, IKey.lang("blockbuster.gui.gun.transforms_first_person"), Icons.WRENCH);
this.morphs = new GuiCreativeMorphsMenu(mc, this::setMorph);
/* Gun options */
Area area = this.gunOptions.area;
this.pickDefault = new GuiNestedEdit(mc, (editing) -> this.openMorphs(1, editing));
this.pickFiring = new GuiNestedEdit(mc, false, (editing) -> this.openMorphs(2, editing));
this.fireCommand = new GuiTextElement(mc, 10000, (value) -> this.props.fireCommand = value);
this.delay = new GuiTrackpadElement(mc, (value) -> this.props.delay = value.intValue());
this.delay.limit(0, Integer.MAX_VALUE, true);
this.projectiles = new GuiTrackpadElement(mc, (value) -> this.props.projectiles = value.intValue());
this.projectiles.limit(0, Integer.MAX_VALUE, true);
this.scatterX = new GuiTrackpadElement(mc, (value) -> this.props.scatterX = value.floatValue());
this.scatterX.tooltip(IKey.lang("blockbuster.gui.gun.scatter_x"));
this.scatterY = new GuiTrackpadElement(mc, (value) -> this.props.scatterY = value.floatValue());
this.scatterY.tooltip(IKey.lang("blockbuster.gui.gun.scatter_y"));
this.launch = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.launch"), false, (b) -> this.props.launch = b.isToggled());
this.useTarget = new GuiToggleElement(mc, IKey.lang("metamorph.gui.body_parts.use_target"), false, (b) -> this.props.useTarget = b.isToggled());
this.ammoStack = new GuiSlotElement(mc, 0, this::pickItem);
this.ammoStack.tooltip(IKey.lang("blockbuster.gui.gun.ammo_stack"));
int firingOffset = 40;
GuiElement scatterBar = new GuiElement(mc);
scatterBar.flex().relative(area).set(0, 0, 0, 20).x(0.5F).y(1, -75).w(0.5F, -60).anchorX(0.5F).row(5);
scatterBar.add(this.scatterX, this.scatterY);
this.fireCommand.flex().relative(area).set(10, 0, 0, 20).w(1, -20).y(1F, -30);
this.delay.flex().relative(scatterBar.resizer()).set(0, 0, 100, 20).x(-10).anchorX(1F);
this.projectiles.flex().relative(scatterBar.resizer()).set(0, 0, 100, 20).x(1F, 10);
this.pickDefault.flex().relative(this.delay.resizer()).w(1F).y(-5 - firingOffset);
this.pickFiring.flex().relative(this.projectiles.resizer()).w(1F).y(-5 - firingOffset);
this.ammoStack.flex().relative(this.pickFiring.resizer()).x(1F, 5).y(-2);
GuiElement launchBar = new GuiElement(mc);
launchBar.flex().relative(scatterBar.resizer()).y(-5 - firingOffset).w(1F).h(11).row(10);
this.launch.flex().h(20);
this.useTarget.flex().h(20);
launchBar.add(this.launch, this.useTarget);
this.gunOptions.add(scatterBar, launchBar, this.delay, this.projectiles, this.pickDefault, this.pickFiring, this.fireCommand, this.ammoStack);
/* Projectile options */
area = this.projectileOptions.area;
this.pickProjectile = new GuiNestedEdit(mc, (editing) -> this.openMorphs(3, editing));
this.tickCommand = new GuiTextElement(mc, 10000, (value) -> this.props.tickCommand = value);
this.ticking = new GuiTrackpadElement(mc, (value) -> this.props.ticking = value.intValue());
this.ticking.tooltip(IKey.lang("blockbuster.gui.gun.ticking"));
this.ticking.limit(0, Integer.MAX_VALUE, true);
this.lifeSpan = new GuiTrackpadElement(mc, (value) -> this.props.lifeSpan = value.intValue());
this.lifeSpan.tooltip(IKey.lang("blockbuster.gui.gun.life_span"));
this.lifeSpan.limit(0, Integer.MAX_VALUE, true);
this.yaw = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.yaw"), false, (b) -> this.props.yaw = b.isToggled());
this.pitch = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.pitch"), false, (b) -> this.props.pitch = b.isToggled());
this.sequencer = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.enabled"), false, (b) -> this.props.sequencer = b.isToggled());
this.random = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.random"), false, (b) -> this.props.random = b.isToggled());
this.hitboxX = new GuiTrackpadElement(mc, (value) -> this.props.hitboxX = value.floatValue());
this.hitboxX.tooltip(IKey.lang("blockbuster.gui.gun.hitbox_x"));
this.hitboxY = new GuiTrackpadElement(mc, (value) -> this.props.hitboxY = value.floatValue());
this.hitboxY.tooltip(IKey.lang("blockbuster.gui.gun.hitbox_y"));
this.speed = new GuiTrackpadElement(mc, (value) -> this.props.speed = value.floatValue());
this.speed.tooltip(IKey.lang("blockbuster.gui.gun.speed"));
this.friction = new GuiTrackpadElement(mc, (value) -> this.props.friction = value.floatValue());
this.friction.tooltip(IKey.lang("blockbuster.gui.gun.friction"));
this.gravity = new GuiTrackpadElement(mc, (value) -> this.props.gravity = value.floatValue());
this.gravity.tooltip(IKey.lang("blockbuster.gui.gun.gravity"));
this.fadeIn = new GuiTrackpadElement(mc, (value) -> this.props.fadeIn = value.intValue());
this.fadeIn.tooltip(IKey.lang("blockbuster.gui.gun.fade_in"));
this.fadeIn.limit(0, Integer.MAX_VALUE, true);
this.fadeOut = new GuiTrackpadElement(mc, (value) -> this.props.fadeOut = value.intValue());
this.fadeOut.tooltip(IKey.lang("blockbuster.gui.gun.fade_out"));
this.fadeOut.limit(0, Integer.MAX_VALUE, true);
this.pickProjectile.flex().relative(area).w(100).x(0.75F, -50).y(1, -60);
this.tickCommand.flex().relative(area).set(10, 0, 0, 20).w(1, -20).y(1, -30);
GuiElement projectileFields = new GuiElement(mc);
projectileFields.flex().relative(area).w(1F).h(1F, -40).column(5).width(100).height(20).padding(10);
projectileFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.category.motion")).background(), this.speed, this.friction, this.gravity);
projectileFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.category.hitbox")).background().marginTop(12), this.hitboxX, this.hitboxY);
projectileFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.category.timers")).background().marginTop(12), this.ticking, this.lifeSpan);
projectileFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.category.rotation")).background().marginTop(12), this.yaw, this.pitch);
projectileFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.category.transition")).background().marginTop(12), this.fadeIn, this.fadeOut);
projectileFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.sequencer")).background().marginTop(12), this.sequencer, this.random);
this.projectileOptions.add(this.pickProjectile, this.tickCommand, projectileFields);
/* Aim options */
area = this.aimOptionsSecond.area;
this.staticRecoil = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.static_recoil"), false, (b) -> this.props.staticRecoil = b.isToggled());
this.staticRecoil.tooltip(IKey.lang("blockbuster.gui.gun.static_recoil_tooltip"));
this.recoilXMin = new GuiTrackpadElement(mc, (value) -> this.props.recoilXMin = value.floatValue());
this.recoilXMin.limit(-200, 200).tooltip(IKey.lang("blockbuster.gui.gun.recoil_min"));
this.recoilXMax = new GuiTrackpadElement(mc, (value) -> this.props.recoilXMax = value.floatValue());
this.recoilXMax.limit(-200, 200).tooltip(IKey.lang("blockbuster.gui.gun.recoil_max"));
this.recoilYMin = new GuiTrackpadElement(mc, (value) -> this.props.recoilYMin = value.floatValue());
this.recoilYMin.limit(-200, 200).tooltip(IKey.lang("blockbuster.gui.gun.recoil_min"));
this.recoilYMax = new GuiTrackpadElement(mc, (value) -> this.props.recoilYMax = value.floatValue());
this.recoilYMax.limit(-200, 200).tooltip(IKey.lang("blockbuster.gui.gun.recoil_max"));
this.enableArmsShootingPose = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.arm_shooting_pose"), false, (b) -> this.props.enableArmsShootingPose = b.isToggled());
this.enableArmsShootingPose.tooltip(IKey.lang("blockbuster.gui.gun.arm_shooting_pose_tooltip"));
this.alwaysArmsShootingPose = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.arm_shooting_pose_always"), false, (b) -> this.props.alwaysArmsShootingPose = b.isToggled());
this.alwaysArmsShootingPose.tooltip(IKey.lang("blockbuster.gui.gun.arm_shooting_pose_always_tooltip"));
this.shootOffsetX = new GuiTrackpadElement(mc, (value) -> this.props.shootingOffsetX = value.floatValue());
this.shootOffsetX.limit(-10, 10);
this.shootOffsetY = new GuiTrackpadElement(mc, (value) -> this.props.shootingOffsetY = value.floatValue());
this.shootOffsetY.limit(-10, 10);
this.shootOffsetZ = new GuiTrackpadElement(mc, (value) -> this.props.shootingOffsetZ = value.floatValue());
this.shootOffsetZ.limit(-10, 10);
this.pickCrosshairMorph = new GuiNestedEdit(mc, (editing) -> this.openMorphs(9, editing));
this.pickInventoryMorph = new GuiNestedEdit(mc, (editing) -> this.openMorphs(7, editing));
this.pickHandsMorph = new GuiNestedEdit(mc, (editing) -> this.openMorphs(5, editing));
this.pickReloadMorph = new GuiNestedEdit(mc, (editing) -> this.openMorphs(8, editing));
this.pickZoomOverlayMorph = new GuiNestedEdit(mc, (editing) -> this.openMorphs(6, editing));
this.hideCrosshairOnZoom = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.hide_crosshair_on_zoom"), false, (b) -> this.props.hideCrosshairOnZoom = b.isToggled());
this.useInventoryMorph = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.use_inventory_morph"), false, (b) -> this.props.useInventoryMorph = b.isToggled());
this.hideHandsOnZoom = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.hide_hands_on_zoom"), false, (b) -> this.props.hideHandsOnZoom = b.isToggled());
this.useZoomOverlayMorph = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.use_zoom_overlay_morph"), false, (b) -> this.props.useZoomOverlayMorph = b.isToggled());
this.zoomFactor = new GuiTrackpadElement(mc, (value) -> this.props.zoomFactor = value.floatValue());
this.zoomFactor.limit(0, 1).increment(0.1).values(0.05, 0.01, 0.1).tooltip(IKey.lang("blockbuster.gui.gun.zoom_factor_tooltip"));
this.ammo = new GuiTrackpadElement(mc, (value) -> this.props.ammo = value.intValue());
this.ammo.limit(1).integer().tooltip(IKey.lang("blockbuster.gui.gun.ammo_tooltip"));
this.useReloading = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.use_reloading"), false, (b) -> this.props.useReloading = b.isToggled());
this.reloadingTime = new GuiTrackpadElement(mc, (value) -> this.props.reloadingTime = value.intValue());
this.reloadingTime.limit(0).integer().tooltip(IKey.lang("blockbuster.gui.gun.reloading_time_tooltip"));
this.shootWhenHeld = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.shoot_when_held"), false, (b) -> this.props.shootWhenHeld = b.isToggled());
this.shotDelay = new GuiTrackpadElement(mc, (value) -> this.props.shotDelay = value.intValue());
this.shotDelay.limit(0).integer().tooltip(IKey.lang("blockbuster.gui.gun.shot_delay_tooltip"));
GuiScrollElement aimFields = new GuiScrollElement(mc, ScrollDirection.HORIZONTAL);
aimFields.flex().relative(area).wh(1F, 1F).column(5).scroll().width(160).height(20).padding(10);
aimFields.add(Elements.label(IKey.str("Recoil")).background(), this.staticRecoil);
aimFields.add(
Elements.label(IKey.lang("blockbuster.gui.gun.recoil_x")).marginBottom(-2),
Elements.row(mc, 5, this.recoilXMin, this.recoilXMax)
);
aimFields.add(
Elements.label(IKey.lang("blockbuster.gui.gun.recoil_y")).marginBottom(-2),
Elements.row(mc, 5, this.recoilYMin, this.recoilYMax)
);
aimFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.arm_pose")).background().marginTop(12), this.enableArmsShootingPose, this.alwaysArmsShootingPose);
aimFields.add(
Elements.label(IKey.lang("blockbuster.gui.gun.shooting_offset")).background().marginTop(12).tooltip(IKey.lang("blockbuster.gui.gun.shooting_offset_tooltip")),
this.shootOffsetX, this.shootOffsetY, this.shootOffsetZ.marginBottom(100000)
);
aimFields.add(
Elements.column(mc, 5,
Elements.label(IKey.lang("blockbuster.gui.gun.crosshair_morph")).background(),
this.hideCrosshairOnZoom, this.pickCrosshairMorph
)
);
aimFields.add(
Elements.column(mc, 5,
Elements.label(IKey.lang("blockbuster.gui.gun.inventory_morph")).background(),
this.useInventoryMorph, this.pickInventoryMorph
).marginTop(12)
);
aimFields.add(
Elements.column(mc, 5,
Elements.label(IKey.lang("blockbuster.gui.gun.hands_morph")).background(),
this.hideHandsOnZoom, this.pickHandsMorph
).marginTop(12)
);
aimFields.add(
Elements.column(mc, 5,
Elements.label(IKey.lang("blockbuster.gui.gun.reload_morph")).background(),
this.pickReloadMorph
).marginTop(12)
);
aimFields.add(
Elements.column(mc, 5,
Elements.label(IKey.lang("blockbuster.gui.gun.overlay_morph")).background(),
this.useZoomOverlayMorph, this.pickZoomOverlayMorph
).marginTop(12).marginBottom(100000)
);
aimFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.zoom_factor")).background().marginTop(12), this.zoomFactor);
aimFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.ammo")).background().marginTop(12), this.ammo);
aimFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.reloading")).background().marginTop(12), this.useReloading, reloadingTime);
aimFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.shooting")).background().marginTop(12), this.shootWhenHeld, this.shotDelay);
this.aimOptionsSecond.add(aimFields);
/* Aim options 2 */
area = this.aimOptions.area;
this.destroyCommand = new GuiTextElement(mc, 10000, (value) -> this.props.destroyCommand = value);
this.meleeCommand = new GuiTextElement(mc, 10000, (value) -> this.props.meleeCommand = value);
this.reloadCommand = new GuiTextElement(mc, 10000, (value) -> this.props.reloadCommand = value);
this.zoomOnCommand = new GuiTextElement(mc, 10000, (value) -> this.props.zoomOnCommand = value);
this.zoomOffCommand = new GuiTextElement(mc, 10000, (value) -> this.props.zoomOffCommand = value);
this.meleeDamage = new GuiTrackpadElement(mc, (value) -> this.props.meleeDamage = value.floatValue());
this.mouseZoom = new GuiTrackpadElement(mc, (value) -> this.props.mouseZoom = value.floatValue());
this.mouseZoom.limit(0, 1.5F);
this.durability = new GuiTrackpadElement(mc, (value) -> this.props.durability = value.intValue());
this.durability.limit(0, Integer.MAX_VALUE, true);
this.preventLeftClick = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.prevent_left_click"), false, (b) -> this.props.preventLeftClick = b.isToggled());
this.preventRightClick = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.prevent_right_click"), false, (b) -> this.props.preventRightClick = b.isToggled());
this.preventEntityAttack = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.prevent_entity_attack"), false, (b) -> this.props.preventEntityAttack = b.isToggled());
GuiElement aimTwo = Elements.column(mc, 5, 10,
Elements.label(IKey.lang("blockbuster.gui.gun.melee_damage")).marginTop(5), this.meleeDamage,
Elements.label(IKey.lang("blockbuster.gui.gun.mouse_zoom")).marginTop(5), this.mouseZoom,
Elements.label(IKey.lang("blockbuster.gui.gun.durability")).marginTop(5), this.durability,
this.preventLeftClick,
this.preventRightClick,
this.preventEntityAttack
);
aimTwo.flex().relative(area).x(1F).y(1F).w(200).anchor(1F, 1F);
GuiElement aimCommands = Elements.column(mc, 3, 10,
Elements.label(IKey.lang("blockbuster.gui.gun.destroyed_command")), this.destroyCommand,
Elements.label(IKey.lang("blockbuster.gui.gun.melee_command")).marginTop(5), this.meleeCommand,
Elements.label(IKey.lang("blockbuster.gui.gun.reload_command")).marginTop(5), this.reloadCommand,
Elements.label(IKey.lang("blockbuster.gui.gun.zoom_on_command")).marginTop(5), this.zoomOnCommand,
Elements.label(IKey.lang("blockbuster.gui.gun.zoom_off_command")).marginTop(5), this.zoomOffCommand
);
aimCommands.flex().relative(area).y(1F).wTo(aimTwo.area, 10).anchorY(1F);
this.aimOptions.add(aimTwo, aimCommands);
/* Impact options */
area = this.impactOptions.area;
this.pickImpact = new GuiNestedEdit(mc, (editing) -> this.openMorphs(4, editing));
this.impactDelay = new GuiTrackpadElement(mc, (value) -> this.props.impactDelay = value.intValue());
this.impactDelay.limit(0, Integer.MAX_VALUE, true);
this.impactCommand = new GuiTextElement(mc, 10000, (value) -> this.props.impactCommand = value);
this.impactEntityCommand = new GuiTextElement(mc, 10000, (value) -> this.props.impactEntityCommand = value);
this.vanish = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.enabled"), false, (b) -> this.props.vanish = b.isToggled());
this.bounce = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.enabled"), false, (b) -> this.props.bounce = b.isToggled());
this.sticks = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.enabled"), false, (b) -> this.props.sticks = b.isToggled());
this.hits = new GuiTrackpadElement(mc, (value) -> this.props.hits = value.intValue());
this.hits.tooltip(IKey.lang("blockbuster.gui.gun.hits"));
this.hits.limit(0, Integer.MAX_VALUE, true);
this.damage = new GuiTrackpadElement(mc, (value) -> this.props.damage = value.floatValue());
this.knockbackHorizontal = new GuiTrackpadElement(mc, (value) -> this.props.knockbackHorizontal = value.floatValue());
this.knockbackHorizontal.tooltip(IKey.lang("blockbuster.gui.gun.knockback_horizontal"));
this.knockbackVertical = new GuiTrackpadElement(mc, (value) -> this.props.knockbackVertical = value.floatValue());
this.knockbackVertical.tooltip(IKey.lang("blockbuster.gui.gun.knockback_vertical"));
this.bounceFactor = new GuiTrackpadElement(mc, (value) -> this.props.bounceFactor = value.floatValue());
this.bounceFactor.tooltip(IKey.lang("blockbuster.gui.gun.bounce_factor"));
this.vanishCommand = new GuiTextElement(mc, 10000, (value) -> this.props.vanishCommand = value);
this.vanishDelay = new GuiTrackpadElement(mc, (value) -> this.props.vanishDelay = value.intValue());
this.vanishDelay.limit(0).integer().tooltip(IKey.lang("blockbuster.gui.gun.vanish_delay"));
this.penetration = new GuiTrackpadElement(mc, (value) -> this.props.penetration = value.floatValue());
this.penetration.block().tooltip(IKey.lang("blockbuster.gui.gun.penetration"));
this.ignoreBlocks = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.ignore_blocks"), false, (b) -> this.props.ignoreBlocks = b.isToggled());
this.ignoreBlocks.tooltip(IKey.lang("blockbuster.gui.gun.ignore_blocks_tooltip"));
this.ignoreEntities = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.gun.ignore_entities"), false, (b) -> this.props.ignoreEntities = b.isToggled());
this.ignoreEntities.tooltip(IKey.lang("blockbuster.gui.gun.ignore_entities_tooltip"));
this.pickImpact.flex().relative(area).w(100).x(0.75F, -40).y(1, -140);
this.vanishCommand.flex().relative(area).set(10, 0, 0, 20).w(1, -20).y(1, -110);
this.impactEntityCommand.flex().relative(this.vanishCommand).y(40).w(1F).h(20);
this.impactCommand.flex().relative(this.impactEntityCommand).y(40).w(1F).h(20);
GuiElement impactFields = new GuiElement(mc);
impactFields.flex().relative(area).w(1F).h(1F, -120).column(5).width(100).height(20).padding(10);
impactFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.impact_delay")).background(), this.impactDelay);
impactFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.damage")).background().marginTop(12), this.damage, this.knockbackHorizontal, this.knockbackVertical);
impactFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.bounce")).background().marginTop(12), this.bounce, this.hits, this.bounceFactor);
impactFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.vanish")).background().marginTop(12), this.vanish, this.vanishDelay);
impactFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.sticks")).background().marginTop(12), this.sticks, this.penetration);
impactFields.add(Elements.label(IKey.lang("blockbuster.gui.gun.collision")).background().marginTop(12), this.ignoreBlocks, this.ignoreEntities);
this.impactOptions.add(this.pickImpact, this.vanishCommand, this.impactEntityCommand, this.impactCommand, impactFields);
/* Gun transforms */
area = this.transformOptions.area;
this.gun = new GuiPoseTransformations(mc);
this.projectile = new GuiPoseTransformations(mc);
this.arms = new GuiMorphRenderer(mc);
this.arms.setRotation(61, -13);
this.arms.setPosition(0.1048045F, 1.081198F, 0.22774392F);
this.arms.setScale(1.5F);
try
{
this.arms.morph = MorphManager.INSTANCE.morphFromNBT(JsonToNBT.getTagFromJson("{Name:\"blockbuster.fred\"}"));
this.arms.getEntity().setItemStackToSlot(EntityEquipmentSlot.MAINHAND, stack);
}
catch (Exception e)
{}
this.bullet = new GuiProjectileModelRenderer(mc);
this.bullet.projectile.props = this.props;
this.bullet.projectile.morph.setDirect(this.props.projectileMorph);
this.bullet.setRotation(-64, 16);
this.bullet.setPosition(-0.042806394F, 0.40452564F, -0.001203875F);
this.bullet.setScale(2.5F);
this.gun.flex().relative(area).x(0.25F, -95).y(1, -80).wh(190, 70);
this.projectile.flex().relative(area).x(0.75F, -95).y(1, -80).wh(190, 70);
this.arms.flex().relative(area).wTo(this.bullet.flex()).h(1F);
this.bullet.flex().relative(area).x(0.5F).wh(0.5F, 1F);
this.transformOptions.add(this.arms, this.bullet, this.gun, this.projectile);
/* Gun transforms (first person) */
area = this.transformFirstPersonOptions.area;
this.gunFirstPerson = new GuiPoseTransformations(mc);
this.gunFirstPerson.flex().relative(area).x(0.5F).y(1, -80).wh(190, 70).anchorX(0.5F);
this.transformFirstPersonOptions.add(this.gunFirstPerson);
/* Placement of the elements */
this.morphs.flex().relative(this.viewport).wh(1F, 1F);
this.panel.flex().relative(this.viewport).set(0, 35, 0, 0).w(1, 0).h(1, -35);
/* Gun properties */
this.pickDefault.setMorph(this.props.defaultMorph);
this.pickHandsMorph.setMorph(this.props.handsMorph);
this.pickInventoryMorph.setMorph(this.props.inventoryMorph);
this.pickReloadMorph.setMorph(this.props.reloadMorph);
this.pickZoomOverlayMorph.setMorph(this.props.zoomOverlayMorph);
this.pickFiring.setMorph(this.props.firingMorph);
this.pickCrosshairMorph.setMorph(this.props.crosshairMorph);
this.fireCommand.setText(this.props.fireCommand);
this.delay.setValue(this.props.delay);
this.projectiles.setValue(this.props.projectiles);
this.zoomFactor.setValue(this.props.zoomFactor);
this.recoilXMin.setValue(this.props.recoilXMin);
this.recoilXMax.setValue(this.props.recoilXMax);
this.shootOffsetX.setValue(this.props.shootingOffsetX);
this.shootOffsetY.setValue(this.props.shootingOffsetY);
this.durability.setValue(this.props.durability);
this.mouseZoom.setValue(this.props.mouseZoom);
this.shootOffsetZ.setValue(this.props.shootingOffsetZ);
this.recoilYMin.setValue(this.props.recoilYMin);
this.meleeDamage.setValue(this.props.meleeDamage);
this.ammo.setValue(this.props.ammo);
this.reloadingTime.setValue(this.props.reloadingTime);
this.recoilYMax.setValue(this.props.recoilYMax);
this.shotDelay.setValue(this.props.shotDelay);
this.staticRecoil.toggled(this.props.staticRecoil);
this.scatterX.setValue(this.props.scatterX);
this.scatterY.setValue(this.props.scatterY);
this.launch.toggled(this.props.launch);
this.useTarget.toggled(this.props.useTarget);
this.ammoStack.setStack(this.props.ammoStack);
this.reloadCommand.setText(this.props.reloadCommand);
this.meleeCommand.setText(this.props.meleeCommand);
this.destroyCommand.setText(this.props.destroyCommand);
this.meleeCommand.setText(this.props.meleeCommand);
this.destroyCommand.setText(this.props.destroyCommand);
this.zoomOnCommand.setText(this.props.zoomOnCommand);
this.zoomOffCommand.setText(this.props.zoomOffCommand);
this.useZoomOverlayMorph.toggled(this.props.useZoomOverlayMorph);
this.hideHandsOnZoom.toggled(this.props.hideHandsOnZoom);
this.hideCrosshairOnZoom.toggled(this.props.hideCrosshairOnZoom);
this.enableArmsShootingPose.toggled(this.props.enableArmsShootingPose);
this.preventRightClick.toggled(this.props.preventRightClick);
this.preventLeftClick.toggled(this.props.preventLeftClick);
this.preventEntityAttack.toggled(this.props.preventEntityAttack);
this.useInventoryMorph.toggled(this.props.useInventoryMorph);
this.useReloading.toggled(this.props.useReloading);
this.alwaysArmsShootingPose.toggled(this.props.alwaysArmsShootingPose);
this.shootWhenHeld.toggled(this.props.shootWhenHeld);
/* Projectile properties */
this.pickProjectile.setMorph(this.props.projectileMorph);
this.tickCommand.setText(this.props.tickCommand);
this.ticking.setValue(this.props.ticking);
this.lifeSpan.setValue(this.props.lifeSpan);
this.yaw.toggled(this.props.yaw);
this.pitch.toggled(this.props.pitch);
this.sequencer.toggled(this.props.sequencer);
this.random.toggled(this.props.random);
this.hitboxX.setValue(this.props.hitboxX);
this.hitboxY.setValue(this.props.hitboxY);
this.speed.setValue(this.props.speed);
this.friction.setValue(this.props.friction);
this.gravity.setValue(this.props.gravity);
this.fadeIn.setValue(this.props.fadeIn);
this.fadeOut.setValue(this.props.fadeOut);
/* Impact properties */
this.pickImpact.setMorph(this.props.impactMorph);
this.impactCommand.setText(this.props.impactCommand);
this.impactEntityCommand.setText(this.props.impactEntityCommand);
this.impactDelay.setValue(this.props.impactDelay);
this.vanish.toggled(this.props.vanish);
this.bounce.toggled(this.props.bounce);
this.sticks.toggled(this.props.sticks);
this.hits.setValue(this.props.hits);
this.damage.setValue(this.props.damage);
this.knockbackHorizontal.setValue(this.props.knockbackHorizontal);
this.knockbackVertical.setValue(this.props.knockbackVertical);
this.bounceFactor.setValue(this.props.bounceFactor);
this.vanishCommand.setText(this.props.vanishCommand);
this.vanishDelay.setValue(this.props.vanishDelay);
this.penetration.setValue(this.props.penetration);
this.ignoreBlocks.toggled(this.props.ignoreBlocks);
this.ignoreEntities.toggled(this.props.ignoreEntities);
/* Gun transforms */
this.gun.set(this.props.gunTransform);
this.gunFirstPerson.set(this.props.gunTransformFirstPerson);
this.projectile.set(this.props.projectileTransform);
this.root.add(this.panel);
this.root.keys().register(IKey.lang("blockbuster.gui.gun.keys.cycle"), Keyboard.KEY_TAB, this::cycle);
}
private void pickItem(ItemStack stack)
{
this.props.ammoStack = stack;
}
protected void cycle()
{
int index = -1;
for (int i = 0; i < this.panel.panels.size(); i++)
{
if (this.panel.view.delegate == this.panel.panels.get(i))
{
index = i;
break;
}
}
index += GuiScreen.isShiftKeyDown() ? 1 : -1;
index = MathUtils.cycler(index, 0, this.panel.panels.size() - 1);
this.panel.buttons.elements.get(index).clickItself(GuiBase.getCurrent());
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
private void openMorphs(int i, boolean editing)
{
AbstractMorph morph = this.props.defaultMorph;
if (i == 2)
{
morph = this.props.firingMorph;
}
else if (i == 3)
{
morph = this.props.projectileMorph;
}
else if (i == 4)
{
morph = this.props.impactMorph;
}
else if (i == 5)
{
morph = this.props.handsMorph;
}
else if (i == 6)
{
morph = this.props.zoomOverlayMorph;
}
else if (i == 7)
{
morph = this.props.inventoryMorph;
}
else if (i == 8)
{
morph = this.props.reloadMorph;
}
else if (i == 9)
{
morph = this.props.crosshairMorph;
}
if (this.morphs.hasParent())
{
if (i == this.index)
{
return;
}
else
{
this.morphs.finish();
this.morphs.removeFromParent();
}
}
this.index = i;
this.morphs.resize();
this.morphs.setSelected(morph);
if (editing)
{
this.morphs.enterEditMorph();
}
this.root.add(this.morphs);
}
private void setMorph(AbstractMorph morph)
{
if (this.index == 1)
{
this.props.defaultMorph = morph;
this.props.setCurrent(MorphUtils.copy(morph));
this.pickDefault.setMorph(morph);
}
else if (this.index == 2)
{
this.props.firingMorph = morph;
this.pickFiring.setMorph(morph);
}
else if (this.index == 3)
{
this.props.projectileMorph = morph;
this.pickProjectile.setMorph(morph);
this.bullet.projectile.morph.setDirect(this.props.projectileMorph);
}
else if (this.index == 4)
{
this.props.impactMorph = morph;
this.pickImpact.setMorph(morph);
}
else if (this.index == 5)
{
this.props.handsMorph = morph;
this.props.setHandsMorph(MorphUtils.copy(morph));
this.pickHandsMorph.setMorph(morph);
}
else if (this.index == 6)
{
this.props.zoomOverlayMorph = morph;
this.props.setCurrentZoomOverlay(MorphUtils.copy(morph));
this.pickZoomOverlayMorph.setMorph(morph);
}
else if (this.index == 7)
{
this.props.inventoryMorph = morph;
this.props.setInventoryMorph(MorphUtils.copy(morph));
this.pickInventoryMorph.setMorph(morph);
}
else if (this.index == 8)
{
this.props.reloadMorph = morph;
this.pickReloadMorph.setMorph(morph);
}
else if (this.index == 9)
{
this.props.crosshairMorph = morph;
this.props.setCrosshairMorph(MorphUtils.copy(morph));
this.pickCrosshairMorph.setMorph(morph);
}
}
@Override
protected void closeScreen()
{
super.closeScreen();
this.props.storedDurability = (int) this.durability.value;
Dispatcher.sendToServer(new PacketGunInfo(this.props.toNBT(), 0));
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
GuiDraw.drawCustomBackground(0, 0, this.width, this.height);
Gui.drawRect(0, 0, this.width, 35, ColorUtils.HALF_BLACK);
this.drawGradientRect(0, 35, this.width, 45, ColorUtils.HALF_BLACK, 0);
this.fontRenderer.drawStringWithShadow(I18n.format("blockbuster.gui.gun.title"), 10, 15, 0xffffffff);
EntityPlayer player = this.mc.player;
int w = this.viewport.w / 4;
if (this.panel.view.delegate == this.gunOptions)
{
if (this.props.defaultMorph != null)
{
this.props.defaultMorph.renderOnScreen(player, this.pickDefault.area.mx(), this.pickDefault.area.y - 20, w * 0.5F, 1);
}
if (this.props.firingMorph != null)
{
this.props.firingMorph.renderOnScreen(player, this.pickFiring.area.mx(), this.pickFiring.area.y - 20, w * 0.5F, 1);
GlStateManager.clear(GL11.GL_DEPTH_BUFFER_BIT);
}
this.drawCenteredString(this.fontRenderer, I18n.format("blockbuster.gui.gun.default_morph"), this.pickDefault.area.mx(), this.pickFiring.area.y - 12, 0xffffff);
this.drawCenteredString(this.fontRenderer, I18n.format("blockbuster.gui.gun.fire_morph"), this.pickFiring.area.mx(), this.pickFiring.area.y - 12, 0xffffff);
this.drawCenteredString(this.fontRenderer, I18n.format("blockbuster.gui.gun.delay"), this.delay.area.mx(), this.delay.area.y - 12, 0xffffff);
this.drawCenteredString(this.fontRenderer, I18n.format("blockbuster.gui.gun.scatter"), this.scatterX.area.ex() + 3, this.scatterX.area.y - 12, 0xffffff);
this.drawCenteredString(this.fontRenderer, I18n.format("blockbuster.gui.gun.projectiles"), this.projectiles.area.mx(), this.projectiles.area.y - 12, 0xffffff);
this.fontRenderer.drawStringWithShadow(I18n.format("blockbuster.gui.gun.fire_command"), this.fireCommand.area.x, this.fireCommand.area.y - 12, 0xffffff);
}
else if (this.panel.view.delegate == this.projectileOptions)
{
if (this.props.projectileMorph != null)
{
this.props.projectileMorph.renderOnScreen(player, this.pickProjectile.area.mx(), this.pickProjectile.area.y - 20, w * 0.5F, 1);
}
this.drawCenteredString(this.fontRenderer, I18n.format("blockbuster.gui.gun.projectile_morph"), this.pickProjectile.area.mx(), this.pickProjectile.area.y - 12, 0xffffff);
this.fontRenderer.drawStringWithShadow(I18n.format("blockbuster.gui.gun.tick_command"), this.tickCommand.area.x, this.tickCommand.area.y - 12, 0xffffff);
}
else if (this.panel.view.delegate == this.impactOptions)
{
if (this.props.impactMorph != null)
{
this.props.impactMorph.renderOnScreen(player, this.pickImpact.area.mx(), this.pickImpact.area.y - 20, w * 0.5F, 1);
}
this.drawCenteredString(this.fontRenderer, I18n.format("blockbuster.gui.gun.impact_morph"), this.pickImpact.area.mx(), this.pickImpact.area.y - 12, 0xffffff);
this.fontRenderer.drawStringWithShadow(I18n.format("blockbuster.gui.gun.impact_command"), this.impactCommand.area.x, this.impactCommand.area.y - 12, 0xffffff);
this.fontRenderer.drawStringWithShadow(I18n.format("blockbuster.gui.gun.impact_entity_command"), this.impactEntityCommand.area.x, this.impactEntityCommand.area.y - 12, 0xffffff);
this.fontRenderer.drawStringWithShadow(I18n.format("blockbuster.gui.gun.vanish_command"), this.vanishCommand.area.x, this.vanishCommand.area.y - 12, 0xffffff);
}
super.drawScreen(mouseX, mouseY, partialTicks);
if (this.panel.view.delegate == this.transformOptions)
{
String gun = I18n.format("blockbuster.gui.gun.gun_transforms");
String trans = I18n.format("blockbuster.gui.gun.projectile_transforms");
GuiDraw.drawTextBackground(this.context.font, gun, this.gun.area.mx(this.context.font.getStringWidth(gun)), this.arms.area.y + 15, 0xffffff, ColorUtils.HALF_BLACK);
GuiDraw.drawTextBackground(this.context.font, trans, this.projectile.area.mx(this.context.font.getStringWidth(trans)), this.arms.area.y + 15, 0xffffff, ColorUtils.HALF_BLACK);
}
}
public static class GuiProjectileModelRenderer extends GuiModelRenderer
{
public EntityGunProjectile projectile;
public GuiProjectileModelRenderer(Minecraft mc)
{
super(mc);
this.projectile = new EntityGunProjectile(mc.world);
}
@Override
protected void drawUserModel(GuiContext context)
{
this.projectile.ticksExisted = this.projectile.props.fadeIn;
this.mc.getRenderManager().renderEntity(this.projectile, 0, 0.5F, 0, 0, context.partialTicks, false);
GlStateManager.disableTexture2D();
GlStateManager.disableLighting();
GlStateManager.disableDepth();
GlStateManager.pushMatrix();
GlStateManager.translate(0, 0.5F, 0);
GL11.glLineWidth(5);
GL11.glBegin(GL11.GL_LINES);
GL11.glColor3d(0, 0, 0);
GL11.glVertex3d(0, 0, 0);
GL11.glVertex3d(0, 0, 0.25);
GL11.glEnd();
GL11.glLineWidth(3);
GL11.glBegin(GL11.GL_LINES);
GL11.glColor3d(0, 1, 0);
GL11.glVertex3d(0, 0, 0);
GL11.glVertex3d(0, 0, 0.25);
GL11.glEnd();
GL11.glLineWidth(1);
GL11.glPointSize(12);
GL11.glBegin(GL11.GL_POINTS);
GL11.glColor3d(0, 0, 0);
GL11.glVertex3d(0, 0, 0);
GL11.glEnd();
GL11.glPointSize(10);
GL11.glBegin(GL11.GL_POINTS);
GL11.glColor3d(1, 1, 1);
GL11.glVertex3d(0, 0, 0);
GL11.glEnd();
GL11.glPointSize(1);
GlStateManager.popMatrix();
GlStateManager.enableDepth();
GlStateManager.enableLighting();
GlStateManager.enableTexture2D();
}
}
public static class GuiGunPanels extends GuiPanelBase<GuiElement>
{
public GuiGunPanels(Minecraft mc)
{
super(mc);
}
@Override
protected void drawBackground(GuiContext context, int x, int y, int w, int h)
{
Gui.drawRect(x, y, x + w, y + h, 0xff080808);
}
}
} | 47,698 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiImmersiveEditor.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/GuiImmersiveEditor.java | package mchorse.blockbuster.client.gui;
import java.util.List;
import java.util.function.Consumer;
import org.lwjgl.input.Keyboard;
import com.google.common.collect.ImmutableList;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.IGuiElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.EntityUtils;
import mchorse.metamorph.api.MorphUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.gui.ScaledResolution;
import net.minecraft.world.GameType;
import net.minecraftforge.common.MinecraftForge;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
/**
* Immersive Editor
*
* This editor allows you to edit morphs in the game world
*/
@SideOnly(Side.CLIENT)
public class GuiImmersiveEditor extends GuiBase
{
public static final IKey CATEGORY = IKey.lang("blockbuster.gui.immersive_editor.keys.category");
public GuiImmersiveMorphMenu morphs;
public GuiOuterScreen outerPanel;
public GuiScreen lastScreen;
public int lastTPS;
public GameType lastMode;
public double lastPosX;
public double lastPosY;
public double lastPosZ;
public float lastRotPitch;
public float lastRotYaw;
public Consumer<GuiImmersiveEditor> onClose;
public GuiImmersiveEditor(Minecraft mc)
{
this.mc = mc;
this.morphs = new GuiImmersiveMorphMenu(mc);
this.morphs.flex().relative(this.viewport).xy(0F, 0F).wh(1F, 1F);
this.outerPanel = new GuiOuterScreen(mc);
this.outerPanel.flex().relative(this.viewport).xy(0F, 0F).wh(1F, 1F);
this.root.add(morphs, this.outerPanel);
this.root.keys().register(IKey.lang("blockbuster.gui.immersive_editor.keys.toggle_outer_panel"), Keyboard.KEY_F1, () -> this.outerPanel.toggleVisible())
.category(CATEGORY).active(() -> !this.outerPanel.getChildren().isEmpty());
}
public void show()
{
this.lastScreen = this.mc.currentScreen;
this.lastTPS = this.mc.gameSettings.thirdPersonView;
this.lastMode = EntityUtils.getGameMode();
this.lastPosX = this.mc.player.posX;
this.lastPosY = this.mc.player.posY;
this.lastPosZ = this.mc.player.posZ;
this.lastRotPitch = this.mc.player.rotationPitch;
this.lastRotYaw = this.mc.player.rotationYaw;
this.mc.currentScreen = this;
ScaledResolution scaledresolution = new ScaledResolution(this.mc);
int i = scaledresolution.getScaledWidth();
int j = scaledresolution.getScaledHeight();
this.setWorldAndResolution(this.mc, i, j);
this.morphs.reload();
this.morphs.resize();
this.morphs.setVisible(true);
this.outerPanel.setVisible(false);
this.mc.gameSettings.thirdPersonView = 0;
this.mc.setRenderViewEntity(this.mc.player);
if (this.lastMode != GameType.SPECTATOR)
{
this.mc.player.sendChatMessage("/gamemode 3");
}
MinecraftForge.EVENT_BUS.register(this.morphs);
}
@Override
public void onGuiClosed()
{
this.closeScreen();
this.lastScreen.onGuiClosed();
}
@Override
public boolean doesGuiPauseGame()
{
return false;
}
@Override
protected void closeScreen()
{
if (this.lastScreen == null)
{
return;
}
this.morphs.finish();
this.mc.currentScreen = this.lastScreen;
ScaledResolution scaledresolution = new ScaledResolution(this.mc);
int i = scaledresolution.getScaledWidth();
int j = scaledresolution.getScaledHeight();
this.lastScreen.setWorldAndResolution(this.mc, i, j);
this.mc.gameSettings.thirdPersonView = this.lastTPS;
/* if the server connection is terminated unexpectedly,
it seems to happen that player is null before screen is closed */
if (this.mc.player != null) {
this.mc.player.sendChatMessage("/gamemode " + this.lastMode.getID());
this.mc.player.setPositionAndRotation(this.lastPosX, this.lastPosY, this.lastPosZ, this.lastRotYaw, this.lastRotPitch);
}
this.lastScreen = null;
MinecraftForge.EVENT_BUS.unregister(this.morphs);
if (this.onClose != null)
{
this.onClose.accept(this);
this.onClose = null;
}
this.morphs.setVisible(false);
}
@Override
public void drawScreen(int mouseX, int mouseY, float partialTicks)
{
if (!this.morphs.isImmersionMode())
{
GuiDraw.drawCustomBackground(0, 0, this.width, this.height);
}
super.drawScreen(mouseX, mouseY, partialTicks);
}
public static class GuiOuterScreen extends GuiElement
{
public GuiOuterScreen(Minecraft mc)
{
super(mc);
}
@Override
public boolean mouseClicked(GuiContext context)
{
List<IGuiElement> list = ImmutableList.copyOf(this.getChildren());
for (int i = list.size() - 1; i >= 0; i--)
{
IGuiElement element = list.get(i);
if (element.isEnabled() && element.mouseClicked(context))
{
return true;
}
}
return false;
}
@Override
public boolean mouseScrolled(GuiContext context)
{
List<IGuiElement> list = ImmutableList.copyOf(this.getChildren());
for (int i = list.size() - 1; i >= 0; i--)
{
IGuiElement element = list.get(i);
if (element.isEnabled() && element.mouseScrolled(context))
{
return true;
}
}
return false;
}
@Override
public void mouseReleased(GuiContext context)
{
List<IGuiElement> list = ImmutableList.copyOf(this.getChildren());
for (int i = list.size() - 1; i >= 0; i--)
{
IGuiElement element = list.get(i);
if (element.isEnabled())
{
element.mouseReleased(context);
}
}
}
@Override
public void draw(GuiContext context)
{
GuiDraw.drawCustomBackground(this.area.x, this.area.y, this.area.ex(), this.area.ey());
super.draw(context);
GuiDraw.drawTextBackground(this.font, IKey.lang("blockbuster.gui.immersive_editor.hide_outer_panel").get(), this.area.x + 5, this.area.y + 5, 0xFFFFFF, 0);
}
}
}
| 7,032 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiShapeKeysEditor.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/utils/GuiShapeKeysEditor.java | package mchorse.blockbuster.client.gui.utils;
import mchorse.blockbuster.api.Model;
import mchorse.blockbuster.api.formats.obj.ShapeKey;
import mchorse.blockbuster_pack.client.gui.GuiCustomMorph;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.context.GuiSimpleContextMenu;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.list.GuiListElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.Direction;
import mchorse.mclib.utils.MathUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
import java.util.List;
import java.util.function.Supplier;
public class GuiShapeKeysEditor extends GuiElement
{
public GuiListElement<ShapeKey> shapes;
public GuiTrackpadElement factor;
public GuiToggleElement relative;
private Supplier<Model> supplier;
public GuiShapeKeysEditor(Minecraft mc, Supplier<Model> supplier)
{
super(mc);
this.supplier = supplier;
this.shapes = new GuiCustomMorph.GuiShapeKeyListElement(mc, (str) -> this.setFactor(str.get(0)));
this.shapes.sorting().background();
this.shapes.context(() ->
{
GuiSimpleContextMenu menu = new GuiSimpleContextMenu(mc);
menu.action(Icons.ADD, IKey.lang("blockbuster.gui.builder.context.add"), () ->
{
Model model = this.supplier == null ? null : this.supplier.get();
if (model == null)
{
return;
}
GuiSimpleContextMenu nested = new GuiSimpleContextMenu(mc);
for (String key : model.shapes)
{
nested.action(Icons.ADD, IKey.format("blockbuster.gui.builder.context.add_to", key), () ->
{
ShapeKey shapeKey = new ShapeKey(key, 0);
this.shapes.getList().add(shapeKey);
this.shapes.update();
this.shapes.setCurrent(shapeKey);
this.setFactor(shapeKey);
});
}
GuiBase.getCurrent().replaceContextMenu(nested);
});
if (this.shapes.getIndex() != -1)
{
menu.action(Icons.REMOVE, IKey.lang("blockbuster.gui.builder.context.remove"), () ->
{
int index = this.shapes.getIndex();
this.shapes.getList().remove(index);
index = MathUtils.clamp(index, 0, this.shapes.getList().size() - 1);
this.shapes.setIndex(index);
this.setFactor(this.shapes.getCurrentFirst());
});
}
return menu;
});
this.factor = new GuiTrackpadElement(mc, (value) -> this.setFactor(value.floatValue()));
this.factor.tooltip(IKey.lang("blockbuster.gui.builder.shape_keys_factor_tooltip"), Direction.TOP);
this.relative = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.builder.relative"), (b) -> this.shapes.getCurrentFirst().relative = b.isToggled());
this.relative.tooltip(IKey.lang("blockbuster.gui.builder.relative_tooltip"), Direction.TOP);
this.shapes.flex().relative(this).y(12).w(1F).hTo(this.factor.flex(), -17);
this.factor.flex().relative(this.relative.flex()).y(-25).w(1F).h(20);
this.relative.flex().relative(this).y(1F).w(1F).anchorY(1F);
this.add(this.relative, this.factor, this.shapes);
}
private void setFactor(ShapeKey key)
{
this.factor.setEnabled(key != null);
this.relative.setEnabled(key != null);
if (key != null)
{
this.factor.setValue(key.value);
this.relative.toggled(key.relative);
}
}
private void setFactor(float value)
{
this.shapes.getCurrentFirst().value = value;
}
public void fillData(List<ShapeKey> shapeKeys)
{
this.shapes.setList(shapeKeys);
if (!shapeKeys.isEmpty())
{
this.shapes.setIndex(0);
this.setFactor(this.shapes.getCurrentFirst());
}
else
{
this.setFactor(null);
}
}
@Override
public void draw(GuiContext context)
{
super.draw(context);
if (this.shapes.isVisible())
{
this.font.drawStringWithShadow(I18n.format("blockbuster.gui.builder.shape_keys"), this.shapes.area.x, this.shapes.area.y - 12, 0xffffff);
}
if (this.factor.isVisible())
{
this.font.drawStringWithShadow(I18n.format("blockbuster.gui.builder.shape_keys_factor"), this.factor.area.x, this.factor.area.y - 12, 0xffffff);
}
}
}
| 5,153 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiBlockbusterPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/GuiBlockbusterPanel.java | package mchorse.blockbuster.client.gui.dashboard;
import mchorse.mclib.client.gui.mclib.GuiDashboard;
import mchorse.mclib.client.gui.mclib.GuiDashboardPanel;
import net.minecraft.client.Minecraft;
public class GuiBlockbusterPanel extends GuiDashboardPanel<GuiDashboard>
{
public GuiBlockbusterPanel(Minecraft mc, GuiDashboard dashboard)
{
super(mc, dashboard);
}
@Override
public void appear()
{
GuiFirstTime.addOverlay(this.dashboard);
}
} | 488 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiFirstTime.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/GuiFirstTime.java | package mchorse.blockbuster.client.gui.dashboard;
import mchorse.blockbuster.Blockbuster;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.IGuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.mclib.GuiAbstractDashboard;
import mchorse.mclib.client.gui.mclib.GuiDashboard;
import mchorse.mclib.client.gui.utils.GuiUtils;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.ColorUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import java.util.List;
/**
* First time? https://i.redd.it/2dbksvvj34121.jpg
*/
public class GuiFirstTime extends GuiElement
{
public GuiButtonElement close;
public GuiButtonElement tutorial;
public GuiButtonElement youtube;
public GuiButtonElement channel;
public GuiButtonElement discord;
public GuiButtonElement twitter;
private IKey title;
private List<String> welcome;
private List<String> social;
private final Overlay overlay;
public static boolean shouldOpen()
{
return Blockbuster.generalFirstTime.get();
}
public static void addOverlay(GuiAbstractDashboard dashboard)
{
if (!GuiFirstTime.shouldOpen())
{
return;
}
boolean alreadyHas = false;
for (IGuiElement element : dashboard.root.getChildren())
{
if (element instanceof GuiFirstTime.Overlay)
{
alreadyHas = true;
break;
}
}
if (!alreadyHas)
{
GuiFirstTime.Overlay overlay = new GuiFirstTime.Overlay(Minecraft.getMinecraft());
overlay.flex().relative(dashboard.viewport).w(1, 0).h(1, 0);
overlay.resize();
dashboard.root.add(overlay);
}
}
public GuiFirstTime(Minecraft mc, Overlay overlay)
{
super(mc);
this.overlay = overlay;
this.close = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.done"), (button) -> this.close());
this.tutorial = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.main.tutorial"), (button) -> GuiUtils.openWebLink(Blockbuster.TUTORIAL_URL()));
this.discord = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.main.discord"), (button) -> GuiUtils.openWebLink(Blockbuster.DISCORD_URL()));
this.youtube = new GuiButtonElement(mc, IKey.str("YouTube"), (button) -> GuiUtils.openWebLink("https://www.youtube.com/c/McHorsesMods"));
this.channel = new GuiButtonElement(mc, IKey.str(Blockbuster.langOrDefault("blockbuster.gui.first_time.channel", "")), (button) -> GuiUtils.openWebLink(Blockbuster.CHANNEL_URL()));
this.twitter = new GuiButtonElement(mc, IKey.str("Twitter"), (button) -> GuiUtils.openWebLink(Blockbuster.TWITTER_URL()));
this.tutorial.flex().set(10, 0, 0, 20).relative(this.area).w(0.5F, -12);
this.youtube.flex().set(0, 0, 0, 20).relative(this.area).x(0.5F, 2).w(0.5F, -12);
this.discord.flex().set(10, 0, 0, 20).relative(this.area).w(0.5F, -12).y(1, -55);
this.twitter.flex().set(0, 0, 0, 20).relative(this.area).x(0.5F, 2).w(0.5F, -12).y(1, -55);
this.close.flex().set(10, 0, 0, 20).relative(this.area).w(1, -20).y(1, -30);
this.add(this.tutorial, this.discord, this.youtube, this.twitter, this.close);
if (!this.channel.label.get().isEmpty())
{
this.tutorial.flex().set(10, 0, 0, 20).relative(this.area).w(0.33F, -10);
this.channel.flex().set(0, 0, 0, 20).relative(this.area).x(0.5F, -30).w(60);
this.youtube.flex().set(0, 0, 0, 20).relative(this.area).x(0.67F, 0).w(0.33F, -10);
this.add(this.channel);
}
this.title = IKey.lang("blockbuster.gui.first_time.title");
this.welcome = this.font.listFormattedStringToWidth(I18n.format("blockbuster.gui.first_time.welcome"), 180);
this.social = this.font.listFormattedStringToWidth(I18n.format("blockbuster.gui.first_time.social"), 180);
}
private void close()
{
this.overlay.removeFromParent();
/* Don't show anymore this modal */
Blockbuster.generalFirstTime.set(false);
}
@Override
public void draw(GuiContext context)
{
final int lineHeight = 11;
this.area.draw(0xff000000);
/* Draw extra text */
String title = this.title.get();
GlStateManager.pushMatrix();
GlStateManager.translate(this.area.mx() - this.font.getStringWidth(title), this.area.y + 10, 0);
GlStateManager.scale(2, 2, 2);
this.font.drawStringWithShadow(title, 0, 0, 0xffffff);
GlStateManager.popMatrix();
/* Draw welcome paragraph */
int y = this.area.y + 35;
for (String label : this.welcome)
{
this.font.drawStringWithShadow(label, this.area.x + 10, y, 0xaaaaaa);
y += lineHeight;
}
y += 5;
/* Readjust buttons */
this.tutorial.flex().y(y - this.area.y);
this.tutorial.resize();
this.channel.flex().y(y - this.area.y);
this.channel.resize();
this.youtube.flex().y(y - this.area.y);
this.youtube.resize();
/* Draw social paragraph */
y = this.discord.area.y - 5 - this.social.size() * lineHeight;
for (String label : this.social)
{
this.font.drawStringWithShadow(label, this.area.x + 10, y, 0xaaaaaa);
y += lineHeight;
}
super.draw(context);
}
public static class Overlay extends GuiElement
{
public Overlay(Minecraft mc)
{
super(mc);
GuiFirstTime firstTime = new GuiFirstTime(mc, this);
firstTime.flex().set(0, 0, 200, 250).relative(this.area).x(0.5F, -100).y(0.5F, -125);
this.add(firstTime);
this.hideTooltip();
}
@Override
public boolean mouseClicked(GuiContext context)
{
return super.mouseClicked(context) || this.isEnabled();
}
@Override
public void draw(GuiContext context)
{
this.area.draw(ColorUtils.HALF_BLACK);
super.draw(context);
}
}
}
| 6,482 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiBlockbusterPanels.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/GuiBlockbusterPanels.java | package mchorse.blockbuster.client.gui.dashboard;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.client.gui.GuiImmersiveEditor;
import mchorse.blockbuster.client.gui.GuiImmersiveMorphMenu;
import mchorse.blockbuster.client.gui.dashboard.panels.GuiTextureManagerPanel;
import mchorse.blockbuster.client.gui.dashboard.panels.scene.GuiScenePanel;
import mchorse.blockbuster.client.gui.dashboard.panels.model_block.GuiModelBlockPanel;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.GuiModelEditorPanel;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.model.parsing.ModelExtrudedLayer;
import mchorse.blockbuster.utils.mclib.BBIcons;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.mclib.GuiDashboard;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.events.MultiskinProcessedEvent;
import mchorse.mclib.events.RegisterDashboardPanels;
import mchorse.mclib.events.RemoveDashboardPanels;
import mchorse.metamorph.api.morphs.AbstractMorph;
import mchorse.metamorph.client.gui.creative.GuiCreativeMorphsMenu;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.EntityLivingBase;
import net.minecraftforge.fml.common.eventhandler.SubscribeEvent;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import java.util.function.Consumer;
/**
* Blockbuster's dashboard GUI entry
*/
@SideOnly(Side.CLIENT)
public class GuiBlockbusterPanels
{
public GuiScenePanel scenePanel;
public GuiModelBlockPanel modelPanel;
public GuiModelEditorPanel modelEditorPanel;
public GuiRecordingEditorPanel recordingEditorPanel;
public GuiTextureManagerPanel texturePanel;
public GuiSnowstorm particleEditor;
public GuiCreativeMorphsMenu morphs;
public GuiImmersiveEditor immersiveEditor;
public void picker(Consumer<AbstractMorph> callback)
{
this.morphs.removeFromParent();
this.morphs.callback = callback;
this.immersiveEditor.morphs.callback = callback;
}
public void addMorphs(GuiElement parent, boolean editing, AbstractMorph morph)
{
if (this.morphs.hasParent())
{
return;
}
parent.add(this.morphs);
this.morphs.reload();
this.morphs.flex().reset().relative(parent).wh(1F, 1F);
this.morphs.resize();
this.morphs.setSelected(morph);
if (editing)
{
this.morphs.enterEditMorph();
}
}
public GuiImmersiveEditor showImmersiveEditor(boolean editing, AbstractMorph morph)
{
this.immersiveEditor.show();
this.immersiveEditor.morphs.setSelected(morph);
this.immersiveEditor.morphs.updateCallback = null;
this.immersiveEditor.morphs.target = null;
this.immersiveEditor.morphs.frameProvider = null;
this.immersiveEditor.morphs.beforeRender = null;
this.immersiveEditor.morphs.afterRender = null;
if (editing)
{
this.immersiveEditor.morphs.enterEditMorph();
}
return this.immersiveEditor;
}
public void closeImmersiveEditor()
{
this.immersiveEditor.closeThisScreen();
}
@SubscribeEvent
public void onRegister(RegisterDashboardPanels event)
{
if (!(event.dashboard instanceof GuiDashboard))
{
return;
}
Minecraft mc = Minecraft.getMinecraft();
GuiDashboard dashboard = (GuiDashboard) event.dashboard;
this.scenePanel = new GuiScenePanel(mc, dashboard);
this.modelPanel = new GuiModelBlockPanel(mc, dashboard);
this.modelEditorPanel = new GuiModelEditorPanel(mc, dashboard);
this.recordingEditorPanel = new GuiRecordingEditorPanel(mc, dashboard);
this.texturePanel = new GuiTextureManagerPanel(mc, dashboard);
this.particleEditor = new GuiSnowstorm(mc, dashboard);
this.morphs = new GuiCreativeMorphsMenu(mc, null);
this.immersiveEditor = new GuiImmersiveEditor(mc);
dashboard.panels.registerPanel(this.scenePanel, IKey.lang("blockbuster.gui.dashboard.director"), BBIcons.SCENE);
dashboard.panels.registerPanel(this.modelPanel, IKey.lang("blockbuster.gui.dashboard.model"), Icons.BLOCK);
dashboard.panels.registerPanel(this.modelEditorPanel, IKey.lang("blockbuster.gui.dashboard.model_editor"), Icons.POSE);
dashboard.panels.registerPanel(this.recordingEditorPanel, IKey.lang("blockbuster.gui.dashboard.player_recording"), BBIcons.EDITOR);
dashboard.panels.registerPanel(this.texturePanel, IKey.lang("blockbuster.gui.dashboard.texture"), Icons.MATERIAL);
dashboard.panels.registerPanel(this.particleEditor, IKey.lang("blockbuster.gui.dashboard.particle"), BBIcons.PARTICLE);
}
@SubscribeEvent
public void onUnregister(RemoveDashboardPanels event)
{
GuiModelBlockPanel.lastBlocks.clear();
ClientProxy.audio.reset();
this.scenePanel = null;
this.modelPanel = null;
this.recordingEditorPanel = null;
this.morphs = null;
this.immersiveEditor = null;
}
@SubscribeEvent
public void onMultiskinLoad(MultiskinProcessedEvent event)
{
ModelExtrudedLayer.forceReload(event.location, event.image);
}
} | 5,550 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiBlockList.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/GuiBlockList.java | package mchorse.blockbuster.client.gui.dashboard.panels;
import java.util.List;
import java.util.function.Consumer;
import mchorse.mclib.client.gui.framework.elements.list.GuiListElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.utils.Area;
import mchorse.mclib.client.gui.utils.ScrollArea;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.util.math.BlockPos;
/**
* GUI block list
*
* This GUI module is responsible for rendering and selecting
*/
public abstract class GuiBlockList<T> extends GuiListElement<T>
{
/**
* Title of this panel
*/
public IKey title;
public GuiBlockList(Minecraft mc, IKey title, Consumer<List<T>> callback)
{
super(mc, callback);
this.title = title;
this.area = new Area();
this.scroll = new ScrollArea(20);
}
public abstract boolean addBlock(BlockPos pos);
@Override
public void resize()
{
super.resize();
this.scroll.copy(this.area);
this.scroll.y += 30;
this.scroll.h -= 30;
}
@Override
public void draw(GuiContext context)
{
this.area.draw(0xff333333);
Gui.drawRect(this.area.x, this.area.y, this.area.ex(), this.area.y + 30, 0x44000000);
this.font.drawStringWithShadow(this.title.get(), this.area.x + 10, this.area.y + 11, 0xcccccc);
super.draw(context);
}
} | 1,528 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiTextureManagerPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/GuiTextureManagerPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.client.gui.dashboard.GuiBlockbusterPanel;
import mchorse.blockbuster.client.textures.MipmapTexture;
import mchorse.blockbuster.utils.TextureUtils;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.list.GuiListElement;
import mchorse.mclib.client.gui.framework.elements.list.GuiResourceLocationListElement;
import mchorse.mclib.client.gui.framework.elements.list.GuiSearchListElement;
import mchorse.mclib.client.gui.framework.elements.modals.GuiMessageModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiPromptModal;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.client.gui.mclib.GuiDashboard;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.GuiUtils;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.Direction;
import mchorse.mclib.utils.ReflectionUtils;
import mchorse.mclib.utils.resources.RLUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.client.renderer.GLAllocation;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.texture.ITextureObject;
import net.minecraft.client.renderer.texture.TextureManager;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.io.FilenameUtils;
import org.lwjgl.opengl.GL11;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.nio.ByteBuffer;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
/**
* Texture manager panel
*
* This is a GUI which allows viewing and managing textures loaded by
* {@link TextureManager} class.
*
* Besides viewing, it also allows changing filter (linear/nearest),
* generating mipmaps and removing (clearing) textures from the manager.
*/
public class GuiTextureManagerPanel extends GuiBlockbusterPanel
{
public GuiSearchResourceLocationList textures;
public GuiToggleElement linear;
public GuiToggleElement mipmap;
public GuiButtonElement remove;
public GuiButtonElement replace;
public GuiButtonElement export;
public GuiIconElement copy;
private ResourceLocation rl;
private String title = I18n.format("blockbuster.gui.texture.title");
private String subtitle = I18n.format("blockbuster.gui.texture.subtitle");
public GuiTextureManagerPanel(Minecraft mc, GuiDashboard dashboard)
{
super(mc, dashboard);
this.textures = new GuiSearchResourceLocationList(mc, (rl) -> this.pickRL(rl.get(0)));
this.textures.list.background();
this.linear = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.texture.linear"), false, (b) -> this.setLinear(b.isToggled()));
this.linear.tooltip(IKey.lang("blockbuster.gui.texture.linear_tooltip"), Direction.LEFT);
this.mipmap = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.texture.mipmap"), false, (b) -> this.setMipmap(b.isToggled()));
this.mipmap.tooltip(IKey.lang("blockbuster.gui.texture.mipmap_tooltip"), Direction.LEFT);
this.remove = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.remove"), (b) -> this.remove());
this.replace = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.texture.replace"), (b) -> this.replace());
this.export = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.texture.export"), (b) -> this.export());
this.copy = new GuiIconElement(mc, Icons.COPY, (b) -> this.copy());
this.copy.tooltip(IKey.lang("blockbuster.gui.texture.copy"), Direction.TOP).flex().wh(20, 20);
GuiElement element = new GuiElement(mc);
element.flex().relative(this).xy(1F, 1F).w(148).anchor(1F, 1F).column(5).vertical().stretch().padding(10);
this.textures.flex().relative(this.area).set(10, 50, 0, 0).w(1, -30 - 128).h(1, -60);
element.add(Elements.row(mc, 5, 0, this.export, this.copy));
element.add(this.replace, this.remove, this.linear, this.mipmap);
this.add(this.textures, element);
}
@Override
public boolean isClientSideOnly()
{
return true;
}
private void copy()
{
ResourceLocation location = this.textures.list.getCurrentFirst();
if (location == null)
{
return;
}
GuiScreen.setClipboardString(location.toString());
}
private void export()
{
ResourceLocation location = this.textures.list.getCurrentFirst();
if (location == null)
{
return;
}
String name = FilenameUtils.getBaseName(location.getResourcePath());
File folder = new File(ClientProxy.configFile, "export");
File file = TextureUtils.getFirstAvailableFile(folder, name);
folder.mkdirs();
this.mc.renderEngine.bindTexture(location);
int w = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
int h = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);
ByteBuffer buffer = GLAllocation.createDirectByteBuffer(w * h * 4);
GL11.glGetTexImage(GL11.GL_TEXTURE_2D, 0, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
int[] pixelData = new int[w * h];
for (int i = 0, c = w * h; i < c; i++)
{
int r = buffer.get() & 0xff;
int g = buffer.get() & 0xff;
int b = buffer.get() & 0xff;
int a = buffer.get() & 0xff;
pixelData[i] = (a << 24) | (r << 16) | (g << 8) | b;
}
image.setRGB(0, 0, w, h, pixelData, 0, w);
try
{
ImageIO.write(image, "png", file);
GuiModal.addFullModal(this, () ->
{
GuiMessageModal modal = new GuiMessageModal(this.mc, IKey.format("blockbuster.gui.texture.export_modal", file.getName()));
GuiButtonElement open = new GuiButtonElement(this.mc, IKey.lang("blockbuster.gui.texture.open_folder"), (b) ->
{
modal.removeFromParent();
GuiUtils.openFolder(new File(ClientProxy.configFile, "export").getAbsolutePath());
});
modal.bar.add(open);
return modal;
});
}
catch (Exception e)
{
e.printStackTrace();
GuiModal.addFullModal(this, () -> new GuiMessageModal(this.mc, IKey.lang("blockbuster.gui.texture.export_error")));
}
}
private void pickRL(ResourceLocation rl)
{
if (this.rl == null)
{
this.linear.toggled(false);
this.mipmap.toggled(false);
this.rl = rl;
}
else
{
try
{
this.mc.renderEngine.bindTexture(rl);
int filter = GL11.glGetTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER);
boolean mipmap = ReflectionUtils.getTextures(this.mc.renderEngine).get(rl) instanceof MipmapTexture;
boolean linear = filter == GL11.GL_LINEAR || filter == GL11.GL_LINEAR_MIPMAP_LINEAR || filter == GL11.GL_LINEAR_MIPMAP_NEAREST;
this.linear.toggled(linear);
this.mipmap.toggled(mipmap);
this.rl = rl;
}
catch (Exception e)
{}
}
}
private void setLinear(boolean linear)
{
if (this.rl == null) return;
this.mc.renderEngine.bindTexture(this.rl);
boolean mipmap = this.mipmap.isToggled();
int mod = linear ? (mipmap ? GL11.GL_LINEAR_MIPMAP_LINEAR : GL11.GL_LINEAR) : (mipmap ? GL11.GL_NEAREST_MIPMAP_LINEAR : GL11.GL_NEAREST);
int mag = linear ? GL11.GL_LINEAR : GL11.GL_NEAREST;
GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MIN_FILTER, mod);
GlStateManager.glTexParameteri(GL11.GL_TEXTURE_2D, GL11.GL_TEXTURE_MAG_FILTER, mag);
}
private void setMipmap(boolean mipmap)
{
if (this.rl == null) return;
Map<ResourceLocation, ITextureObject> map = ReflectionUtils.getTextures(this.mc.renderEngine);
ITextureObject tex = map.get(this.rl);
boolean mipmapped = tex instanceof MipmapTexture;
/* Add or remove mipmap */
if (mipmap && !mipmapped)
{
GlStateManager.deleteTexture(map.remove(this.rl).getGlTextureId());
try
{
/* Load texture manually */
tex = new MipmapTexture(this.rl);
tex.loadTexture(Minecraft.getMinecraft().getResourceManager());
map.put(this.rl, tex);
}
catch (Exception e)
{
e.printStackTrace();
}
}
else if (!mipmap && mipmapped)
{
GlStateManager.deleteTexture(map.remove(this.rl).getGlTextureId());
}
}
private void remove()
{
if (this.rl == null)
{
return;
}
Map<ResourceLocation, ITextureObject> map = ReflectionUtils.getTextures(this.mc.renderEngine);
GlStateManager.deleteTexture(map.remove(this.rl).getGlTextureId());
this.textures.list.remove(this.rl);
this.textures.list.setIndex(this.textures.list.getIndex() - 1);
this.pickRL(this.textures.list.getCurrentFirst());
}
private void replace()
{
if (this.rl == null || GuiModal.hasModal(this))
{
return;
}
GuiModal.addModal(this, () ->
{
GuiPromptModal modal = new GuiPromptModal(this.mc, IKey.lang("blockbuster.gui.texture.replace_modal"), this::replace);
modal.text.field.setMaxStringLength(2000);
modal.setValue(this.rl.toString());
modal.flex().relative(this.area).set(10, 50, 0, 0).w(1, -30 - 128).h(1, -60);
return modal;
});
}
private void replace(String string)
{
if (this.rl.toString().equals(string))
{
return;
}
Map<ResourceLocation, ITextureObject> map = ReflectionUtils.getTextures(this.mc.renderEngine);
ITextureObject texture = map.get(RLUtils.create(string));
if (texture != null)
{
map.put(this.rl, texture);
}
}
@Override
public void open()
{
Map<ResourceLocation, ITextureObject> map = ReflectionUtils.getTextures(this.mc.renderEngine);
this.textures.list.clear();
this.textures.list.getList().addAll(map.keySet());
this.textures.list.sort();
this.textures.list.update();
this.pickRL(this.rl);
this.textures.list.setCurrent(this.rl);
}
@Override
public void draw(GuiContext context)
{
this.font.drawString(this.title, this.area.x + 10, this.area.y + 10, 0xffffff);
this.font.drawSplitString(this.subtitle, this.area.x + 10, this.area.y + 26, this.area.w - 158, 0xcccccc);
/* Draw preview */
if (this.rl != null)
{
this.mc.renderEngine.bindTexture(this.rl);
int w = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
int h = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);
int x = this.area.ex();
int y = this.area.y + 10;
int fw = w;
int fh = h;
if (fw > 128 || fh > 128)
{
fw = fh = 128;
if (w > h)
{
fh = (int) ((h / (float) w) * fw);
}
else if (h > w)
{
fw = (int) ((w / (float) h) * fh);
}
}
x -= fw + 10;
GlStateManager.color(1, 1, 1);
Icons.CHECKBOARD.renderArea(x, y, fw, fh);
GlStateManager.enableAlpha();
this.mc.renderEngine.bindTexture(this.rl);
GuiDraw.drawBillboard(x, y, 0, 0, fw, fh, fw, fh);
}
super.draw(context);
}
public static class GuiSearchResourceLocationList extends GuiSearchListElement<ResourceLocation>
{
public GuiSearchResourceLocationList(Minecraft mc, Consumer<List<ResourceLocation>> callback)
{
super(mc, callback);
}
@Override
protected GuiListElement<ResourceLocation> createList(Minecraft mc, Consumer<List<ResourceLocation>> callback)
{
return new GuiResourceLocationListElement(mc, callback);
}
}
} | 13,334 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiScenePanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/scene/GuiScenePanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.scene;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.aperture.CameraHandler;
import mchorse.blockbuster.client.gui.dashboard.GuiBlockbusterPanel;
import mchorse.blockbuster.common.BlockbusterPermissions;
import mchorse.blockbuster.common.item.ItemPlayback;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.PacketPlaybackButton;
import mchorse.blockbuster.network.common.recording.PacketUpdatePlayerData;
import mchorse.blockbuster.network.common.scene.PacketSceneCast;
import mchorse.blockbuster.network.common.scene.PacketScenePause;
import mchorse.blockbuster.network.common.scene.PacketScenePlayback;
import mchorse.blockbuster.network.common.scene.PacketSceneRecord;
import mchorse.blockbuster.network.server.recording.ServerHandlerFramesOverwrite;
import mchorse.blockbuster.network.server.recording.ServerHandlerRequestRecording;
import mchorse.blockbuster.recording.RecordUtils;
import mchorse.blockbuster.recording.data.Frame;
import mchorse.blockbuster.recording.scene.Replay;
import mchorse.blockbuster.recording.scene.Scene;
import mchorse.blockbuster.recording.scene.SceneLocation;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.GuiCollapseSection;
import mchorse.mclib.client.gui.framework.elements.GuiDelegateElement;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.list.GuiStringListElement;
import mchorse.mclib.client.gui.framework.elements.modals.GuiModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiPopUpModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiPromptModal;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.client.gui.framework.elements.utils.GuiLabel;
import mchorse.mclib.client.gui.mclib.GuiDashboard;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.GuiUtils;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.permissions.PermissionCategory;
import mchorse.mclib.utils.ColorUtils;
import mchorse.mclib.utils.Direction;
import mchorse.mclib.utils.MathUtils;
import mchorse.mclib.utils.OpHelper;
import mchorse.metamorph.api.MorphUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import mchorse.metamorph.client.gui.creative.GuiNestedEdit;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.resources.I18n;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.item.ItemStack;
import net.minecraft.util.math.MathHelper;
import net.minecraft.util.text.ITextComponent;
import net.minecraft.util.text.TextComponentString;
import net.minecraft.util.text.TextFormatting;
import net.minecraft.util.text.event.ClickEvent;
import net.minecraft.util.text.event.HoverEvent;
import org.lwjgl.input.Keyboard;
import java.util.List;
import java.util.function.Consumer;
import java.util.function.Supplier;
public class GuiScenePanel extends GuiBlockbusterPanel
{
private GuiElement subChildren;
private GuiDelegateElement<GuiElement> mainView;
private GuiElement replays;
private GuiElement replayEditor;
private GuiElement configOptions;
private GuiReplaySelector selector;
/* Config fields */
public GuiTextElement title;
public GuiTextElement startCommand;
public GuiTextElement stopCommand;
public GuiToggleElement loops;
public GuiStringListElement audio;
public GuiTrackpadElement audioShift;
public GuiIconElement openAudioFolder;
/* Replay fields */
public GuiTextElement id;
public GuiTextElement name;
public GuiTextElement target;
public GuiToggleElement playbackXPFood;
public GuiToggleElement invincible;
public GuiToggleElement invisible;
public GuiToggleElement enableBurning;
public GuiToggleElement enabled;
public GuiToggleElement fake;
public GuiToggleElement teleportBack;
public GuiToggleElement renderLast;
public GuiTrackpadElement health;
public GuiTrackpadElement foodLevel;
public GuiTrackpadElement totalExperience;
public GuiButtonElement record;
public GuiButtonElement rename;
public GuiButtonElement attach;
public GuiButtonElement camera;
public GuiButtonElement teleport;
public GuiCollapseSection eulerFilter;
public GuiCirculateElement eulerFilterChannel;
public GuiTrackpadElement eulerFilterFrom;
public GuiTrackpadElement eulerFilterTo;
public GuiButtonElement eulerFilterExecute;
public GuiLabel recordingId;
public GuiNestedEdit pickMorph;
public GuiSceneManager scenes;
private SceneLocation location = new SceneLocation();
private Replay replay;
private IKey noneAudioTrack = IKey.lang("blockbuster.gui.director.none");
public GuiScenePanel(Minecraft mc, GuiDashboard dashboard)
{
super(mc, dashboard);
this.selector = new GuiReplaySelector(mc, (replay) -> this.setReplay(replay.get(0)));
this.selector.flex().set(0, 0, 0, 60).relative(this).w(1, -20).y(1, -60);
GuiElement left = new GuiElement(mc);
GuiElement right = new GuiElement(mc);
left.flex().relative(this).w(120).y(20).hTo(this.selector.flex()).column(5).width(100).height(20).padding(10);
right.flex().relative(this).x(1F).y(20).w(120).hTo(this.selector.flex()).anchorX(1F).column(5).flip().width(100).height(20).padding(10);
this.subChildren = new GuiElement(mc).noCulling();
this.subChildren.setVisible(false);
this.replays = new GuiElement(mc).noCulling();
this.replayEditor = new GuiElement(mc).noCulling();
this.replayEditor.setVisible(false);
this.replayEditor.add(left, right);
this.configOptions = new GuiElement(mc).noCulling();
this.mainView = new GuiDelegateElement<GuiElement>(mc, this.replays);
this.mainView.noCulling();
this.add(this.subChildren);
this.subChildren.add(this.mainView);
/* Config options */
this.title = new GuiTextElement(mc, 80, (str) -> this.location.getScene().title = str);
this.startCommand = new GuiTextElement(mc, 10000, (str) -> this.location.getScene().startCommand = str);
this.stopCommand = new GuiTextElement(mc, 10000, (str) -> this.location.getScene().stopCommand = str);
this.loops = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.loops"), false, (b) -> this.location.getScene().loops = b.isToggled());
this.audio = new GuiStringListElement(mc, (value) -> this.location.getScene().setAudio(value.get(0).equals(this.noneAudioTrack.get()) ? "" : value.get(0)));
this.audio.background().tooltip(IKey.lang("blockbuster.gui.director.audio_tooltip"), Direction.RIGHT);
this.audioShift = new GuiTrackpadElement(mc, (value) -> this.location.getScene().setAudioShift(value.intValue()));
this.audioShift.integer().tooltip(IKey.lang("blockbuster.gui.director.audio_shift_tooltip"));
this.openAudioFolder = new GuiIconElement(mc, Icons.FOLDER, (b) -> GuiUtils.openFolder(ClientProxy.audio.folder.getAbsolutePath()));
this.openAudioFolder.tooltip(IKey.lang("blockbuster.gui.director.open_audio_folder"));
this.title.flex().set(120, 50, 0, 20).relative(this.area).w(1, -130);
this.startCommand.flex().set(120, 90, 0, 20).relative(this.area).w(1, -130);
this.stopCommand.flex().set(120, 130, 0, 20).relative(this.area).w(1, -130);
this.audio.flex().relative(this).xy(10, 50).w(100).hTo(this.stopCommand.area, 1F);
this.audioShift.flex().relative(this.audio).y(1F, 5).w(1F);
this.openAudioFolder.flex().relative(this.audio).x(1F, -16).y(-16).wh(16, 16);
GuiElement row = Elements.row(mc, 5, 0, 20, this.loops);
row.flex().relative(this.stopCommand).y(25).w(1F);
this.loops.flex().h(20);
this.configOptions.add(this.title, this.startCommand, this.stopCommand, row, this.audio, this.audioShift, this.openAudioFolder);
/* Replay options */
this.id = new GuiTextElement(mc, 120, (str) ->
{
this.replay.id = str;
this.updateLabel(true);
}).filename();
this.name = new GuiTextElement(mc, 80, (str) -> this.replay.name = str);
this.name.tooltip(IKey.lang("blockbuster.gui.director.name_tooltip"), Direction.RIGHT);
this.target = new GuiTextElement(mc, 80, (str) -> this.replay.target = str);
this.target.tooltip(IKey.lang("blockbuster.gui.director.target_tooltip"), Direction.LEFT);
this.playbackXPFood = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.playback_xp_food_level_enabled"), (b) -> this.replay.playBackXPFood = b.isToggled());
this.playbackXPFood.tooltip(IKey.lang("blockbuster.gui.director.playback_xp_food_level_tooltip"), Direction.LEFT);
this.invincible = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.invincible"), false, (b) -> this.replay.invincible = b.isToggled());
this.invisible = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.invisible"), false, (b) -> this.replay.invisible = b.isToggled());
this.enableBurning = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.enable_burning"), true, (b) -> this.replay.enableBurning = b.isToggled());
this.enabled = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.enabled"), false, (b) -> this.replay.enabled = b.isToggled());
this.fake = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.fake_player"), false, (b) -> this.replay.fake = b.isToggled());
this.teleportBack = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.tp_back"), false, (b) -> this.replay.teleportBack = b.isToggled());
this.teleportBack.tooltip(IKey.lang("blockbuster.gui.director.tp_back_tooltip"), Direction.RIGHT);
this.renderLast = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.director.render_last"), false, (b) -> this.replay.renderLast = b.isToggled());
this.renderLast.tooltip(IKey.lang("blockbuster.gui.director.render_last_tooltip"), Direction.RIGHT);
this.health = new GuiTrackpadElement(mc, (value) -> this.replay.health = value.floatValue());
this.health.limit(0);
this.foodLevel = new GuiTrackpadElement(mc, (value) -> this.replay.foodLevel = value.intValue());
this.foodLevel.limit(0).integer();
this.totalExperience = new GuiTrackpadElement(mc, (value) -> this.replay.totalExperience = value.intValue());
this.totalExperience.limit(0).integer();
this.recordingId = Elements.label(IKey.lang("blockbuster.gui.director.id")).color(0xcccccc);
left.add(this.recordingId, this.id);
left.add(Elements.label(IKey.lang("blockbuster.gui.director.name")).color(0xcccccc), this.name);
left.add(Elements.label(IKey.lang("blockbuster.gui.director.health")).color(0xcccccc), this.health,
Elements.label(IKey.lang("blockbuster.gui.director.food_level")).color(0xcccccc), this.foodLevel,
Elements.label(IKey.lang("blockbuster.gui.director.total_experience")).color(0xcccccc), this.totalExperience,
this.invincible, this.invisible, this.enableBurning, this.enabled, this.fake, this.teleportBack, this.renderLast);
this.replays.add(this.selector, this.replayEditor);
/* Toggle view button */
GuiIconElement toggle = new GuiIconElement(mc, Icons.GEAR, (b) ->
{
this.mainView.setDelegate(this.mainView.delegate == this.configOptions ? this.replays : this.configOptions);
});
GuiIconElement toggleScenes = new GuiIconElement(mc, Icons.MORE, (b) -> this.scenes.toggleVisible());
toggleScenes.flex().y(4).relative(this.area).x(1, -24);
toggle.tooltip(IKey.lang("blockbuster.gui.director.config"), Direction.LEFT);
toggle.flex().y(4).relative(this.area).x(1, -44);
this.add(toggleScenes);
this.subChildren.add(toggle);
/* Add, duplicate and remove replay buttons */
GuiIconElement add = new GuiIconElement(mc, Icons.ADD, (b) -> this.addReplay());
GuiIconElement dupe = new GuiIconElement(mc, Icons.DUPE, (b) -> this.dupeReplay());
GuiIconElement remove = new GuiIconElement(mc, Icons.REMOVE, (b) -> this.removeReplay());
add.tooltip(IKey.lang("blockbuster.gui.director.add_replay"), Direction.LEFT);
dupe.tooltip(IKey.lang("blockbuster.gui.director.dupe_replay"), Direction.LEFT);
remove.tooltip(IKey.lang("blockbuster.gui.director.remove_replay"), Direction.LEFT);
add.flex().set(0, 0, 20, 20).relative(this.selector.resizer()).x(1F);
dupe.flex().set(0, 20, 20, 20).relative(this.selector.resizer()).x(1F);
remove.flex().set(0, 40, 20, 20).relative(this.selector.resizer()).x(1F);
this.replays.add(add, dupe, remove);
/* Additional utility buttons */
IKey category = IKey.lang("blockbuster.gui.director.keys.category");
Supplier<Boolean> active = () -> this.replay != null;
this.pickMorph = new GuiNestedEdit(mc, (editing) -> ClientProxy.panels.addMorphs(this, editing, this.replay.morph));
this.record = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.record"), (b) -> this.sendRecordMessage());
GuiButtonElement edit = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.director.edit_record"), (b) -> this.openRecordEditor());
GuiButtonElement update = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.director.update_data"), (b) -> this.updatePlayerData());
this.rename = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.director.rename_prefix"), (b) -> this.renamePrefix());
this.attach = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.director.attach"), (b) -> this.attach());
this.teleport = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.director.tp"), (b) -> this.teleport());
this.teleport.keys().register(this.teleport.label, Keyboard.KEY_T, () -> this.teleport.clickItself(GuiBase.getCurrent())).category(category).active(active);
this.eulerFilter = new GuiCollapseSection(mc, IKey.lang("blockbuster.gui.director.rotation_filter.title"));
this.eulerFilter.setCollapsed(true);
this.eulerFilterFrom = new GuiTrackpadElement(mc, (Consumer<Double>) null);
this.eulerFilterFrom.limit(0).integer();
this.eulerFilterFrom.tooltip(IKey.lang("blockbuster.gui.director.rotation_filter.from_tooltip"));
this.eulerFilterTo = new GuiTrackpadElement(mc, (Consumer<Double>) null);
this.eulerFilterTo.limit(0).integer();
this.eulerFilterTo.tooltip(IKey.lang("blockbuster.gui.director.rotation_filter.to_tooltip"));
this.eulerFilterChannel = new GuiCirculateElement(mc, null);
this.eulerFilterChannel.addLabel(IKey.lang("blockbuster.gui.director.rotation_filter.head_yaw"));
this.eulerFilterChannel.addLabel(IKey.lang("blockbuster.gui.director.rotation_filter.head_pitch"));
this.eulerFilterChannel.addLabel(IKey.lang("blockbuster.gui.director.rotation_filter.body_yaw"));
this.eulerFilterChannel.tooltip(IKey.lang("blockbuster.gui.director.rotation_filter.channel_tooltip"));
this.eulerFilterExecute = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.director.rotation_filter.execute"), (b) ->
{
this.rotationFilter();
});
this.eulerFilter.addFields(this.eulerFilterChannel, this.eulerFilterFrom, this.eulerFilterTo, this.eulerFilterExecute);
this.pickMorph.flex().relative(this.selector).x(0.5F).y(-10).w(100).anchor(0.5F, 1F);
update.tooltip(IKey.lang("blockbuster.gui.director.update_data_tooltip"), Direction.LEFT);
this.rename.tooltip(IKey.lang("blockbuster.gui.director.rename_prefix_tooltip"), Direction.LEFT);
this.attach.tooltip(IKey.lang("blockbuster.gui.director.attach_tooltip"), Direction.LEFT);
this.teleport.tooltip(IKey.lang("blockbuster.gui.director.tp_tooltip"), Direction.LEFT);
right.add(this.attach, this.record, update, this.rename, edit);
if (CameraHandler.isApertureLoaded())
{
this.camera = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.director.camera"), (b) ->
{
CameraHandler.location = this.location;
CameraHandler.openCameraEditor();
});
this.camera.keys().register(this.camera.label, Keyboard.KEY_C, () -> this.camera.clickItself(GuiBase.getCurrent())).category(category).active(active);
right.add(this.camera);
}
right.add(this.teleport, this.eulerFilter);
right.add(Elements.label(IKey.lang("blockbuster.gui.director.target")).color(0xcccccc).marginTop(12), this.target, Elements.label(IKey.lang("blockbuster.gui.director.playback_xp_food_level")), this.playbackXPFood);
this.replayEditor.add(this.pickMorph);
/* Scene manager */
this.add(this.scenes = new GuiSceneManager(mc, this));
this.scenes.flex().relative(toggleScenes).xy(1F, 1F).w(160).hTo(this.selector.flex()).anchorX(1F);
this.scenes.setVisible(false);
this.keys().register(IKey.lang("blockbuster.gui.director.keys.toggle_list"), Keyboard.KEY_N, () -> toggleScenes.clickItself(GuiBase.getCurrent())).category(category);
this.keys().register(IKey.lang("blockbuster.gui.director.keys.toggle_options"), Keyboard.KEY_O, () -> toggle.clickItself(GuiBase.getCurrent())).category(category);
}
@Override
public PermissionCategory getRequiredPermission()
{
return BlockbusterPermissions.openScene;
}
public SceneLocation getLocation()
{
return this.location;
}
public Replay getReplay()
{
return this.replay;
}
public List<Replay> getReplays()
{
if (this.location.isEmpty())
{
return null;
}
return this.getLocation().getScene().replays;
}
public GuiScenePanel openScene(SceneLocation location)
{
this.scenes.setVisible(false);
return this.setScene(location);
}
public GuiScenePanel setScene(SceneLocation location)
{
this.location = location == null ? new SceneLocation() : location;
this.subChildren.setVisible(!location.isEmpty());
this.replayEditor.setVisible(!location.isEmpty());
this.scenes.setScene(location.getScene());
if (location.isEmpty())
{
this.setReplay(null);
return this;
}
this.selector.setList(location.getScene().replays);
if (!this.location.getScene().replays.isEmpty())
{
int current = this.location.getScene().replays.indexOf(this.replay);
this.setReplay(this.location.getScene().replays.get(current == -1 ? 0 : current));
}
else
{
this.setReplay(null);
}
this.fillData();
return this;
}
public GuiScenePanel set(SceneLocation location)
{
this.location = location;
this.scenes.setScene(location.getScene());
return this;
}
protected void rotationFilter()
{
int fromTest = Math.min((int) this.eulerFilterFrom.value, (int) this.eulerFilterTo.value);
int toTest = Math.max((int) this.eulerFilterFrom.value, (int) this.eulerFilterTo.value);
if (toTest - fromTest + 1 < 2)
{
this.addPopUpModal(IKey.lang("blockbuster.gui.director.rotation_filter.not_enough_frames"));
return;
}
/* wait for the requested recording to return from server */
ServerHandlerRequestRecording.requestRecording(this.replay.id, (record) ->
{
Frame.RotationChannel channel = Frame.RotationChannel.values()[this.eulerFilterChannel.getValue()];
if (record == null)
{
this.addPopUpModal(IKey.lang("blockbuster.gui.director.rotation_filter.record_not_loaded"));
return;
}
int from = MathUtils.clamp(Math.min((int) this.eulerFilterFrom.value, (int) this.eulerFilterTo.value), 0, record.frames.size() - 1);
int to = MathUtils.clamp(Math.max((int) this.eulerFilterFrom.value, (int) this.eulerFilterTo.value), 0, record.frames.size() - 1);
List<Frame> frames = RecordUtils.discontinuityEulerFilter(record.frames, from, to, channel);
if (frames.isEmpty())
{
this.addPopUpModal(IKey.lang("blockbuster.gui.director.rotation_filter.empty_filtered_frames"));
return;
}
ServerHandlerFramesOverwrite.sendFramesToServer(record.filename, frames, from, to, (obj) ->
{
this.addPopUpModal(obj.getKey());
});
});
}
private void addPopUpModal(IKey lang)
{
GuiPopUpModal modal = new GuiPopUpModal(this.mc, lang);
modal.flex().relative(this.parent).wh(200, 50);
modal.setFadeDuration(0);
modal.resize();
this.add(modal);
}
@Override
public void appear()
{
super.appear();
ClientProxy.panels.picker(this::setMorph);
if (!this.location.isEmpty())
{
this.setScene(this.location);
}
}
@Override
public void open()
{
ClientProxy.panels.morphs.reload();
this.setScene(this.location);
this.scenes.setScene(this.location.getScene());
this.scenes.updateSceneList();
}
@Override
public void close()
{
if (!OpHelper.isPlayerOp())
{
return;
}
if (this.location.isScene())
{
if (ClientProxy.panels.morphs.hasParent())
{
ClientProxy.panels.morphs.finish();
}
Dispatcher.sendToServer(new PacketSceneCast(this.location));
}
}
private void setReplay(Replay replay)
{
if (this.replay != null)
{
this.replay.morph = MorphUtils.copy(this.replay.morph);
}
this.replay = replay;
this.replayEditor.setVisible(this.replay != null);
this.mainView.setDelegate(this.replays);
this.selector.setCurrent(replay);
this.fillReplayData();
}
private void fillData()
{
this.title.setText(this.location.getScene().title);
this.startCommand.setText(this.location.getScene().startCommand);
this.stopCommand.setText(this.location.getScene().stopCommand);
this.loops.toggled(this.location.getScene().loops);
this.attach.setEnabled(false);
this.audio.clear();
this.audio.add(this.noneAudioTrack.get());
this.audio.add(ClientProxy.audio.getFileNames());
this.audio.sort();
String audio = this.location.getScene().getAudio();
this.audio.setCurrentScroll(audio == null || audio.isEmpty() ? this.noneAudioTrack.get() : audio);
this.audioShift.setValue(this.location.getScene().getAudioShift());
if (this.mc != null && this.mc.player != null)
{
ItemStack stack = this.mc.player.getHeldItemMainhand();
this.attach.setEnabled(!this.location.isEmpty() && stack.getItem() instanceof ItemPlayback);
}
}
private void fillReplayData()
{
if (this.replay == null)
{
return;
}
this.id.setText(this.replay.id);
this.name.setText(this.replay.name);
this.target.setText(this.replay.target);
this.playbackXPFood.toggled(this.replay.playBackXPFood);
this.invincible.toggled(this.replay.invincible);
this.invisible.toggled(this.replay.invisible);
this.enableBurning.toggled(this.replay.enableBurning);
this.enabled.toggled(this.replay.enabled);
this.fake.toggled(this.replay.fake);
this.teleportBack.toggled(this.replay.teleportBack);
this.renderLast.toggled(this.replay.renderLast);
this.health.setValue(this.replay.health);
this.foodLevel.setValue(this.replay.foodLevel);
this.totalExperience.setValue(this.replay.totalExperience);
this.pickMorph.setMorph(this.replay.morph);
this.selector.setCurrent(this.replay);
this.updateLabel(false);
}
/**
* Add an empty replay
*/
private void addReplay()
{
Replay replay = new Replay("");
if (this.location.isScene())
{
replay.id = this.location.getScene().getNextBaseSuffix(this.location.getScene().getId());
}
this.location.getScene().replays.add(replay);
this.setReplay(replay);
this.selector.update();
}
/**
* Duplicate a replay
*/
private void dupeReplay()
{
if (this.selector.isDeselected())
{
return;
}
Scene scene = this.location.getScene();
if (scene.dupe(scene.replays.indexOf(this.replay)))
{
this.selector.update();
this.selector.scroll.scrollTo(this.selector.getIndex() * this.selector.scroll.scrollItemSize);
this.setReplay(scene.replays.get(scene.replays.size() - 1));
}
}
/**
* Remove replay
*/
private void removeReplay()
{
if (this.selector.isDeselected())
{
return;
}
Scene scene = this.location.getScene();
int index = this.selector.getIndex();
scene.replays.remove(this.replay);
int size = scene.replays.size();
index = MathHelper.clamp(index, 0, size - 1);
this.setReplay(size == 0 ? null : scene.replays.get(index));
this.selector.update();
}
private void setMorph(AbstractMorph morph)
{
if (this.replay != null)
{
this.replay.morph = morph;
}
this.pickMorph.setMorph(morph);
}
/**
* update the labels
* @param gui true when this is called by a callback from a GuiElement
*/
private void updateLabel(boolean gui)
{
boolean error = this.replay != null && this.replay.id.isEmpty();
this.recordingId.color(error ? 0xff3355 : 0xcccccc);
if (this.replay != null && !this.replay.id.isEmpty() && gui)
{
boolean isDuplicate = false;
for (Replay element : this.scenes.parent.getLocation().getScene().replays)
{
if (element.id.equals(this.replay.id) && this.replay != element)
{
isDuplicate = true;
break;
}
}
if (isDuplicate)
{
GuiModal.addModal(this, () ->
{
GuiPopUpModal modal = new GuiPopUpModal(this.mc, IKey.lang("blockbuster.gui.director.rename_replay_dupe_modal"));
modal.flex().relative(this.parent).wh(220, 50);
return modal;
});
}
}
}
/**
* Send record message to the player
*/
private void sendRecordMessage()
{
EntityPlayer player = this.mc.player;
if (this.replay.id.isEmpty())
{
Blockbuster.l10n.error(player, "recording.fill_filename");
return;
}
String command = "/action record " + this.replay.id + " " + this.location.getFilename();
ITextComponent component = new TextComponentString(I18n.format("blockbuster.info.recording.clickhere"));
component.getStyle().setClickEvent(new ClickEvent(ClickEvent.Action.RUN_COMMAND, command));
component.getStyle().setHoverEvent(new HoverEvent(HoverEvent.Action.SHOW_TEXT, new TextComponentString(command)));
component.getStyle().setColor(TextFormatting.GRAY).setUnderlined(true);
Blockbuster.l10n.info(player, "recording.message", this.replay.id, component);
/* Add the command to the history */
List<String> messages = this.mc.ingameGUI.getChatGUI().getSentMessages();
boolean empty = messages.isEmpty();
boolean lastMessageIsntCommand = !empty && !messages.get(messages.size() - 1).equals(command);
if (lastMessageIsntCommand || empty)
{
messages.add(command);
}
}
private void attach()
{
if (CameraHandler.isApertureLoaded())
{
CameraHandler.attach(this.location, this.scenes.sceneList.getList());
}
else
{
Dispatcher.sendToServer(new PacketPlaybackButton(this.location, 0, ""));
this.mc.displayGuiScreen(null);
}
}
private void openRecordEditor()
{
if (this.replay != null && !this.replay.id.isEmpty())
{
this.dashboard.panels.setPanel(ClientProxy.panels.recordingEditorPanel);
ClientProxy.panels.recordingEditorPanel.selectRecord(this.replay.id);
ClientProxy.panels.recordingEditorPanel.records.setVisible(false);
}
}
private void updatePlayerData()
{
Dispatcher.sendToServer(new PacketUpdatePlayerData(this.replay.id));
}
private void teleport()
{
if (this.replay == null)
{
return;
}
this.mc.displayGuiScreen(null);
try
{
RecordUtils.applyFrameOnEntity(Minecraft.getMinecraft().player, ClientProxy.manager.get(this.replay.id), 0); //TODO requires client to request recording from server
}
catch (Exception e)
{
e.printStackTrace();
}
}
private void renamePrefix()
{
GuiModal.addModal(this.replayEditor, () ->
{
GuiPromptModal modal = new GuiPromptModal(this.mc, IKey.lang("blockbuster.gui.director.rename_prefix_popup"), this::renamePrefix);
modal.markIgnored().flex().relative(this.rename).y(1F).w(1F).h(120);
return modal;
});
}
private void renamePrefix(String newPrefix)
{
this.location.getScene().renamePrefix(newPrefix);
this.fillReplayData();
}
@Override
public void draw(GuiContext context)
{
if (this.scenes.isVisible())
{
int x = this.scenes.area.ex() - 20;
int y = this.scenes.area.y - 20;
Gui.drawRect(x, y, x + 20, y + 20, ColorUtils.HALF_BLACK);
}
/* Draw additional stuff */
if (this.mainView.delegate == this.replays)
{
Gui.drawRect(this.selector.area.x, this.selector.area.y, this.selector.area.ex() + 20, this.selector.area.ey(), ColorUtils.HALF_BLACK);
this.drawGradientRect(this.selector.area.x, this.selector.area.y - 16, this.selector.area.ex() + 20, this.selector.area.y, 0, ColorUtils.HALF_BLACK);
this.font.drawStringWithShadow(I18n.format("blockbuster.gui.scenes.title"), this.area.x + 10, this.area.y + 10, 0xffffff);
if (this.replay != null)
{
AbstractMorph morph = this.replay.morph;
if (morph != null)
{
int x = this.area.mx();
int y = this.area.y(0.55F);
GuiDraw.scissor(this.area.x, this.area.y, this.area.w, this.area.h, context);
morph.renderOnScreen(this.mc.player, x, y, this.area.h / 3.5F, 1.0F);
GuiDraw.unscissor(context);
}
}
}
else
{
this.font.drawStringWithShadow(I18n.format("blockbuster.gui.director.config"), this.area.x + 10, this.area.y + 10, 0xffffff);
this.font.drawStringWithShadow(I18n.format("blockbuster.gui.director.audio"), this.audio.area.x, this.audio.area.y - 12, 0xcccccc);
this.font.drawStringWithShadow(I18n.format("blockbuster.gui.director.start_command"), this.startCommand.area.x, this.startCommand.area.y - 12, 0xcccccc);
this.font.drawStringWithShadow(I18n.format("blockbuster.gui.director.stop_command"), this.stopCommand.area.x, this.stopCommand.area.y - 12, 0xcccccc);
this.font.drawStringWithShadow(I18n.format("blockbuster.gui.director.display_title"), this.title.area.x, this.title.area.y - 12, 0xcccccc);
}
if (this.location.isEmpty())
{
String no = I18n.format("blockbuster.gui.director.not_selected");
this.drawCenteredString(this.font, no, this.area.mx(), this.area.my() - 6, 0xffffff);
}
super.draw(context);
}
public void plause()
{
if (!OpHelper.isPlayerOp())
{
return;
}
if (this.location.isScene())
{
Dispatcher.sendToServer(new PacketScenePlayback(this.location));
}
}
public void record()
{
if (!OpHelper.isPlayerOp())
{
return;
}
Replay replay = this.replay;
if (replay != null && !replay.id.isEmpty() && this.location.isScene())
{
Dispatcher.sendToServer(new PacketSceneRecord(this.location, replay.id));
}
}
public void pause()
{
if (!OpHelper.isPlayerOp())
{
return;
}
if (this.location.isScene())
{
Dispatcher.sendToServer(new PacketScenePause(this.location));
}
}
} | 34,332 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiReplaySelector.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/scene/GuiReplaySelector.java | package mchorse.blockbuster.client.gui.dashboard.panels.scene;
import mchorse.blockbuster.recording.scene.Replay;
import mchorse.blockbuster.utils.mclib.BBIcons;
import mchorse.mclib.McLib;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.list.GuiListElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.utils.ColorUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.resources.I18n;
import java.util.List;
import java.util.function.Consumer;
/**
* This GUI is responsible for drawing replays available in the
* director thing
*/
public class GuiReplaySelector extends GuiListElement<Replay>
{
private String hovered;
private int hoverX;
private int hoverY;
public GuiReplaySelector(Minecraft mc, Consumer<List<Replay>> callback)
{
super(mc, callback);
this.horizontal().sorting();
this.scroll.scrollItemSize = 40;
}
@Override
public void draw(GuiContext context)
{
this.hovered = null;
super.draw(context);
if (this.hovered != null)
{
int w = this.font.getStringWidth(hovered);
int x = this.hoverX - w / 2;
Gui.drawRect(x - 2, this.hoverY - 1, x + w + 2, this.hoverY + 9, ColorUtils.HALF_BLACK);
this.font.drawStringWithShadow(this.hovered, x, this.hoverY, 0xffffff);
}
else if (this.getList().isEmpty())
{
this.drawCenteredString(this.font, I18n.format("blockbuster.gui.director.no_replays"), this.area.mx(), this.area.my() - 6, 0xffffff);
}
}
@Override
public void drawListElement(Replay replay, int i, int x, int y, boolean hover, boolean selected)
{
int w = this.scroll.scrollItemSize;
int h = this.scroll.h;
boolean isDragging = this.isDragging() && this.getDraggingIndex() == i;
if (isDragging)
{
y -= 20;
}
else
{
x += w / 2;
}
if (selected && !isDragging)
{
Gui.drawRect(x - w / 2, y, x + w / 2, y + h, 0xaa000000 + McLib.primaryColor.get());
GuiDraw.scissor(x - w / 2, y, w, h, GuiBase.getCurrent());
}
if (replay.morph != null)
{
replay.morph.renderOnScreen(this.mc.player, x, y + (int) (this.scroll.h * 0.8F), 24, 1);
}
else
{
GlStateManager.color(1, 1, 1);
BBIcons.CHICKEN.render(x - 8, y + this.scroll.h / 2 - 8);
}
if (selected && !isDragging)
{
GuiDraw.drawOutline(x - w / 2, y, x + w / 2, y + h, 0xff000000 + McLib.primaryColor.get(), 2);
GuiDraw.unscissor(GuiBase.getCurrent());
}
if (hover && !replay.id.isEmpty() && this.hovered == null)
{
this.hovered = replay.id;
this.hoverX = x;
this.hoverY = y + this.scroll.h / 2;
}
}
} | 3,180 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSceneManager.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/scene/GuiSceneManager.java | package mchorse.blockbuster.client.gui.dashboard.panels.scene;
import mchorse.blockbuster.CommonProxy;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.scene.PacketRequestScenes;
import mchorse.blockbuster.network.common.scene.PacketSceneManage;
import mchorse.blockbuster.network.common.scene.PacketSceneRequestCast;
import mchorse.blockbuster.recording.scene.Scene;
import mchorse.blockbuster.recording.scene.SceneLocation;
import mchorse.blockbuster.recording.scene.SceneManager;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.list.GuiStringListElement;
import mchorse.mclib.client.gui.framework.elements.modals.GuiConfirmModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiPromptModal;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.config.values.ValueBoolean;
import mchorse.mclib.utils.ColorUtils;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.resources.I18n;
import java.io.IOException;
import java.util.List;
/**
* Scene manager GUI
*/
public class GuiSceneManager extends GuiElement
{
public GuiScenePanel parent;
public GuiStringListElement sceneList;
/* Elements for scene manager */
public GuiIconElement add;
public GuiIconElement dupe;
public GuiIconElement rename;
public GuiIconElement remove;
public GuiSceneManager(Minecraft mc, GuiScenePanel parent)
{
super(mc);
this.parent = parent;
/* Scene manager elements */
this.sceneList = new GuiStringListElement(mc, (scene) -> this.switchScene(scene.get(0)));
this.add = new GuiIconElement(mc, Icons.ADD, (b) -> this.addScene());
this.add.tooltip(IKey.lang("blockbuster.gui.scenes.add_scene"));
this.dupe = new GuiIconElement(mc, Icons.DUPE, (b) -> this.dupeScene());
this.dupe.tooltip(IKey.lang("blockbuster.gui.scenes.dupe_scene"));
this.rename = new GuiIconElement(mc, Icons.EDIT, (b) -> this.renameScene());
this.rename.tooltip(IKey.lang("blockbuster.gui.scenes.rename_scene"));
this.remove = new GuiIconElement(mc, Icons.REMOVE, (b) -> this.removeScene());
this.remove.tooltip(IKey.lang("blockbuster.gui.scenes.remove_scene"));
this.sceneList.flex().relative(this.area).set(0, 20, 0, 0).w(1, 0).h(1, -20);
this.add.flex().relative(this.area).set(0, 2, 16, 16).x(1, -78);
this.dupe.flex().relative(this.add.resizer()).set(20, 0, 16, 16);
this.rename.flex().relative(this.dupe.resizer()).set(20, 0, 16, 16);
this.remove.flex().relative(this.rename.resizer()).set(20, 0, 16, 16);
/* Add children */
this.add(this.sceneList, this.add, this.dupe, this.rename, this.remove);
this.hideTooltip();
}
/* Popup callbacks */
private void switchScene(String scene)
{
this.parent.close();
Dispatcher.sendToServer(new PacketSceneRequestCast(new SceneLocation(scene)));
}
private void addScene()
{
GuiModal.addFullModal(this, () -> new GuiPromptModal(this.mc, IKey.lang("blockbuster.gui.scenes.add_modal"), (name) ->
{
if (this.sceneList.getList().contains(name) || !SceneManager.isValidFilename(name)) return;
Scene scene = new Scene();
scene.setId(name);
this.sceneList.add(name);
this.sceneList.sort();
this.sceneList.setCurrent(name);
this.parent.setScene(new SceneLocation(scene));
}).filename());
}
private void dupeScene()
{
if (!this.parent.getLocation().isScene())
{
return;
}
GuiModal.addFullModal(this, () ->
{
GuiToggleElement dupeRecordings = new GuiToggleElement(this.mc, IKey.lang("blockbuster.gui.scenes.dupe_recordings"), null);
GuiPromptModal modal = new GuiPromptModal(this.mc, IKey.lang("blockbuster.gui.scenes.dupe_modal"), (name) ->
{
if (this.sceneList.getList().contains(name) || !SceneManager.isValidFilename(name)) return;
Scene scene = new Scene();
scene.copy(this.parent.getLocation().getScene());
scene.setId(name);
scene.setupIds();
scene.renamePrefix(this.parent.getLocation().getScene().getId(), scene.getId(), (id) -> id + "_copy");
//copy recordings
if (dupeRecordings.isToggled())
{
Dispatcher.sendToServer(new PacketSceneManage(this.parent.getLocation().getScene().getId(), name, PacketSceneManage.DUPE));
}
this.sceneList.add(name);
this.sceneList.sort();
this.sceneList.setCurrent(name);
this.parent.setScene(new SceneLocation(scene));
this.parent.close();
});
dupeRecordings.tooltip(IKey.lang("blockbuster.gui.scenes.dupe_recordings_tooltip"));
dupeRecordings.flex().relative(modal.bar).y(-50).x(10).w(1F, -20);
modal.add(dupeRecordings);
return modal.filename().setValue(this.parent.getLocation().getFilename());
});
}
private void renameScene()
{
if (!this.parent.getLocation().isScene())
{
return;
}
GuiModal.addFullModal(this, () ->
{
GuiPromptModal modal = new GuiPromptModal(mc, IKey.lang("blockbuster.gui.scenes.rename_modal"), (name) ->
{
if (this.sceneList.getList().contains(name) || !SceneManager.isValidFilename(name)) return;
String old = this.parent.getLocation().getFilename();
this.sceneList.remove(old);
this.parent.getLocation().getScene().setId(name);
this.sceneList.add(name);
this.sceneList.sort();
this.sceneList.setCurrent(name);
this.parent.setScene(new SceneLocation(this.parent.getLocation().getScene()));
Dispatcher.sendToServer(new PacketSceneManage(old, name, PacketSceneManage.RENAME));
});
return modal.filename().setValue(this.parent.getLocation().getFilename());
});
}
private void removeScene()
{
if (!this.parent.getLocation().isScene())
{
return;
}
GuiModal.addFullModal(this, () -> new GuiConfirmModal(this.mc, IKey.lang("blockbuster.gui.scenes.remove_modal"), (value) ->
{
if (!value) return;
String name = this.parent.getLocation().getFilename();
this.sceneList.remove(name);
this.sceneList.update();
this.sceneList.setCurrent((String) null);
this.parent.setScene(new SceneLocation());
Dispatcher.sendToServer(new PacketSceneManage(name, "", PacketSceneManage.REMOVE));
}));
}
/* Scene manager methods */
public void setScene(Scene scene)
{
this.sceneList.setCurrent(scene == null ? "" : scene.getId());
}
public void updateSceneList()
{
Dispatcher.sendToServer(new PacketRequestScenes());
}
public void add(List<String> scenes)
{
String current = this.sceneList.getCurrentFirst();
this.sceneList.clear();
this.sceneList.add(scenes);
this.sceneList.sort();
this.sceneList.setCurrent(current);
}
@Override
public void draw(GuiContext context)
{
this.area.draw(0xaa000000);
Gui.drawRect(this.area.x, this.area.y, this.area.ex(), this.area.y + 20, ColorUtils.HALF_BLACK);
this.font.drawStringWithShadow(I18n.format("blockbuster.gui.scenes.title"), this.area.x + 6, this.area.y + 7, 0xffffff);
super.draw(context);
}
} | 8,272 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiRecordTimeline.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/GuiRecordTimeline.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor;
import mchorse.blockbuster.network.server.recording.actions.ServerHandlerActionsChange;
import mchorse.blockbuster.recording.actions.Action;
import mchorse.blockbuster.recording.actions.ActionRegistry;
import mchorse.blockbuster.recording.actions.MorphAction;
import mchorse.blockbuster_pack.morphs.SequencerMorph;
import mchorse.mclib.McLib;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.client.gui.utils.ScrollArea;
import mchorse.mclib.client.gui.utils.ScrollDirection;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.Color;
import mchorse.mclib.utils.ColorUtils;
import mchorse.mclib.utils.ICopy;
import mchorse.mclib.utils.MathUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import mchorse.metamorph.api.morphs.utils.Animation;
import mchorse.metamorph.api.morphs.utils.IAnimationProvider;
import mchorse.metamorph.bodypart.BodyPart;
import mchorse.metamorph.bodypart.BodyPartManager;
import mchorse.metamorph.bodypart.IBodyPartProvider;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.gui.GuiScreen;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.nbt.NBTTagList;
import net.minecraft.util.math.MathHelper;
import org.lwjgl.input.Keyboard;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class GuiRecordTimeline extends GuiElement
{
public GuiRecordingEditorPanel panel;
public ScrollArea scroll;
public ScrollArea vertical;
/**
* Pointer to the current selected action.
* Can be null
*/
private Action current;
/**
* A frame in the list can be null if it does not contain any actions
*/
private final List<List<Action>> selection = new ArrayList<>();
/**
* The tick where the selection begins
*/
private int fromTick = -1;
/**
* The current selected tick. It should always be greater or equal to {@link #fromTick}
*/
private Selection currentTick = new Selection(-1, -1);
/**
* What has been last left clicked
*/
private Selection lastClicked = new Selection(-1, -1);
public boolean lastDragging = false;
public int lastX;
public int lastY;
private int lastLeftX;
private int lastLeftY;
public int lastH;
public int lastV;
/**
* To render the actions at the mouse position correctly when dragging.
* The default value is -1 when this has not been set
*/
private int movingDx = -1;
private int movingDy = -1;
/**
* The first scroll when drawing the selection area.
* This is used to ensure continuity of the selection area when scrolling around.
*/
private int areaScrollDx = -1;
private int areaScrollDy = -1;
/**
* If this is true moving is possible
*/
public boolean canMove;
public boolean moving;
/**
* Whether the user is ready to select an area
*/
private boolean canSelectArea;
private boolean selectingArea;
public int cursor = -1;
private boolean preventMouseReleaseSelect = false;
private int adaptiveMaxIndex;
private final int itemHeight = 20;
public GuiRecordTimeline(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc);
this.scroll = new ScrollArea(34);
this.scroll.direction = ScrollDirection.HORIZONTAL;
this.scroll.scrollSpeed = 34 * 2;
this.vertical = new ScrollArea(this.itemHeight);
this.vertical.direction = ScrollDirection.VERTICAL;
this.panel = panel;
IKey category = IKey.lang("blockbuster.gui.aperture.keys.category");
this.keys().register(IKey.lang("blockbuster.gui.aperture.keys.add_morph_action"), Keyboard.KEY_M, () -> this.createAction("morph"))
.held(Keyboard.KEY_LCONTROL).category(category);
this.keys().register(IKey.lang("blockbuster.gui.record_editor.deselect"), Keyboard.KEY_ESCAPE, this::deselect)
.category(category).active(() -> this.isActive());
this.keys().register(IKey.lang("blockbuster.gui.record_editor.select_all"), Keyboard.KEY_A, this::selectAll)
.held(Keyboard.KEY_LCONTROL).category(category);
this.keys().register(IKey.lang("blockbuster.gui.record_editor.copy"), Keyboard.KEY_C, this::copyActions)
.held(Keyboard.KEY_LCONTROL).category(category);
this.keys().register(IKey.lang("blockbuster.gui.record_editor.paste"), Keyboard.KEY_V, this::pasteActions)
.held(Keyboard.KEY_LCONTROL).category(category);
this.keys().register(IKey.lang("blockbuster.gui.record_editor.cut"), Keyboard.KEY_X, this::cutActions)
.held(Keyboard.KEY_LCONTROL).category(category);
this.keys().register(IKey.lang("blockbuster.gui.duplicate"), Keyboard.KEY_D, this::dupeActions)
.held(Keyboard.KEY_LSHIFT).category(category);
this.keys().register(IKey.lang("blockbuster.gui.remove"), Keyboard.KEY_DELETE, this::removeActions).category(category);
}
/**
* @return the tick of the current selected action / frame
*/
public int getCurrentTick()
{
return this.currentTick.tick;
}
public int getCurrentIndex()
{
return this.currentTick.index;
}
/**
* This is used to determine whether you can escape out of the gui
* @return true if this selection is not empty and if it does not contain only one empty frame.
*/
public boolean isActive()
{
return !(this.selection.isEmpty() || (this.selection.size() == 1 && this.isFrameEmpty(this.selection.get(0))));
}
@Override
public void resize()
{
super.resize();
this.scroll.copy(this.area);
this.vertical.copy(this.area);
}
/**
* Update with a new recording
*/
public void reset()
{
if (this.panel.record != null)
{
this.selection.clear();
this.selectCurrent(MathUtils.clamp(this.fromTick, 0, this.panel.record.actions.size() - 1), -1);
this.scroll.setSize(this.panel.record.actions.size());
this.scroll.clamp();
this.recalculateVertical();
}
}
public void recalculateVertical()
{
int max = 0;
if (this.panel.record != null)
{
for (List<Action> actions : this.panel.record.actions)
{
if (actions != null && actions.size() > max)
{
max = actions.size();
}
}
max += 1;
}
this.vertical.setSize(max);
this.vertical.clamp();
}
@Override
public boolean mouseClicked(GuiContext context)
{
this.lastX = context.mouseX;
this.lastY = context.mouseY;
//TODO getIndex returns -2 when beyond end but returns -1 when beyond max index, but also -1 when behind beginning...
//this brings issues with interpreting!
int tick = this.scroll.getIndex(context.mouseX, context.mouseY);
int index = this.vertical.getIndex(context.mouseX, context.mouseY);
if (context.mouseButton == 0)
{
this.lastClicked = new Selection(tick, index);
this.lastLeftX = this.lastX;
this.lastLeftY = this.lastY;
}
if (context.mouseButton == 1)
{
if (this.moving || this.selectingArea)
{
this.preventMouseReleaseSelect = true;
}
this.moving = false;
this.canMove = false;
this.selectingArea = false;
}
if (context.mouseButton == 2 && this.area.isInside(context))
{
this.lastDragging = true;
this.lastH = this.scroll.scroll;
this.lastV = this.vertical.scroll;
return true;
}
if (super.mouseClicked(context) || this.scroll.mouseClicked(context) || this.vertical.mouseClicked(context))
{
this.preventMouseReleaseSelect = true;
return true;
}
if (this.scroll.isInside(context) && !this.moving && context.mouseButton == 0)
{
if (tick >= 0 && tick < this.panel.record.actions.size())
{
this.selectMouseClicked(tick, index);
}
}
return false;
}
private void selectMouseClicked(int tick, int index)
{
if (this.isInSelection(tick, index))
{
if (GuiScreen.isCtrlKeyDown())
{
this.removeFromSelection(tick, index);
}
else if (GuiScreen.isShiftKeyDown())
{
this.canSelectArea = true;
}
else
{
this.awaitMoving();
}
}
else
{
if (GuiScreen.isShiftKeyDown())
{
if (this.currentTick.tick != -1 && this.currentTick.index != -1)
{
/* select a range from current tick to clicked tick */
List<List<Action>> actionRange = this.panel.record.getActions(tick, this.currentTick.tick, index, this.currentTick.index);
this.addToSelection(Math.min(tick, this.currentTick.tick), actionRange);
}
this.selectCurrentSaveOld(tick, index);
}
else if (GuiBase.isCtrlKeyDown())
{
if (this.panel.record.getAction(tick, index) != null)
{
this.selectCurrentSaveOld(tick, index);
}
}
else if (this.panel.record.getAction(tick, index) != null)
{
this.selection.clear();
this.fromTick = tick;
this.selectCurrentSaveOld(tick, index);
this.awaitMoving();
}
else
{
this.canSelectArea = true;
}
}
}
private void awaitMoving()
{
this.canMove = true;
this.moving = false;
}
@Override
public void mouseReleased(GuiContext context)
{
super.mouseReleased(context);
if (context.mouseButton == 0)
{
if (this.moving)
{
this.moveSelectionTo(this.scroll.getIndex(context.mouseX, context.mouseY), this.vertical.getIndex(context.mouseX, context.mouseY));
}
else if (this.selectingArea)
{
if (!GuiScreen.isShiftKeyDown())
{
this.selection.clear();
}
int scrollIndex = this.scroll.getIndex(context.mouseX, context.mouseY);
int verticalIndex = this.vertical.getIndex(context.mouseX, context.mouseY);
scrollIndex = scrollIndex == -1 ? 0 : (scrollIndex == -2 ? this.panel.record.actions.size() - 1 : scrollIndex);
int frameSize = this.panel.record.getActions(scrollIndex) == null ? 1 : this.panel.record.getActions(scrollIndex).size();
verticalIndex = verticalIndex == -1 ? 0 : (verticalIndex == -2 ? frameSize - 1 : verticalIndex);
int fromSt = Math.min(this.lastClicked.tick, scrollIndex);
int toSt = Math.max(this.lastClicked.tick, scrollIndex);
int fromSi = Math.min(this.lastClicked.index, verticalIndex);
int toSi = Math.max(this.lastClicked.index, verticalIndex);
List<List<Action>> actionRange = this.panel.record.getActions(fromSt, toSt, fromSi, toSi);
int startShift = this.trimSelectionBeginning(actionRange);
this.trimSelectionEnd(actionRange);
this.addToSelection(fromSt + startShift, actionRange);
}
else if (!this.preventMouseReleaseSelect)
{
int tick = this.scroll.getIndex(context.mouseX, context.mouseY);
int index = this.vertical.getIndex(context.mouseX, context.mouseY);
if (index != -1 && 0 <= tick && tick < this.panel.record.actions.size())
{
if (!GuiScreen.isShiftKeyDown() && !GuiScreen.isCtrlKeyDown()
&& (this.isInSelection(tick, index) || this.panel.record.getAction(tick, index) == null))
{
this.selection.clear();
this.selectCurrentSaveOld(tick, index);
}
}
}
this.preventMouseReleaseSelect = false;
this.canSelectArea = false;
this.selectingArea = false;
this.canMove = false;
this.moving = false;
}
this.lastDragging = false;
this.scroll.mouseReleased(context);
this.vertical.mouseReleased(context);
}
/**
* Add the given actions to the selection starting at the specified tick.
* Nothing will be added if the tick is outside the record.actions range or if the specified actions are empty.
* @param tick
* @param actions
*/
private void addToSelection(int tick, List<List<Action>> actions)
{
if (actions.isEmpty() || this.panel.record.actions.size() <= tick || tick < 0)
{
return;
}
this.selectTick(tick);
this.selectTick(tick + actions.size() - 1);
int start = tick - this.fromTick;
for (int i = start, c = 0; i < this.selection.size() && c < actions.size(); i++, c++)
{
if (this.selection.get(i) == null && actions.get(c) != null)
{
this.selection.set(i, new ArrayList<>(actions.get(c)));
}
else if (this.selection.get(i) != null && actions.get(c) != null)
{
this.selection.get(i).removeAll(actions.get(c));
this.selection.get(i).addAll(actions.get(c));
}
}
}
@Override
public boolean mouseScrolled(GuiContext context)
{
if (super.mouseScrolled(context))
{
return true;
}
boolean shift = GuiScreen.isShiftKeyDown();
boolean alt = GuiScreen.isAltKeyDown();
if (shift && !alt)
{
return this.vertical.mouseScroll(context);
}
else if (alt && !shift)
{
int scale = this.scroll.scrollItemSize;
this.scroll.scrollItemSize = MathUtils.clamp(this.scroll.scrollItemSize + (int) Math.copySign(2, context.mouseWheel), 6, 50);
this.scroll.setSize(this.panel.record.actions.size());
this.scroll.clamp();
if (this.scroll.scrollItemSize != scale)
{
int value = this.scroll.scroll + (context.mouseX - this.area.x);
this.scroll.scroll = (int) ((value - (value - this.scroll.scroll) * (scale / (float) this.scroll.scrollItemSize)) * (this.scroll.scrollItemSize / (float) scale));
}
return true;
}
return this.scroll.mouseScroll(context);
}
/**
* @param tick
* @param index
* @return true if the action at the tick and index is selected.
* False if tick is outside of selection, if there is no action at the tick and index
* or if the action is not in the selection.
*/
private boolean isInSelection(int tick, int index)
{
if (tick < this.fromTick || this.selection.isEmpty() || this.fromTick == -1)
{
return false;
}
Action action = this.panel.record.getAction(tick, index);
int t = tick - this.fromTick;
if (action == null || t >= this.selection.size())
{
return false;
}
return this.selection.get(t) != null ? this.selection.get(t).contains(action) : false;
}
/**
* Remove the given tick and index from the selection
* and update {@link #currentTick} and {@link #fromTick} if necessary.
* @param tick
* @param index
*/
private void removeFromSelection(int tick, int index)
{
if (tick < this.fromTick)
{
return;
}
int t = tick - fromTick;
Action remove = this.panel.record.getAction(tick, index);
if (remove == null || t >= this.selection.size())
{
return;
}
if (this.selection.get(t) != null)
{
this.selection.get(t).remove(remove);
}
if (t == this.selection.size() - 1)
{
this.trimSelectionEnd(this.selection);
}
else if (t == 0)
{
this.fromTick += this.trimSelectionBeginning(this.selection);
}
else if (this.selection.get(t).isEmpty())
{
this.selection.set(t, null);
}
if (this.current == remove)
{
this.selectCurrentSaveOld(-1, -1);
}
}
/**
* Clear the selection, but keep current tick (without selecting a current action) and save the old action.
*/
public void deselect()
{
this.selection.clear();
this.selectCurrentSaveOld(this.currentTick.tick, -1);
}
public void selectAll()
{
this.selection.clear();
this.addToSelection(0, this.panel.record.getActions(0, this.panel.record.actions.size() - 1));
this.selectCurrentSaveOld(this.currentTick.tick, this.currentTick.index);
}
/**
* Trims the selection so that the first start frame is not empty or null.
* This method will remove entry from the given list, but it will not remove entries from the list entries.
* @param selection
* @return the shift from the beginning
*/
private int trimSelectionBeginning(List<List<Action>> selection)
{
int shift = 0;
for (int start = 0; start < selection.size(); start++)
{
if (this.isFrameEmpty(selection.get(start)))
{
selection.remove(start);
start--;
shift++;
}
else
{
break;
}
}
return shift;
}
private boolean isFrameEmpty(List<Action> frame)
{
boolean empty = true;
if (frame != null && !frame.isEmpty())
{
for (int a = 0; a < frame.size(); a++)
{
if (frame.get(a) != null)
{
empty = false;
}
}
}
return empty;
}
/**
* Trims the selection so that the first end frame that is not empty or null.
* This method will remove entry from the given list, but it will not remove entries from the list entries.
* @param selection
* @return the shift from the end
*/
private int trimSelectionEnd(List<List<Action>> selection)
{
int shift = 0;
for (int end = selection.size() - 1; end >= 0; end--)
{
if (this.isFrameEmpty(selection.get(end)))
{
selection.remove(end);
shift++;
}
else
{
break;
}
}
return shift;
}
/**
* Sets current action and {@link #currentTick} and updates the selection.
* This method also updates the GUI action panel of the recording editor panel.
* If the selection was empty or if {@link #fromTick} was -1 then {@link #fromTick} will be set to the provided tick
* @param tick
* @param index
*/
public void selectCurrent(int tick, int index)
{
Action selected = this.panel.record.getAction(tick, index);
if (selected != null)
{
if (this.fromTick == -1 || this.selection.isEmpty())
{
this.selection.clear();
this.fromTick = tick;
this.selection.add(null);
}
else
{
this.selectTick(tick);
}
int t = tick - this.fromTick;
if (this.selection.get(t) != null)
{
if (!this.selection.get(t).contains(selected))
{
this.selection.get(t).add(selected);
}
}
else
{
this.selection.set(t, new ArrayList<>(Arrays.asList(selected)));
}
}
else if (this.fromTick == -1 || this.selection.isEmpty())
{
this.selection.clear();
this.fromTick = tick;
this.selection.add(null);
}
this.current = selected;
this.currentTick.tick = tick;
this.currentTick.index = index;
this.panel.selectAction(this.current);
}
/**
* This method also saves the old action of the panel via {@link GuiRecordingEditorPanel#saveAction()}.
* Sets current action and {@link #currentTick} and updates the selection.
* This method also updates the GUI action panel of the recording editor panel.
* If the selection was empty or if {@link #fromTick} was -1 then {@link #fromTick} will be set to the provided tick
* @param tick
* @param index
*/
public void selectCurrentSaveOld(int tick, int index)
{
this.saveAction();
this.selectCurrent(tick, index);
}
public void saveAction()
{
this.panel.saveAction();
}
/**
* Add the given tick to the selection and close gaps to previous selection.
* The provided tick will be greater or equal to {@link #fromTick} after this operation.
* @param tick
*/
private void selectTick(int tick)
{
int t = tick - this.fromTick;
int start = (tick < this.fromTick) ? 0 : ((t >= this.selection.size()) ? this.selection.size() : 0);
int end = (tick < this.fromTick) ? this.fromTick - tick : ((t >= this.selection.size()) ? t + 1: 0);
for (int i = start; i < end; i++)
{
this.selection.add(i, null);
}
if (tick < this.fromTick)
{
this.fromTick = tick;
}
}
/**
* Sort the given actions to the original actions list from the recording.
* This should be used for example when copying or moving so the order of selection doesn't
* change the order of the actions when inserted.
* @param actions
*/
private void sortToOriginal(List<List<Action>> actions)
{
for (int tick = 0; tick < actions.size(); tick++)
{
if (actions.get(tick) != null && !actions.get(tick).isEmpty())
{
List<Action> frameList = new ArrayList<>();
boolean added = false;
for (int a = 0; a < actions.get(tick).size(); a++)
{
int newIndex = this.panel.record.getActionIndex(this.fromTick + tick, actions.get(tick).get(a));
if (newIndex != -1)
{
if (newIndex >= frameList.size())
{
frameList.addAll(Arrays.asList(new Action[newIndex - frameList.size() + 1]));
}
frameList.set(newIndex, actions.get(tick).get(a));
if (!added)
{
added = actions.get(tick).get(a) != null;
}
}
}
if (added)
{
this.removeNulls(frameList);
actions.set(tick, frameList);
}
}
}
}
private void removeNulls(List<Action> frame)
{
for (int s = 0, e = frame.size() - 1; s < frame.size() && e >= 0; s++, e--)
{
if (frame.get(e) == null)
{
frame.remove(e);
e--;
}
if (frame.get(s) == null)
{
frame.remove(s);
s--;
e--;
}
if (s >= e) break;
}
}
private void moveSelectionTo(int tick, int index)
{
/* beyond start */
if (tick == -1)
{
tick = 0;
}
/* beyond end */
else if (tick == -2)
{
tick = this.panel.record.actions.size() - this.selection.size();
}
else
{
tick = tick + this.fromTick - this.lastClicked.tick;
}
if (index == -1)
{
index = 0;
}
else if (index == -2)
{
index = this.panel.record.actions.get(tick) == null ? 0 : this.panel.record.actions.get(tick).size() - 1;
}
List<List<Action>> selectionCopy = new ArrayList<>(this.selection);
this.sortToOriginal(selectionCopy);
int start = this.trimSelectionBeginning(selectionCopy);
this.trimSelectionEnd(selectionCopy);
if (selectionCopy.isEmpty())
{
return;
}
Action current = this.current;
int dT = this.currentTick.tick - this.fromTick;
this.removeActions();
this.selection.clear();
this.selection.addAll(selectionCopy);
tick += start;
/* move it back if outside of range */
if (tick < 0)
{
tick = 0;
}
else if (tick + this.selection.size() - 1 >= this.panel.record.actions.size())
{
tick -= tick + this.selection.size() - 1 - this.panel.record.actions.size() + 1;
}
this.fromTick = tick;
this.currentTick.tick = tick + dT - start;
this.addActions(tick, index, selectionCopy);
this.selectCurrent(this.currentTick.tick, this.panel.record.getActionIndex(this.currentTick.tick, current));
}
public void cutActions()
{
if (this.fromTick == -1 || this.selection.isEmpty())
{
return;
}
this.copyActions();
this.removeActions();
}
public void copyActions()
{
if (this.fromTick == -1 || this.selection.isEmpty())
{
return;
}
List<List<Action>> selectionCopy = new ArrayList<>(this.selection);
this.sortToOriginal(selectionCopy);
this.trimSelectionBeginning(selectionCopy);
this.trimSelectionEnd(selectionCopy);
if (selectionCopy.isEmpty())
{
return;
}
NBTTagList list = new NBTTagList();
for (List<Action> frame : selectionCopy)
{
NBTTagList frameNBT = new NBTTagList();
if (frame != null)
{
for (Action action : frame)
{
if (action == null) continue;
NBTTagCompound actionNBT = new NBTTagCompound();
actionNBT.setString("ActionType", ActionRegistry.NAME_TO_CLASS.inverse().get(action.getClass()));
action.toNBT(actionNBT);
frameNBT.appendTag(actionNBT);
}
}
list.appendTag(frameNBT);
}
this.panel.buffer = new NBTTagCompound();
this.panel.buffer.setTag("Actions", list);
}
public void pasteActions()
{
if (this.panel.buffer == null || !this.panel.buffer.hasKey("Actions") || this.currentTick.tick == -1)
{
return;
}
List<List<Action>> copied = new ArrayList<>();
if (this.panel.buffer.getTag("Actions") instanceof NBTTagList)
{
NBTTagList nbtList = (NBTTagList) this.panel.buffer.getTag("Actions");
for (int i = 0; i < nbtList.tagCount(); i++)
{
if (nbtList.get(i) == null || !(nbtList.get(i) instanceof NBTTagList))
{
copied.add(null);
continue;
}
List<Action> frame = null;
NBTTagList frameNBT = (NBTTagList) nbtList.get(i);
//TODO externalise parsing of action data - checkout Record too
for (int a = 0; a < frameNBT.tagCount(); a++)
{
if (frameNBT.get(a) instanceof NBTTagCompound)
{
NBTTagCompound actionNBT = (NBTTagCompound) frameNBT.get(a);
if (actionNBT.hasKey("ActionType"))
{
try
{
Action action = ActionRegistry.fromName(actionNBT.getString("ActionType"));
action.fromNBT(actionNBT);
if (frame == null)
{
frame = new ArrayList<>();
}
frame.add(action);
}
catch (Exception e)
{ }
}
}
}
copied.add(frame);
}
}
this.trimSelectionBeginning(copied);
this.trimSelectionEnd(copied);
if (copied.isEmpty())
{
return;
}
this.saveAction();
if (this.currentTick.index < 0 || this.current == null)
{
this.addActions(this.currentTick.tick, -1, copied);
}
else
{
this.addActions(this.currentTick.tick, this.currentTick.index, copied);
}
this.selection.clear();
this.selection.addAll(copied);
this.selectCurrent(this.currentTick.tick, -1);
}
public void createAction(String str)
{
if (!ActionRegistry.NAME_TO_CLASS.containsKey(str)
|| this.currentTick.tick < 0 || this.currentTick.tick >= this.panel.record.actions.size())
{
return;
}
try
{
Action action = ActionRegistry.fromName(str);
int tick = this.currentTick.tick;
int index = this.currentTick.index;
List<List<Action>> insert = new ArrayList<>();
insert.add(new ArrayList<>(Arrays.asList(action)));
this.addActions(tick, index, insert);
this.selection.clear();
this.selectCurrentSaveOld(tick, this.panel.record.getActionIndex(tick, action));
}
catch (Exception e)
{
e.printStackTrace();
}
}
public void dupeActions()
{
if (this.fromTick < 0 || this.selection.isEmpty())
{
return;
}
int tick = this.fromTick;
int index = this.currentTick.index == -1 ? 0 : (this.currentTick.index == -2 ? -1 : this.currentTick.index);
List<List<Action>> selectionCopy = new ArrayList<>(this.selection);
if (selectionCopy.isEmpty())
{
return;
}
this.sortToOriginal(selectionCopy);
int start = this.trimSelectionBeginning(selectionCopy);
this.trimSelectionEnd(selectionCopy);
Action newCurrent = null;
for (int t = 0; t < selectionCopy.size(); t++)
{
if (selectionCopy.get(t) != null && !selectionCopy.get(t).isEmpty())
{
for (int a = 0; a < selectionCopy.get(t).size(); a++)
{
if (selectionCopy.get(t).get(a) == null) continue;
try
{
//TODO implement copy interface for actions...
Action newAction = ActionRegistry.fromType(ActionRegistry.getType(selectionCopy.get(t).get(a)));
NBTTagCompound tag = new NBTTagCompound();
selectionCopy.get(t).get(a).toNBT(tag);
newAction.fromNBT(tag);
if (selectionCopy.get(t).get(a) == this.current)
{
newCurrent = newAction;
}
selectionCopy.get(t).set(a, newAction);
}
catch (Exception e)
{}
}
}
}
tick += start;
this.addActions(tick, index, selectionCopy);
this.selection.clear();
this.addToSelection(tick, selectionCopy);
this.selectCurrentSaveOld(this.currentTick.tick, this.panel.record.getActionIndex(this.currentTick.tick, newCurrent));
}
private void addActions(int tick, int index, List<List<Action>> actions)
{
if (index < 0)
{
ServerHandlerActionsChange.addActions(actions, this.panel.record, tick);
}
else
{
ServerHandlerActionsChange.addActions(actions, this.panel.record, tick, index);
}
this.recalculateVertical();
}
/**
* Remove selected actions, send to server, clear selection and set current to none
*/
public void removeActions()
{
if (this.fromTick == -1 || this.selection.isEmpty())
{
return;
}
List<List<Action>> selectionCopy = new ArrayList<>(this.selection);
int startShift = this.trimSelectionBeginning(selectionCopy);
this.trimSelectionEnd(selectionCopy);
if (selectionCopy.isEmpty())
{
return;
}
int from = this.fromTick + startShift;
List<List<Boolean>> deletionMask = this.panel.record.getActionsMask(from, selectionCopy);
this.saveAction();
ServerHandlerActionsChange.deleteActions(this.panel.record, from, deletionMask);
/* deselect without saving previous action */
this.selection.clear();
this.selectCurrent(this.currentTick.tick, -1);
this.recalculateVertical();
}
@Override
public void draw(GuiContext context)
{
if (this.panel.record == null)
{
return;
}
int mouseX = context.mouseX;
int mouseY = context.mouseY;
int count = this.panel.record.actions.size();
if (this.lastDragging)
{
this.scroll.scroll = this.lastH + (this.lastX - mouseX);
this.scroll.clamp();
this.vertical.scroll = this.lastV + (this.lastY - mouseY);
this.vertical.clamp();
}
if (!this.moving && (Math.abs(mouseX - this.lastX) > 2 || Math.abs(mouseY - this.lastY) > 2))
{
if (this.canMove)
{
this.moving = true;
}
if (this.canSelectArea)
{
this.selectingArea = true;
}
}
this.scroll.drag(mouseX, mouseY);
this.vertical.drag(mouseX, mouseY);
this.scroll.draw(ColorUtils.HALF_BLACK);
Gui.drawRect(this.area.ex(), this.area.y, this.area.ex() + 20, this.area.ey(), 0xff222222);
Gui.drawRect(this.area.x - 20, this.area.y, this.area.x, this.area.ey(), 0xff222222);
GuiDraw.drawHorizontalGradientRect(this.area.ex() - 8, this.area.y, this.area.ex(), this.area.ey(), 0, ColorUtils.HALF_BLACK, 0);
GuiDraw.drawHorizontalGradientRect(this.area.x, this.area.y, this.area.x + 8, this.area.ey(), ColorUtils.HALF_BLACK, 0, 0);
int max = this.area.x + this.scroll.scrollItemSize * count;
if (max < this.area.ex())
{
Gui.drawRect(max, this.area.y, this.area.ex(), this.area.ey(), 0xaa000000);
}
GuiDraw.scissor(this.area.x, this.area.y, this.area.w, this.area.h, context);
int w = this.scroll.scrollItemSize;
int index = this.scroll.scroll / w;
int diff = index;
index -= this.adaptiveMaxIndex;
index = index < 0 ? 0 : index;
diff = diff - index;
this.adaptiveMaxIndex = 0;
for (int i = index, c = i + this.area.w / w + 2 + diff; i < c; i++)
{
int x = this.scroll.x - this.scroll.scroll + i * w;
if (i < count)
{
Gui.drawRect(x, this.scroll.y, x + 1, this.scroll.ey(), 0x22ffffff);
}
int toTick = this.selection.isEmpty() ? this.fromTick : this.fromTick + this.selection.size() - 1;
if (this.fromTick <= i && i <= toTick)
{
Gui.drawRect(x, this.scroll.y, x + w + 1, this.scroll.ey(), 0x440088ff);
}
if (i >= 0 && i < count)
{
List<Action> actions = this.panel.record.actions.get(i);
if (actions != null)
{
int j = 0;
for (Action action : actions)
{
if (this.moving && this.isInSelection(i, j))
{
j++;
continue;
}
int y = this.scroll.y + j * this.itemHeight - this.vertical.scroll;
int scrollIndex = this.scroll.getIndex(mouseX, mouseY);
int verticalIndex = this.vertical.getIndex(mouseX, mouseY);
scrollIndex = scrollIndex == -1 ? 0 : (scrollIndex == -2 ? count - 1 : scrollIndex);
verticalIndex = verticalIndex == -1 ? 0 : (verticalIndex == -2 ? actions.size() - 1 : verticalIndex);
int fromSt = Math.min(this.lastClicked.tick, scrollIndex);
int toSt = Math.max(this.lastClicked.tick, scrollIndex);
int fromSi = Math.min(this.lastClicked.index, verticalIndex);
int toSi = Math.max(this.lastClicked.index, verticalIndex);
boolean selected;
if (this.selectingArea)
{
selected = fromSt <= i && i <= toSt && fromSi <= j && j <= toSi;
if (GuiScreen.isShiftKeyDown())
{
selected = selected || this.isInSelection(i, j);
}
}
else
{
selected = this.isInSelection(i, j);
}
this.drawAction(action, String.valueOf(j), x, y, selected);
j++;
}
}
}
}
for (int i = index, c = i + this.area.w / w + 2 + diff; i < c; i++)
{
if (i % 5 == 0 && i < count && i != this.cursor)
{
int x = this.scroll.x - this.scroll.scroll + i * w;
int y = this.scroll.ey() - 12;
String str = String.valueOf(i);
this.drawGradientRect(x + 1, y - 6, x + w, y + 12, 0, ColorUtils.HALF_BLACK);
this.font.drawStringWithShadow(str, x + (this.scroll.scrollItemSize - this.font.getStringWidth(str) + 2) / 2, y, 0xffffff);
}
}
this.scroll.drawScrollbar();
this.vertical.drawScrollbar();
/* Draw cursor (tick indicator) */
if (this.cursor >= 0 && this.cursor < this.panel.record.actions.size())
{
int x = this.scroll.x - this.scroll.scroll + this.cursor * w;
int cursorX = x + 2;
String label = this.cursor + "/" + this.panel.record.actions.size();
int width = this.font.getStringWidth(label);
int height = 2 + this.font.FONT_HEIGHT;
int offsetY = this.scroll.ey() - height;
if (cursorX + width + 4 > this.scroll.ex())
{
cursorX -= width + 4 + 2;
}
Gui.drawRect(x, this.scroll.y, x + 2, this.scroll.ey(), 0xff57f52a);
Gui.drawRect(cursorX, offsetY, cursorX + width + 4, offsetY + height, 0xaa57f52a);
this.font.drawStringWithShadow(label, cursorX + 2, offsetY + 2, 0xffffff);
}
String label = this.panel.record.filename;
GuiDraw.drawTextBackground(this.font, label, this.area.ex() - this.font.getStringWidth(label) - 5, this.area.ey() - 13, 0xffffff, 0xaa000000 + McLib.primaryColor.get());
GuiDraw.unscissor(context);
if (this.moving)
{
int x = mouseX;
int y = mouseY;
int posX = w * (this.lastClicked.tick) + this.scroll.x - this.scroll.scroll;
int posY = this.itemHeight * this.lastClicked.index + this.scroll.y - this.vertical.scroll;
if (this.movingDx == -1)
{
this.movingDx = mouseX - posX;
}
if (this.movingDy == -1)
{
this.movingDy = mouseY - posY;
}
x -= this.movingDx - w * (this.fromTick - this.lastClicked.tick);
y -= this.movingDy + this.itemHeight * this.lastClicked.index;
int y0 = y;
for (int tick = this.fromTick; tick < this.panel.record.actions.size(); tick++)
{
List<Action> frame = this.panel.record.actions.get(tick);
if (frame != null)
{
for (int i = 0; i < frame.size(); i++)
{
if (this.isInSelection(tick, i))
{
this.drawAction(frame.get(i), String.valueOf(i), x, y, true);
}
y += this.itemHeight;
}
}
y = y0;
x += w;
}
}
else
{
this.movingDx = -1;
this.movingDy = -1;
}
if (this.selectingArea)
{
if (this.areaScrollDx == -1)
{
this.areaScrollDx = this.scroll.scroll;
}
if (this.areaScrollDy == -1)
{
this.areaScrollDy = this.vertical.scroll;
}
Gui.drawRect(this.lastLeftX - (this.scroll.scroll - this.areaScrollDx), this.lastLeftY - (this.vertical.scroll - this.areaScrollDy), mouseX, mouseY, 0x440088FF);
}
else
{
this.areaScrollDy = -1;
this.areaScrollDx = -1;
}
super.draw(context);
this.cursor = -1;
}
private void drawAction(Action action, String label, int x, int y, boolean selected)
{
int w = this.scroll.scrollItemSize;
float hue = ((ActionRegistry.getType(action) - 1) / ((float) ActionRegistry.getMaxID()));
int color = MathHelper.hsvToRGB(hue, 1F, 1F);
int offset = this.scroll.scrollItemSize < 18 ? (this.scroll.scrollItemSize - this.font.getStringWidth(label)) / 2 : 6;
this.drawAnimationLength(action, x, y, color, selected);
Gui.drawRect(x, y, x + w, y + this.itemHeight, color + ColorUtils.HALF_BLACK);
this.font.drawStringWithShadow(label, x + offset, y + 6, 0xffffff);
if (selected)
{
/* get complementary color, but ignore purple and blue colors - they don't pop enough */
float hueSelected = MathUtils.clamp((hue - 0.5F) < 0 ? 0.5F + hue : hue - 0.5F, 0, 0.5F);
int c = action == this.current ? (new Color(MathHelper.hsvToRGB(hueSelected, 0.5F, 1F), false)).getRGBAColor() : 0xffffffff;
int border = action == this.current ? 2 : 1;
GuiDraw.drawOutline(x, y, x + w, y + this.itemHeight, c, border);
}
}
private void drawAnimationLength(Action action, int x, int y, int color, boolean selected)
{
if (action instanceof MorphAction)
{
MorphAction morphAction = (MorphAction) action;
int ticks = this.getLength(morphAction.morph);
if (ticks > 1)
{
ticks -= 1;
int offset = x + this.scroll.scrollItemSize;
Gui.drawRect(offset, y + 8, offset + ticks * this.scroll.scrollItemSize, y + 12, selected ? 0xffffffff : color + 0x33000000);
Gui.drawRect(offset + ticks * this.scroll.scrollItemSize - 1, y, offset + ticks * this.scroll.scrollItemSize, y + this.itemHeight, selected ? 0xffffffff : 0xff000000 + color);
}
this.adaptiveMaxIndex = Math.max(ticks, this.adaptiveMaxIndex);
}
}
private int getLength(AbstractMorph morph)
{
int ticks = 0;
if (morph instanceof IAnimationProvider)
{
Animation animation = ((IAnimationProvider) morph).getAnimation();
if (animation.animates)
{
ticks = animation.duration;
}
}
else if (morph instanceof SequencerMorph)
{
SequencerMorph sequencerMorph = (SequencerMorph) morph;
ticks = (int) sequencerMorph.getDuration();
}
if (morph instanceof IBodyPartProvider)
{
BodyPartManager manager = ((IBodyPartProvider) morph).getBodyPart();
for (BodyPart part : manager.parts)
{
if (!part.morph.isEmpty() && part.limb != null && !part.limb.isEmpty())
{
ticks = Math.max(ticks, this.getLength(part.morph.get()));
}
}
}
return ticks;
}
public static class Selection implements ICopy<Selection>
{
private int tick;
private int index;
public Selection(int tick, int index)
{
this.set(tick, index);
}
public void set(int tick, int index)
{
this.tick = tick;
this.index = index;
}
public int getTick()
{
return this.tick;
}
public int getIndex()
{
return this.index;
}
@Override
public Selection copy()
{
Selection copy = new Selection(this.tick, this.index);
return copy;
}
}
} | 46,810 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiRecordingEditorPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/GuiRecordingEditorPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.aperture.CameraHandler;
import mchorse.blockbuster.client.gui.dashboard.GuiBlockbusterPanel;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions.*;
import mchorse.blockbuster.events.ActionPanelRegisterEvent;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.recording.actions.PacketRequestAction;
import mchorse.blockbuster.network.common.recording.actions.PacketRequestActions;
import mchorse.blockbuster.network.common.scene.PacketSceneRecord;
import mchorse.blockbuster.network.common.scene.sync.PacketScenePlay;
import mchorse.blockbuster.network.server.recording.actions.ServerHandlerActionsChange;
import mchorse.blockbuster.recording.RecordUtils;
import mchorse.blockbuster.recording.actions.*;
import mchorse.blockbuster.recording.data.Record;
import mchorse.blockbuster.recording.scene.SceneLocation;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.GuiDelegateElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.list.GuiLabelSearchListElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.mclib.GuiDashboard;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.Label;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.Direction;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraftforge.common.MinecraftForge;
import org.lwjgl.input.Keyboard;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class GuiRecordingEditorPanel extends GuiBlockbusterPanel
{
/**
* A map of action editing panels mapped to their classes
*/
public Map<Class<? extends Action>, GuiActionPanel<? extends Action>> panels = new HashMap<Class<? extends Action>, GuiActionPanel<? extends Action>>();
public GuiRecordList records;
public GuiRecordTimeline timeline;
public GuiDelegateElement<GuiActionPanel<? extends Action>> actionEditor;
public GuiIconElement add;
public GuiIconElement dupe;
public GuiIconElement remove;
public GuiIconElement capture;
public GuiIconElement cut;
public GuiIconElement copy;
public GuiIconElement paste;
public GuiIconElement teleport;
public GuiIconElement open;
public GuiLabelSearchListElement<String> list;
public Record record;
public NBTTagCompound buffer;
public GuiRecordingEditorPanel(Minecraft mc, GuiDashboard dashboard)
{
super(mc, dashboard);
this.timeline = new GuiRecordTimeline(mc, this);
this.timeline.setVisible(false);
this.records = new GuiRecordList(mc, this);
this.actionEditor = new GuiDelegateElement<GuiActionPanel<? extends Action>>(mc, null);
/* Add/remove */
this.add = new GuiIconElement(mc, Icons.ADD, (b) -> this.list.toggleVisible());
this.add.tooltip(IKey.lang("blockbuster.gui.add"), Direction.LEFT);
this.dupe = new GuiIconElement(mc, Icons.DUPE, (b) -> this.timeline.dupeActions());
this.dupe.tooltip(IKey.lang("blockbuster.gui.duplicate"), Direction.LEFT);
this.remove = new GuiIconElement(mc, Icons.REMOVE, (b) -> this.timeline.removeActions());
this.remove.tooltip(IKey.lang("blockbuster.gui.remove"), Direction.LEFT);
this.capture = new GuiIconElement(mc, Icons.SPHERE, (b) -> this.capture());
this.capture.tooltip(IKey.lang("blockbuster.gui.record_editor.capture"), Direction.LEFT);
this.cut = new GuiIconElement(mc, Icons.CUT, (icon) -> this.timeline.cutActions());
this.cut.tooltip(IKey.lang("blockbuster.gui.record_editor.cut"), Direction.RIGHT);
this.copy = new GuiIconElement(mc, Icons.COPY, (icon) -> this.timeline.copyActions());
this.copy.tooltip(IKey.lang("blockbuster.gui.record_editor.copy"), Direction.RIGHT);
this.paste = new GuiIconElement(mc, Icons.PASTE, (b) -> this.timeline.pasteActions());
this.paste.tooltip(IKey.lang("blockbuster.gui.record_editor.paste"), Direction.RIGHT);
this.teleport = new GuiIconElement(mc, Icons.MOVE_TO, (b) -> this.teleport());
this.teleport.tooltip(IKey.lang("blockbuster.gui.record_editor.teleport"), Direction.RIGHT);
this.list = new GuiLabelSearchListElement<String>(mc, (str) ->
{
this.timeline.createAction(str.get(0).value);
this.list.setVisible(false);
});
this.list.label(IKey.lang("blockbuster.gui.search"));
this.list.list.background();
for (String key : ActionRegistry.NAME_TO_CLASS.keySet())
{
IKey title = IKey.lang("blockbuster.gui.record_editor.actions." + key + ".title");
this.list.list.add(new Label<String>(title, key));
}
this.list.filter("", false);
this.add.flex().relative(this.timeline).x(1F);
this.dupe.flex().relative(this.add.resizer()).y(20);
this.remove.flex().relative(this.dupe.resizer()).y(20);
this.capture.flex().relative(this.remove.resizer()).y(20);
this.cut.flex().relative(this.timeline).x(-20);
this.copy.flex().relative(this.cut.resizer()).y(20);
this.paste.flex().relative(this.copy.resizer()).y(20);
this.teleport.flex().relative(this.paste.resizer()).y(20);
this.list.flex().set(0, 0, 80, 80).relative(this.timeline.area).x(1, -80);
this.open = new GuiIconElement(mc, Icons.MORE, (b) -> this.records.toggleVisible());
this.open.flex().relative(this.area).set(0, 2, 24, 24).x(1, -28);
this.add(this.open);
this.timeline.add(this.add, this.dupe, this.remove, this.capture, this.cut, this.copy, this.paste, this.teleport, this.list);
IKey category = IKey.lang("blockbuster.gui.aperture.keys.category");
this.timeline.keys().register(IKey.lang("blockbuster.gui.record_editor.capture"), Keyboard.KEY_R, this::capture)
.held(Keyboard.KEY_LCONTROL).category(category);
this.timeline.keys().register(IKey.lang("blockbuster.gui.record_editor.teleport"), Keyboard.KEY_T, this::teleport)
.held(Keyboard.KEY_LCONTROL).category(category);
this.keys().register(IKey.lang("blockbuster.gui.aperture.keys.toggle_list"), Keyboard.KEY_L, () -> this.open.clickItself(GuiBase.getCurrent()))
.held(Keyboard.KEY_LCONTROL).category(category);
}
@SuppressWarnings({"rawtypes", "unchecked"})
public GuiActionPanel<? extends Action> getActionPanel(Action action)
{
if (action == null)
{
return null;
}
GuiActionPanel panel = this.panels.get(action.getClass());
if (panel == null)
{
panel = this.panels.get(Action.class);
}
panel.fill(action);
return panel;
}
private void capture()
{
if (this.record == null)
{
return;
}
int offset = this.getOffset();
if (offset >= 0)
{
SceneLocation scene = CameraHandler.isCameraEditorOpen() ? CameraHandler.get() : null;
CameraHandler.closeScreenOrCameraEditor();
if (scene != null)
{
Dispatcher.sendToServer(new PacketScenePlay(scene, PacketScenePlay.STOP, 0));
}
Dispatcher.sendToServer(new PacketSceneRecord(scene, this.record.filename, offset));
}
}
private void teleport()
{
if (this.record == null)
{
return;
}
int offset = this.getOffset();
if (offset >= 0)
{
SceneLocation scene = CameraHandler.get();
if (scene != null)
{
Dispatcher.sendToServer(new PacketScenePlay(scene, PacketScenePlay.STOP, 0));
}
GuiBase.getCurrent().screen.closeThisScreen();
RecordUtils.applyFrameOnEntity(Minecraft.getMinecraft().player, this.record, offset - record.preDelay);
}
}
private int getOffset()
{
return this.timeline.getCurrentTick();
}
@Override
public void open()
{
this.records.clear();
Dispatcher.sendToServer(new PacketRequestActions());
this.timeline.removeFromParent();
this.timeline.flex().reset().relative(this.area).x(20).y(1F, -80).h(80).w(1F, -40);
this.actionEditor.removeFromParent();
this.actionEditor.flex().reset().relative(this.area).w(1F).h(1, -80);
this.records.removeFromParent();
this.records.flex().reset().relative(this).w(120).x(1, -120).hTo(this.timeline.flex());
this.prepend(this.records);
this.add(this.actionEditor, this.timeline);
this.updateEditorWidth();
if (this.record != null && this.record != ClientProxy.manager.records.get(this.record.filename))
{
this.selectRecord(this.record.filename);
}
if (this.panels.isEmpty())
{
GuiEmptyActionPanel empty = new GuiEmptyActionPanel(this.mc, this);
this.panels.put(Action.class, empty);
this.panels.put(ChatAction.class, new GuiChatActionPanel(this.mc, this));
this.panels.put(DropAction.class, new GuiDropActionPanel(this.mc, this));
this.panels.put(EquipAction.class, new GuiEquipActionPanel(this.mc, this));
this.panels.put(HotbarChangeAction.class, new GuiHotbarChangeActionPanel(this.mc, this));
this.panels.put(ShootArrowAction.class, new GuiShootArrowActionPanel(this.mc, this));
this.panels.put(PlaceBlockAction.class, new GuiPlaceBlockActionPanel(this.mc, this));
this.panels.put(MountingAction.class, new GuiMountingActionPanel(this.mc, this));
this.panels.put(InteractBlockAction.class, new GuiBlockActionPanel<InteractBlockAction>(this.mc, this));
this.panels.put(BreakBlockAction.class, new GuiBreakBlockActionPanel(this.mc, this));
this.panels.put(MorphAction.class, new GuiMorphActionPanel(this.mc, this));
this.panels.put(AttackAction.class, new GuiDamageActionPanel(this.mc, this));
this.panels.put(DamageAction.class, new GuiDamageActionPanel(this.mc, this));
this.panels.put(CommandAction.class, new GuiCommandActionPanel(this.mc, this));
this.panels.put(BreakBlockAnimation.class, new GuiBreakBlockAnimationPanel(this.mc, this));
this.panels.put(ItemUseAction.class, new GuiItemUseActionPanel<ItemUseAction>(this.mc, this));
this.panels.put(ItemUseBlockAction.class, new GuiItemUseBlockActionPanel(this.mc, this));
this.panels.put(InteractEntityAction.class, new GuiInteractEntityActionPanel(this.mc, this));
MinecraftForge.EVENT_BUS.post(new ActionPanelRegisterEvent(this));
}
}
@Override
public void appear()
{
super.appear();
ClientProxy.panels.picker((morph) ->
{
if (this.actionEditor.delegate != null)
{
this.actionEditor.delegate.setMorph(morph);
}
});
}
@Override
public void close()
{
this.saveAction();
}
public void saveAction()
{
if (this.actionEditor.delegate != null && this.record != null)
{
this.actionEditor.delegate.disappear();
if (this.actionEditor.delegate.action != null)
{
/* so this method is independent from the current tick and index of GuiRecordTimeline */
int[] found = this.record.findAction(this.actionEditor.delegate.action);
if (found[0] != -1 && found[1] != -1)
{
/* save the old action */
ServerHandlerActionsChange.editAction(this.actionEditor.delegate.action, this.record, found[0], found[1]);
}
}
//TODO out of scope for this method to reset delegate GUI
this.actionEditor.delegate = null;
}
}
public void addRecords(List<String> records)
{
this.records.add(records);
if (this.record != null)
{
this.records.records.list.setCurrent(this.record.filename);
}
}
/**
* Select the record by the filename - request actions from the server
* @param str
*/
public void selectRecord(String str)
{
//this.timeline.reset();
this.saveAction();
Dispatcher.sendToServer(new PacketRequestAction(str, true));
}
//TODO This needs refactoring... data flow is not clear and ClientHandlerActions receiver shouldn't control GUI...
/**
* When the server sends back actions after the request {@link #selectRecord(String)} - select the recording
* @param record
*/
public void selectRecord(Record record)
{
this.record = record;
this.timeline.setVisible(record != null);
this.timeline.reset();
this.setDelegate(null);
this.list.setVisible(false);
}
public void reselectRecord(Record record)
{
if (this.record != null && this.record.filename.equals(record.filename))
{
this.record.preDelay = record.preDelay;
this.record.postDelay = record.postDelay;
}
}
public void selectAction(Action action)
{
this.setDelegate(this.getActionPanel(action));
}
public void updateEditorWidth()
{
if (this.records.isVisible())
{
this.actionEditor.flex().wTo(this.records.area);
}
else
{
this.actionEditor.flex().w(1F);
}
this.actionEditor.resize();
}
public void setDelegate(GuiActionPanel<? extends Action> panel)
{
if (this.actionEditor.delegate != null)
{
this.actionEditor.delegate.disappear();
}
this.actionEditor.setDelegate(panel);
}
@Override
public void draw(GuiContext context)
{
if (this.record == null)
{
this.drawCenteredString(this.font, I18n.format("blockbuster.gui.record_editor.not_selected"), this.area.mx(), this.area.my() - 6, 0xffffff);
}
super.draw(context);
}
} | 14,631 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiRecordList.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/GuiRecordList.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.aperture.CameraHandler;
import mchorse.blockbuster.recording.scene.Replay;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.list.GuiStringSearchListElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import net.minecraft.client.gui.Gui;
import net.minecraft.client.resources.I18n;
import java.util.List;
public class GuiRecordList extends GuiElement
{
public GuiRecordingEditorPanel panel;
public GuiStringSearchListElement records;
public boolean director;
public GuiRecordList(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc);
this.panel = panel;
this.records = new GuiStringSearchListElement(mc, (str) -> this.panel.selectRecord(str.get(0)));
this.records.flex().relative(this.area).set(10, 35, 0, 0).h(1, -45).w(1, -20);
this.records.label = IKey.lang("blockbuster.gui.search");
this.add(this.records);
}
public void clear()
{
this.records.list.clear();
this.records.filter("", true);
}
public void add(List<String> records)
{
List<Replay> replays = ClientProxy.panels.scenePanel.getReplays();
boolean loadAll = replays == null || !CameraHandler.canSync() || !CameraHandler.isCameraEditorOpen();
if (loadAll)
{
/* Display all replays */
for (String record : records)
{
this.records.list.add(record);
}
}
else
{
/* Display only current director block's replays */
for (Replay replay : replays)
{
if (records.contains(replay.id) && !this.records.list.getList().contains(replay.id))
{
this.records.list.getList().add(replay.id);
}
}
}
this.director = !loadAll;
this.records.filter("", true);
this.records.list.update();
}
@Override
public void toggleVisible()
{
super.toggleVisible();
this.panel.updateEditorWidth();
}
@Override
public void setVisible(boolean visible)
{
super.setVisible(visible);
this.panel.updateEditorWidth();
}
@Override
public void draw(GuiContext context)
{
this.area.draw(0xff222222);
Gui.drawRect(this.area.x, this.area.y, this.area.ex(), this.area.y + 30, 0x44000000);
this.font.drawStringWithShadow(I18n.format(this.director ? "blockbuster.gui.record_editor.directors" : "blockbuster.gui.record_editor.title"), this.area.x + 10, this.area.y + 11, 0xcccccc);
super.draw(context);
}
} | 2,947 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiDropActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiDropActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.DropAction;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiSlotElement;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
public class GuiDropActionPanel extends GuiActionPanel<DropAction>
{
public GuiSlotElement slot;
public GuiDropActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.slot = new GuiSlotElement(mc,0, this::pickItem);
this.slot.flex().relative(this.area).xy(0.5F, 0.5F).anchor(0.5F, 0.5F);
this.add(this.slot);
}
public void pickItem(ItemStack stack)
{
this.action.itemData = stack.isEmpty() ? null : stack.serializeNBT();
this.slot.setStack(stack);
}
@Override
public void fill(DropAction action)
{
super.fill(action);
this.slot.setStack(action.itemData == null ? ItemStack.EMPTY : new ItemStack(action.itemData));
}
} | 1,146 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiBreakBlockAnimationPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiBreakBlockAnimationPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.BreakBlockAnimation;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
public class GuiBreakBlockAnimationPanel extends GuiBlockActionPanel<BreakBlockAnimation>
{
public GuiTrackpadElement charge;
public GuiBreakBlockAnimationPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.charge = new GuiTrackpadElement(mc, (charge) -> this.action.progress = charge.intValue());
this.charge.tooltip(IKey.lang("blockbuster.gui.record_editor.progress"));
this.charge.limit(0, 100, true);
this.charge.flex().set(0, -25, 100, 20).relative(this.x.resizer());
this.add(this.charge);
}
@Override
public void fill(BreakBlockAnimation action)
{
super.fill(action);
this.charge.setValue(action.progress);
}
}
| 1,199 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiDamageActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiDamageActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.DamageAction;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
public class GuiDamageActionPanel extends GuiActionPanel<DamageAction>
{
public GuiTrackpadElement damage;
public GuiDamageActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.damage = new GuiTrackpadElement(mc, (charge) -> this.action.damage = charge.intValue());
this.damage.tooltip(IKey.lang("blockbuster.gui.record_editor.damage"));
this.damage.min = 0;
this.damage.flex().set(10, 0, 100, 20).relative(this.area).y(1, -30);
this.add(this.damage);
}
@Override
public void fill(DamageAction action)
{
super.fill(action);
this.damage.setValue(action.damage);
}
} | 1,098 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiChatActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiChatActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.ChatAction;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.utils.ColorUtils;
import net.minecraft.client.Minecraft;
public class GuiChatActionPanel extends GuiActionPanel<ChatAction>
{
public GuiTextElement command;
public GuiChatActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.command = new GuiTextElement(mc, 10000, (str) -> this.action.message = str);
this.command.flex().relative(this.area).set(10, 0, 0, 20).y(1, -30).w(1, -20);
this.add(this.command);
}
@Override
public void fill(ChatAction action)
{
super.fill(action);
this.command.setText(action.message);
}
@Override
public void draw(GuiContext context)
{
String message = this.action.getMessage(null);
if (!message.isEmpty())
{
GuiDraw.drawTextBackground(this.font, message, this.command.area.x + 3, this.command.area.y - this.font.FONT_HEIGHT - 3, 0xffffff, ColorUtils.HALF_BLACK);
}
super.draw(context);
}
} | 1,469 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiShootArrowActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiShootArrowActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.ShootArrowAction;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
public class GuiShootArrowActionPanel extends GuiActionPanel<ShootArrowAction>
{
public GuiTrackpadElement charge;
public GuiShootArrowActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.charge = new GuiTrackpadElement(mc, (charge) -> this.action.charge = charge.intValue());
this.charge.tooltip(IKey.lang("blockbuster.gui.record_editor.arrow_charge"));
this.charge.limit(0, 100, true);
this.charge.flex().set(10, 0, 100, 20).relative(this.area).y(1, -30);
this.add(this.charge);
}
@Override
public void fill(ShootArrowAction action)
{
super.fill(action);
this.charge.setValue(action.charge);
}
} | 1,136 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiPlaceBlockActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiPlaceBlockActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.PlaceBlockAction;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
public class GuiPlaceBlockActionPanel extends GuiBlockActionPanel<PlaceBlockAction>
{
public GuiTextElement block;
public GuiTrackpadElement meta;
public GuiPlaceBlockActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.block = new GuiTextElement(mc, (str) -> this.action.block = str);
this.meta = new GuiTrackpadElement(mc, (value) -> this.action.metadata = value.byteValue());
this.meta.tooltip(IKey.lang("blockbuster.gui.record_editor.meta"));
this.block.flex().set(0, -30, 100, 20).relative(this.meta.resizer());
this.meta.flex().set(0, -30, 100, 20).relative(this.x.resizer());
this.meta.limit(0, 15, true);
this.add(this.block, this.meta);
}
@Override
public void fill(PlaceBlockAction action)
{
super.fill(action);
this.block.setText(action.block);
this.meta.setValue(action.metadata);
}
} | 1,437 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiItemUseActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiItemUseActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.ItemUseAction;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import net.minecraft.util.EnumHand;
public class GuiItemUseActionPanel<T extends ItemUseAction> extends GuiActionPanel<T>
{
public GuiCirculateElement hand;
public GuiItemUseActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.hand = new GuiCirculateElement(mc, (b) -> this.action.hand = EnumHand.values()[this.hand.getValue()]);
this.hand.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.equip.main_hand"));
this.hand.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.equip.off_hand"));
this.hand.flex().set(10, 0, 80, 20).relative(this.area).y(1, -30);
this.add(this.hand);
}
@Override
public void fill(T action)
{
super.fill(action);
this.hand.setValue(action.hand.ordinal());
}
} | 1,239 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiEquipActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiEquipActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.EquipAction;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiSlotElement;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
import net.minecraft.nbt.NBTTagCompound;
public class GuiEquipActionPanel extends GuiActionPanel<EquipAction>
{
public GuiCirculateElement armor;
public GuiSlotElement slot;
public GuiEquipActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.armor = new GuiCirculateElement(mc, (b) -> this.action.armorSlot = (byte) b.getValue());
this.armor.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.equip.main_hand"));
this.armor.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.equip.feet"));
this.armor.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.equip.legs"));
this.armor.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.equip.chest"));
this.armor.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.equip.head"));
this.armor.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.equip.off_hand"));
this.armor.flex().relative(this).w(80).x(10).y(1F, -30);
this.slot = new GuiSlotElement(mc,0, this::pickItem);
this.slot.flex().relative(this).xy(0.5F, 0.5F).anchor(0.5F, 0.5F);
this.add(this.armor, this.slot);
}
public void pickItem(ItemStack stack)
{
this.action.itemData = stack.isEmpty() ? null : stack.writeToNBT(new NBTTagCompound());
this.slot.setStack(stack);
}
@Override
public void fill(EquipAction action)
{
super.fill(action);
this.armor.setValue(action.armorSlot);
this.slot.setStack(action.itemData == null ? ItemStack.EMPTY : new ItemStack(action.itemData));
}
} | 2,161 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiHotbarChangeActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiHotbarChangeActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.HotbarChangeAction;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiSlotElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import net.minecraft.item.ItemStack;
public class GuiHotbarChangeActionPanel extends GuiActionPanel<HotbarChangeAction>
{
public GuiSlotElement item;
public GuiTrackpadElement slot;
public GuiTrackpadElement durability;
public GuiHotbarChangeActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.slot = new GuiTrackpadElement(mc, (b) -> this.action.setSlot(b.intValue()));
this.slot.integer().limit(0,8);
this.slot.flex().relative(this).xy(0.5F, 0.65F).anchor(0.5F, 0.5F).w(75);
this.slot.tooltip(IKey.lang("blockbuster.gui.record_editor.actions.hotbar_change.slot_tooltip"));
this.durability = new GuiTrackpadElement(mc, (b) ->
{
if (this.item.getStack().getMaxDamage() != 0)
{
ItemStack newItemStack = this.item.getStack().copy();
newItemStack.setItemDamage((int) ((1 - b.floatValue() / 100F) * this.item.getStack().getMaxDamage()));
this.action.setItemStack(newItemStack);
this.item.setStack(newItemStack);
}
});
this.durability.limit(0,100);
this.durability.flex().relative(this).xy(0.5F, 0.75F).anchor(0.5F, 0.5F).w(75);
this.durability.tooltip(IKey.lang("blockbuster.gui.record_editor.actions.hotbar_change.durability_tooltip"));
this.item = new GuiSlotElement(mc,0, this::pickItem);
this.item.flex().relative(this).xy(0.5F, 0.5F).anchor(0.5F, 0.5F);
this.add(this.item, this.slot);
}
public void pickItem(ItemStack stack)
{
this.action.setItemStack(stack);
this.item.setStack(stack);
this.updateFields();
}
protected void updateFields()
{
this.durability.removeFromParent();
if (this.item.getStack().getMaxDamage() != 0)
{
this.add(this.durability);
}
double durability = (this.item.getStack().getMaxDamage() == 0) ? 1 : (1 - (double) this.item.getStack().getItemDamage() / (double) this.item.getStack().getMaxDamage());
this.durability.setValue(durability * 100D);
if (this.parent != null)
{
this.parent.resize();
}
}
@Override
public void fill(HotbarChangeAction action)
{
super.fill(action);
this.slot.setValue(action.getSlot());
this.item.setStack(action.getItemStack() == null ? ItemStack.EMPTY : action.getItemStack().copy());
this.updateFields();
}
}
| 3,024 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiItemUseBlockActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiItemUseBlockActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.model_editor.utils.GuiThreeElement;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.ItemUseBlockAction;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.EnumFacing;
import net.minecraft.util.math.BlockPos;
public class GuiItemUseBlockActionPanel extends GuiItemUseActionPanel<ItemUseBlockAction>
{
public GuiCirculateElement facing;
public GuiThreeElement block;
public GuiThreeElement hit;
public GuiItemUseBlockActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.facing = new GuiCirculateElement(mc, (b) -> this.action.facing = EnumFacing.values()[this.facing.getValue()]);
this.facing.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.use_item_block.down"));
this.facing.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.use_item_block.up"));
this.facing.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.use_item_block.north"));
this.facing.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.use_item_block.south"));
this.facing.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.use_item_block.west"));
this.facing.addLabel(IKey.lang("blockbuster.gui.record_editor.actions.use_item_block.east"));
this.block = new GuiThreeElement(mc, (values) -> this.action.pos = new BlockPos(values[0], values[1], values[2]));
this.block.a.integer = true;
this.block.b.integer = true;
this.block.c.integer = true;
this.hit = new GuiThreeElement(mc, (values) ->
{
this.action.hitX = values[0].floatValue();
this.action.hitY = values[1].floatValue();
this.action.hitZ = values[2].floatValue();
});
this.hit.flex().set(0, -25, 200, 20).relative(this.hand.resizer());
this.block.flex().set(0, -25, 200, 20).relative(this.hit.resizer());
this.facing.flex().set(0, -25, 70, 20).relative(this.block.resizer());
this.add(this.facing, this.block, this.hit);
}
@Override
public void fill(ItemUseBlockAction action)
{
super.fill(action);
this.facing.setValue(action.facing.ordinal());
this.block.setValues(action.pos.getX(), action.pos.getY(), action.pos.getZ());
this.hit.setValues(action.hitX, action.hitY, action.hitZ);
}
} | 2,761 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiMorphActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiMorphActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import java.util.ArrayList;
import java.util.List;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.aperture.CameraHandler;
import mchorse.blockbuster.client.gui.GuiImmersiveEditor;
import mchorse.blockbuster.client.gui.GuiImmersiveMorphMenu;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.common.entity.EntityActor;
import mchorse.blockbuster.network.Dispatcher;
import mchorse.blockbuster.network.common.scene.sync.PacketSceneGoto;
import mchorse.blockbuster.recording.actions.MorphAction;
import mchorse.blockbuster.recording.data.Frame;
import mchorse.blockbuster.recording.data.Record;
import mchorse.blockbuster.recording.data.Record.FoundAction;
import mchorse.blockbuster.recording.scene.Replay;
import mchorse.blockbuster.utils.EntityUtils;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiColorElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.Color;
import mchorse.mclib.utils.DummyEntity;
import mchorse.metamorph.api.MorphAPI;
import mchorse.metamorph.api.MorphUtils;
import mchorse.metamorph.api.morphs.AbstractMorph;
import mchorse.metamorph.client.gui.creative.GuiCreativeMorphsList;
import mchorse.metamorph.client.gui.creative.GuiCreativeMorphsList.OnionSkin;
import mchorse.metamorph.client.gui.creative.GuiNestedEdit;
import net.minecraft.client.Minecraft;
import net.minecraft.entity.EntityLivingBase;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.util.math.Vec3d;
public class GuiMorphActionPanel extends GuiActionPanel<MorphAction>
{
public GuiNestedEdit pickMorph;
public GuiColorElement onionSkin;
public GuiElement onionSkinPanel;
private DummyEntity actor;
private int lastTick;
private OnionSkin skin;
private boolean isImmersiveEditing;
private boolean showRecordList;
private int cursor;
public GuiMorphActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.pickMorph = new GuiNestedEdit(mc, this::doNestEdit);
this.pickMorph.flex().relative(this.area).set(0, 5, 100, 20).x(0.5F, -30);
this.onionSkin = new GuiColorElement(mc, Blockbuster.morphActionOnionSkinColor);
this.onionSkinPanel = Elements.column(mc, 10, 5, Elements.label(IKey.lang("blockbuster.config.onion_skin.title")), this.onionSkin);
this.onionSkinPanel.flex().relative(this.area).x(0F, 10).y(1F, -20).w(150).anchorY(1F);
this.add(this.pickMorph, this.onionSkinPanel);
this.actor = new DummyEntity(this.mc.world);
}
@Override
public void setMorph(AbstractMorph morph)
{
this.action.morph = morph;
this.pickMorph.setMorph(action.morph);
}
@Override
public void fill(MorphAction action)
{
super.fill(action);
ClientProxy.panels.morphs.removeFromParent();
this.pickMorph.setMorph(action.morph);
this.onionSkinPanel.setVisible(CameraHandler.get() != null && CameraHandler.isCameraEditorOpen());
}
@Override
public void disappear()
{
ClientProxy.panels.morphs.finish();
ClientProxy.panels.morphs.removeFromParent();
if (this.isImmersiveEditing)
{
ClientProxy.panels.closeImmersiveEditor();
}
this.action.morph = MorphUtils.copy(this.action.morph);
super.disappear();
}
@Override
public void draw(GuiContext context)
{
if (this.action.morph != null)
{
int x = this.area.mx();
int y = this.area.y(0.8F);
GuiDraw.scissor(this.area.x, this.area.y, this.area.w, this.area.h, context);
this.action.morph.renderOnScreen(this.mc.player, x, y, this.area.h / 3F, 1.0F);
GuiDraw.unscissor(context);
}
super.draw(context);
}
public void doNestEdit(boolean editing)
{
if (CameraHandler.get() != null && CameraHandler.isCameraEditorOpen())
{
this.lastTick = -1;
if (Blockbuster.immersiveRecordEditor.get())
{
this.cursor = Math.max(0, CameraHandler.getOffset());
CameraHandler.detachOutside();
GuiImmersiveEditor editor = ClientProxy.panels.showImmersiveEditor(editing, this.action.morph);
editor.morphs.updateCallback = this::updateMorphEditor;
editor.morphs.frameProvider = this::getFrame;
editor.onClose = this::onImmersiveEditorClose;
this.panel.records.removeFromParent();
this.panel.records.flex().relative(editor.outerPanel);
this.panel.timeline.removeFromParent();
this.panel.timeline.flex().relative(editor.outerPanel);
editor.outerPanel.add(this.panel.records, this.panel.timeline);
this.addOnionSkin(editor.morphs);
this.isImmersiveEditing = true;
this.showRecordList = this.panel.records.isVisible();
this.panel.records.setVisible(true);
}
else
{
ClientProxy.panels.addMorphs(this, editing, this.action.morph);
this.addOnionSkin(ClientProxy.panels.morphs);
}
}
else
{
ClientProxy.panels.addMorphs(this, editing, this.action.morph);
}
}
public void updateMorphEditor(GuiImmersiveMorphMenu menu)
{
Record record = ClientProxy.manager.records.get(this.panel.record.filename);
int tick = this.panel.timeline.getCurrentTick();
if (menu.isNested())
{
tick = this.lastTick;
}
else
{
tick += menu.editor.delegate.getCurrentTick();
}
if (tick != this.lastTick)
{
Dispatcher.sendToServer(new PacketSceneGoto(CameraHandler.get(), tick, CameraHandler.actions.get()));
if (record != null && record.getFrameSafe(0) != null)
{
record.applyFrame(Math.max(tick - 1, 0), this.actor, true, true);
Frame frame = record.getFrameSafe(tick - 1);
if (frame.hasBodyYaw)
{
this.actor.renderYawOffset = frame.bodyYaw;
}
}
else
{
menu.target = null;
}
this.lastTick = tick;
}
boolean refreshTarget = true;
if (menu.target != null && menu.target != this.actor && this.mc.world.getLoadedEntityList().contains(menu.target))
{
refreshTarget = false;
}
if (refreshTarget)
{
EntityLivingBase entity = null;
for (EntityLivingBase actor : Minecraft.getMinecraft().world.getEntities(EntityLivingBase.class, actor ->
{
return actor.isEntityAlive() && EntityUtils.getRecordPlayer(actor) != null && EntityUtils.getRecordPlayer(actor).record != null && this.panel.record.filename.equals(EntityUtils.getRecordPlayer(actor).record.filename);
}))
{
entity = actor;
break;
}
if (entity == null)
{
entity = this.actor;
}
menu.target = entity;
}
if (menu.target instanceof EntityActor)
{
((EntityActor) menu.target).morph.setDirect(null);
}
else if (menu.target instanceof EntityPlayer)
{
MorphAPI.morph((EntityPlayer) menu.target, null, true);
}
if (record != null && !record.frames.isEmpty() && this.skin != null && menu.target != null)
{
Frame last = record.getFrameSafe(this.panel.timeline.getCurrentTick() - 1);
EntityLivingBase actor = menu.target;
float yaw = actor.rotationYaw;
Vec3d pos = new Vec3d(last.x - actor.posX, last.y - actor.posY, last.z - actor.posZ);
pos = pos.rotateYaw((float) Math.toRadians(yaw));
this.skin.offset(pos.x, pos.y, pos.z, last.pitch, last.yawHead - yaw, last.bodyYaw - yaw);
}
}
public Frame getFrame(int tick)
{
Record record = ClientProxy.manager.records.get(this.panel.record.filename);
if (record != null)
{
return record.getFrameSafe(this.panel.timeline.getCurrentTick() + tick - 1);
}
else
{
return null;
}
}
public void addOnionSkin(GuiCreativeMorphsList morphs)
{
if (this.onionSkin.picker.color.a < 0.003921F)
{
return;
}
List<OnionSkin> skins = new ArrayList<OnionSkin>();
Record record = this.panel.record;
Color color = this.onionSkin.picker.color;
if (record != null)
{
FoundAction found = record.seekMorphAction(this.panel.timeline.getCurrentTick(), this.action);
AbstractMorph morph = null;
int tick = 0;
if (found != null)
{
morph = found.action.morph;
tick = found.tick;
}
else
{
for (Replay replay : ClientProxy.panels.scenePanel.getReplays())
{
if (replay.id.equals(this.panel.record.filename))
{
morph = replay.morph;
break;
}
}
}
if (morph != null)
{
MorphUtils.pause(morph, null, Math.max(0, this.panel.timeline.getCurrentTick() - tick));
this.skin = new OnionSkin().color(color.r, color.g, color.b, color.a).morph(morph);
skins.add(this.skin);
}
}
morphs.lastOnionSkins = skins;
}
public void onImmersiveEditorClose(GuiImmersiveEditor editor)
{
this.isImmersiveEditing = false;
this.panel.records.setVisible(this.showRecordList);
CameraHandler.updatePlayerPosition();
CameraHandler.attachOutside();
CameraHandler.moveRecordPanel(this.panel);
Dispatcher.sendToServer(new PacketSceneGoto(CameraHandler.get(), this.cursor, CameraHandler.actions.get()));
}
}
| 10,785 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiBreakBlockActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiBreakBlockActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.BreakBlockAction;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
public class GuiBreakBlockActionPanel extends GuiBlockActionPanel<BreakBlockAction>
{
public GuiToggleElement drop;
public GuiBreakBlockActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.drop = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.record_editor.drop"), false, (b) -> this.action.drop = b.isToggled());
this.drop.flex().set(0, -16, 70, 11).relative(this.x.resizer());
this.add(this.drop);
}
@Override
public void fill(BreakBlockAction action)
{
super.fill(action);
this.drop.toggled(action.drop);
}
} | 1,039 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiEmptyActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiEmptyActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.Action;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
public class GuiEmptyActionPanel extends GuiActionPanel<Action>
{
public GuiEmptyActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
}
@Override
public void draw(GuiContext context)
{
super.draw(context);
this.drawCenteredString(this.font, I18n.format("blockbuster.gui.record_editor.no_fields"), this.area.mx(), this.area.my(), 0xffffff);
}
} | 807 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiBlockActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiBlockActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.InteractBlockAction;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import net.minecraft.client.resources.I18n;
import net.minecraft.util.math.BlockPos;
public class GuiBlockActionPanel<T extends InteractBlockAction> extends GuiActionPanel<T>
{
public GuiTrackpadElement x;
public GuiTrackpadElement y;
public GuiTrackpadElement z;
public GuiBlockActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.x = new GuiTrackpadElement(mc, (v) -> this.action.pos = new BlockPos(v.intValue(), this.action.pos.getY(), this.action.pos.getZ()));
this.x.tooltip(IKey.lang("blockbuster.gui.model_block.x"));
this.y = new GuiTrackpadElement(mc, (v) -> this.action.pos = new BlockPos(this.action.pos.getX(), v.intValue(), this.action.pos.getZ()));
this.y.tooltip(IKey.lang("blockbuster.gui.model_block.y"));
this.z = new GuiTrackpadElement(mc, (v) -> this.action.pos = new BlockPos(this.action.pos.getX(), this.action.pos.getY(), v.intValue()));
this.z.tooltip(IKey.lang("blockbuster.gui.model_block.z"));
this.x.integer = this.y.integer = this.z.integer = true;
this.x.flex().set(10, 0, 80, 20).relative(this.area).y(1, -80);
this.y.flex().set(0, 25, 80, 20).relative(this.x.resizer());
this.z.flex().set(0, 25, 80, 20).relative(this.y.resizer());
this.add(this.x, this.y, this.z);
}
@Override
public void fill(T action)
{
super.fill(action);
this.x.setValue(action.pos.getX());
this.y.setValue(action.pos.getY());
this.z.setValue(action.pos.getZ());
}
}
| 1,987 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.Action;
import mchorse.blockbuster.recording.actions.ActionRegistry;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDraw;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.metamorph.api.morphs.AbstractMorph;
import net.minecraft.client.Minecraft;
import net.minecraft.nbt.NBTTagCompound;
import java.util.Map.Entry;
public abstract class GuiActionPanel<T extends Action> extends GuiElement
{
public T action;
public GuiRecordingEditorPanel panel;
private IKey title = IKey.lang("");
private IKey description = IKey.lang("");
public GuiActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc);
this.panel = panel;
this.hideTooltip();
}
public void fill(T action)
{
this.action = action;
String key = ActionRegistry.NAME_TO_CLASS.inverse().get(action.getClass());
if (key != null)
{
this.setKey(key);
}
}
public void disappear()
{}
public void setMorph(AbstractMorph morph)
{}
public void setKey(String key)
{
this.title.set("blockbuster.gui.record_editor.actions." + key + ".title");
this.description.set("blockbuster.gui.record_editor.actions." + key + ".desc");
}
@Override
public void draw(GuiContext context)
{
String title = this.title.get();
if (!title.isEmpty())
{
this.font.drawStringWithShadow(title, this.area.x + 10, this.area.y + 10, 0xffffff);
GuiDraw.drawMultiText(this.font, this.description.get(), this.area.x + 10, this.area.y + 30, 0xcccccc, this.area.w / 3);
}
super.draw(context);
}
} | 2,251 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiMountingActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiMountingActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.MountingAction;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
public class GuiMountingActionPanel extends GuiActionPanel<MountingAction>
{
public GuiToggleElement mounting;
public GuiMountingActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.mounting = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.record_editor.mounting"), false, (b) -> this.action.isMounting = b.isToggled());
this.mounting.flex().set(10, 0, 60, 11).relative(this.area).y(1, -21);
this.add(this.mounting);
}
@Override
public void fill(MountingAction action)
{
super.fill(action);
this.mounting.toggled(action.isMounting);
}
}
| 1,063 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiInteractEntityActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiInteractEntityActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import net.minecraft.client.Minecraft;
public class GuiInteractEntityActionPanel extends GuiItemUseActionPanel
{
public GuiInteractEntityActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
}
} | 418 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiCommandActionPanel.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/recording_editor/actions/GuiCommandActionPanel.java | package mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.actions;
import mchorse.blockbuster.client.gui.dashboard.panels.recording_editor.GuiRecordingEditorPanel;
import mchorse.blockbuster.recording.actions.CommandAction;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import net.minecraft.client.Minecraft;
public class GuiCommandActionPanel extends GuiActionPanel<CommandAction>
{
public GuiTextElement command;
public GuiCommandActionPanel(Minecraft mc, GuiRecordingEditorPanel panel)
{
super(mc, panel);
this.command = new GuiTextElement(mc, 10000, (str) -> this.action.command = str);
this.command.flex().relative(this.area).set(10, 0, 0, 20).y(1, -30).w(1, -20);
this.add(this.command);
}
@Override
public void fill(CommandAction action)
{
super.fill(action);
this.command.setText(action.command);
}
} | 937 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstorm.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/GuiSnowstorm.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm;
import mchorse.blockbuster.Blockbuster;
import mchorse.blockbuster.ClientProxy;
import mchorse.blockbuster.client.gui.dashboard.GuiBlockbusterPanel;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormAppearanceSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormCollisionAppearanceSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormCollisionLightingSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormCollisionSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormExpirationSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormGeneralSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormInitializationSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormLifetimeSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormLightingSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormMotionSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormParticleMorphSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormRateSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormShapeSection;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections.GuiSnowstormSpaceSection;
import mchorse.blockbuster.client.particles.BedrockLibrary;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.mclib.client.gui.framework.GuiBase;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.GuiScrollElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.list.GuiStringSearchListElement;
import mchorse.mclib.client.gui.framework.elements.modals.GuiConfirmModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiModal;
import mchorse.mclib.client.gui.framework.elements.modals.GuiPromptModal;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.framework.elements.utils.GuiDrawable;
import mchorse.mclib.client.gui.framework.elements.utils.GuiLabel;
import mchorse.mclib.client.gui.mclib.GuiDashboard;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.GuiUtils;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.utils.ColorUtils;
import mchorse.mclib.utils.MathUtils;
import net.minecraft.client.Minecraft;
import org.lwjgl.input.Keyboard;
import java.util.ArrayList;
import java.util.List;
public class GuiSnowstorm extends GuiBlockbusterPanel
{
public static final String DEFAULT_PARTICLE = "default_snow";
public GuiSnowstormRenderer renderer;
public GuiScrollElement editor;
public GuiIconElement open;
public GuiIconElement save;
public GuiElement modal;
public GuiIconElement add;
public GuiIconElement dupe;
public GuiIconElement remove;
public GuiIconElement folder;
public GuiStringSearchListElement particles;
public List<GuiSnowstormSection> sections = new ArrayList<GuiSnowstormSection>();
private GuiSnowstormParticleMorphSection particleMorphSection;
private BedrockLibrary library;
private String filename;
private BedrockScheme scheme;
private boolean dirty;
public GuiSnowstorm(Minecraft mc, GuiDashboard dashboard)
{
super(mc, dashboard);
/* TODO: Add link to snowstorm web editor */
this.library = Blockbuster.proxy.particles;
this.renderer = new GuiSnowstormRenderer(mc);
this.renderer.flex().relative(this).wh(1F, 1F);
this.editor = new GuiScrollElement(mc);
this.editor.flex().relative(this).x(1F).w(200).h(1F).anchorX(1F).column(20).vertical().stretch().scroll().padding(10);
this.open = new GuiIconElement(mc, Icons.MORE, (b) -> this.modal.toggleVisible());
this.open.tooltip(IKey.lang("blockbuster.gui.snowstorm.open_tooltip"));
this.open.flex().relative(this);
this.save = new GuiIconElement(mc, Icons.SAVE, (b) -> this.save());
this.save.tooltip(IKey.lang("blockbuster.gui.snowstorm.save_tooltip"));
this.save.flex().relative(this.open).x(20);
/* Modal */
this.modal = new GuiElement(mc);
this.modal.flex().relative(this).y(20).w(160).hTo(this.area, 1F, -16);
GuiLabel label = Elements.label(IKey.lang("blockbuster.gui.snowstorm.title"), 20)
.anchor(0, 0.5F);
label.flex().relative(this.modal).xy(10, 10).w(1F, -20);
this.add = new GuiIconElement(mc, Icons.ADD, (b) -> this.addEffect());
this.add.tooltip(IKey.lang("blockbuster.gui.snowstorm.add_tooltip"));
this.dupe = new GuiIconElement(mc, Icons.DUPE, (b) -> this.dupeEffect());
this.dupe.tooltip(IKey.lang("blockbuster.gui.snowstorm.dupe_tooltip"));
this.remove = new GuiIconElement(mc, Icons.REMOVE, (b) -> this.removeEffect());
this.folder = new GuiIconElement(mc, Icons.FOLDER, (b) -> GuiUtils.openFolder(this.library.folder.getAbsolutePath()));
this.folder.tooltip(IKey.lang("blockbuster.gui.snowstorm.folder_tooltip"));
this.particles = new GuiStringSearchListElement(mc, (list) -> this.setScheme(list.get(0)));
this.particles.flex().relative(this.modal).xy(10, 35).w(1F, -20).h(1F, -45);
this.particleMorphSection = new GuiSnowstormParticleMorphSection(mc, this);
GuiElement icons = new GuiElement(mc);
icons.flex().relative(this.modal).x(1F, -10).y(10).h(20).anchorX(1F).row(0).resize().width(20).height(20);
icons.add(this.add, this.dupe, this.remove, this.folder);
this.modal.add(label, icons, this.particles);
this.modal.setVisible(false);
this.add(this.renderer, new GuiDrawable(this::drawOverlay), this.editor, this.modal, this.open, this.save);
this.addSection(new GuiSnowstormGeneralSection(mc, this));
//this.addSection(this.particleMorphSection);
this.addSection(new GuiSnowstormSpaceSection(mc, this));
this.addSection(new GuiSnowstormInitializationSection(mc, this));
this.addSection(new GuiSnowstormRateSection(mc, this));
this.addSection(new GuiSnowstormLifetimeSection(mc, this));
this.addSection(new GuiSnowstormShapeSection(mc, this));
this.addSection(new GuiSnowstormMotionSection(mc, this));
this.addSection(new GuiSnowstormExpirationSection(mc, this));
this.addSection(new GuiSnowstormAppearanceSection(mc, this));
this.addSection(new GuiSnowstormLightingSection(mc, this));
this.addSection(new GuiSnowstormCollisionSection(mc, this));
this.addSection(new GuiSnowstormCollisionAppearanceSection(mc, this));
this.addSection(new GuiSnowstormCollisionLightingSection(mc, this));
this.keys()
.register(IKey.lang("blockbuster.gui.snowstorm.keys.save"), Keyboard.KEY_S, () -> this.save.clickItself(GuiBase.getCurrent()))
.held(Keyboard.KEY_LCONTROL).category(IKey.lang("blockbuster.gui.snowstorm.keys.category"));
}
private void addEffect()
{
GuiModal.addFullModal(this.modal, () -> new GuiPromptModal(this.mc, IKey.lang("blockbuster.gui.snowstorm.add_modal"), (name) ->
{
if (this.library.hasEffect(name) || name.isEmpty())
{
return;
}
BedrockScheme scheme = this.library.load(DEFAULT_PARTICLE);
scheme.identifier = name;
this.setScheme(name, scheme);
this.dirty();
this.particles.list.setCurrent("");
}));
}
private void dupeEffect()
{
GuiModal.addFullModal(this.modal, () -> new GuiPromptModal(this.mc, IKey.lang("blockbuster.gui.snowstorm.dupe_modal"), (name) ->
{
if (this.library.hasEffect(name) || name.isEmpty())
{
return;
}
if (!this.scheme.isFactory())
{
this.particles.list.setCurrent("");
}
BedrockScheme scheme = BedrockScheme.dupe(this.scheme);
scheme.factory(this.library.factory.containsKey(name));
scheme.identifier = name;
this.setScheme(name, scheme);
this.save();
}).setValue(this.filename));
}
private void removeEffect()
{
if (this.scheme.isFactory())
{
return;
}
GuiModal.addFullModal(this.modal, () -> new GuiConfirmModal(this.mc, IKey.lang("blockbuster.gui.snowstorm.remove_modal"), (confirm) ->
{
if (!confirm || !this.library.hasEffect(this.filename))
{
return;
}
int index = this.particles.list.getIndex();
if (this.library.file(this.filename).delete())
{
if (!this.library.factory.containsKey(this.filename))
{
this.particles.list.remove(this.filename);
}
index = MathUtils.clamp(index, 0, this.particles.list.getList().size() - 1);
this.particles.list.setIndex(index);
this.setScheme(this.particles.list.getCurrentFirst());
}
}));
}
public void dirty()
{
this.dirty = true;
this.updateSaveButton();
this.renderer.emitter.setupVariables();
}
private void updateSaveButton()
{
this.save.both(this.dirty ? Icons.SAVE : Icons.SAVED);
}
private void updateRemoveButton()
{
this.remove.setEnabled(!this.scheme.isFactory());
if (this.remove.isEnabled())
{
this.remove.tooltip(IKey.lang("blockbuster.gui.snowstorm.remove_tooltip"));
}
else
{
this.remove.tooltip(IKey.lang("blockbuster.gui.snowstorm.remove_factory_tooltip"));
}
}
private void save()
{
for (GuiSnowstormSection section : this.sections)
{
section.beforeSave(this.scheme);
}
this.library.save(this.filename, this.scheme);
if (!this.particles.list.getList().contains(this.filename))
{
this.particles.list.add(this.filename);
this.particles.list.sort();
this.particles.list.setCurrent(this.filename);
}
this.dirty = false;
this.scheme.factory(false);
this.updateSaveButton();
this.updateRemoveButton();
}
private void addSection(GuiSnowstormSection section)
{
this.sections.add(section);
this.editor.add(section);
}
private void setScheme(String scheme)
{
this.setScheme(scheme, this.library.load(scheme));
}
private void setScheme(String name, BedrockScheme scheme)
{
if (scheme == null)
{
this.particles.list.remove(name);
this.particles.list.setIndex(-1);
return;
}
this.filename = name;
this.scheme = scheme;
this.renderer.setScheme(this.scheme);
this.dirty = false;
this.updateSaveButton();
this.updateRemoveButton();
for (GuiSnowstormSection section : this.sections)
{
section.setScheme(this.scheme);
}
this.editor.resize();
}
@Override
public void appear()
{
super.appear();
String current = this.particles.list.getCurrentFirst();
this.particles.filter("", true);
this.particles.list.clear();
this.particles.list.add(this.library.presets.keySet());
this.particles.list.sort();
if (this.scheme == null)
{
this.setScheme(DEFAULT_PARTICLE);
this.particles.list.setCurrent(DEFAULT_PARTICLE);
}
else
{
this.particles.list.setCurrent(current);
}
ClientProxy.panels.picker(this.particleMorphSection::setMorph);
}
@Override
public void close()
{
if (this.renderer.emitter != null)
{
this.renderer.emitter.particles.clear();
}
}
private void drawOverlay(GuiContext context)
{
/* Draw debug info */
BedrockEmitter emitter = this.renderer.emitter;
String label = emitter.particles.size() + "P - " + emitter.age + "A";
this.font.drawStringWithShadow(label, this.area.x + 4, this.area.ey() - 12, 0xffffff);
if (this.modal.isVisible())
{
this.open.area.draw(ColorUtils.HALF_BLACK);
this.modal.area.draw(ColorUtils.HALF_BLACK);
}
}
} | 13,313 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormRenderer.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/GuiSnowstormRenderer.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm;
import mchorse.blockbuster.api.formats.obj.Vector3f;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.expiration.BedrockComponentKillPlane;
import mchorse.blockbuster.client.particles.emitter.BedrockEmitter;
import mchorse.mclib.client.Draw;
import mchorse.mclib.client.gui.framework.elements.GuiModelRenderer;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import net.minecraft.client.Minecraft;
import net.minecraft.client.renderer.BufferBuilder;
import net.minecraft.client.renderer.GlStateManager;
import net.minecraft.client.renderer.Tessellator;
import net.minecraft.client.renderer.vertex.DefaultVertexFormats;
import org.lwjgl.opengl.GL11;
public class GuiSnowstormRenderer extends GuiModelRenderer
{
public BedrockEmitter emitter;
public boolean playing = true;
private Vector3f vector = new Vector3f(0, 0, 0);
public GuiSnowstormRenderer(Minecraft mc)
{
super(mc);
this.emitter = new BedrockEmitter();
}
public void setScheme(BedrockScheme scheme)
{
this.emitter = new BedrockEmitter();
this.emitter.setScheme(scheme);
this.playing = true;
}
@Override
protected void update()
{
super.update();
if (this.playing && this.emitter != null)
{
this.emitter.rotation.setIdentity();
this.emitter.update();
}
}
@Override
protected void drawUserModel(GuiContext context)
{
if (this.emitter == null || this.emitter.scheme == null)
{
return;
}
this.emitter.cYaw = this.yaw;
this.emitter.cPitch = this.pitch;
this.emitter.cX = this.temp.x;
this.emitter.cY = this.temp.y;
this.emitter.cZ = this.temp.z;
this.emitter.perspective = 100;
this.emitter.rotation.setIdentity();
GlStateManager.disableLighting();
GlStateManager.disableDepth();
GlStateManager.glLineWidth(3);
GlStateManager.disableTexture2D();
Draw.axis(1F);
GlStateManager.enableTexture2D();
GlStateManager.glLineWidth(1);
GlStateManager.enableDepth();
this.emitter.render(this.playing ? context.partialTicks : 1);
BedrockComponentKillPlane plane = this.emitter.scheme.get(BedrockComponentKillPlane.class);
if (plane.a != 0 || plane.b != 0 || plane.c != 0)
{
this.drawKillPlane(plane.a, plane.b, plane.c, plane.d);
}
GlStateManager.enableLighting();
}
private void drawKillPlane(float a, float b, float c, float d)
{
Tessellator tessellator = Tessellator.getInstance();
BufferBuilder buffer = tessellator.getBuffer();
// GL11.glLineWidth(2F);
GL11.glPointSize(4F);
GlStateManager.disableTexture2D();
GlStateManager.enableAlpha();
GlStateManager.enableBlend();
GlStateManager.color(1F, 1F, 1F);
buffer.begin(GL11.GL_QUADS, DefaultVertexFormats.POSITION_COLOR);
this.calculate(0, 0, a, b, c, d);
buffer.pos(this.vector.x, this.vector.y, this.vector.z).color(0, 1, 0, 0.5F).endVertex();
this.calculate(1, 0, a, b, c, d);
buffer.pos(this.vector.x, this.vector.y, this.vector.z).color(0, 1, 0, 0.5F).endVertex();
this.calculate(1, 1, a, b, c, d);
buffer.pos(this.vector.x, this.vector.y, this.vector.z).color(0, 1, 0, 0.5F).endVertex();
this.calculate(0, 1, a, b, c, d);
buffer.pos(this.vector.x, this.vector.y, this.vector.z).color(0, 1, 0, 0.5F).endVertex();
tessellator.draw();
GlStateManager.enableTexture2D();
}
private void calculate(float i, float j, float a, float b, float c, float d)
{
final float radius = 5;
if (b != 0)
{
this.vector.x = -radius + radius * 2 * i;
this.vector.z = -radius + radius * 2 * j;
this.vector.y = (a * this.vector.x + c * this.vector.z + d) / -b;
}
else if (a != 0)
{
this.vector.y = -radius + radius * 2 * i;
this.vector.z = -radius + radius * 2 * j;
this.vector.x = (b * this.vector.y + c * this.vector.z + d) / -a;
}
else if (c != 0)
{
this.vector.x = -radius + radius * 2 * i;
this.vector.y = -radius + radius * 2 * j;
this.vector.z = (b * this.vector.y + a * this.vector.x + d) / -c;
}
}
} | 4,605 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSectionManager.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/GuiSectionManager.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm;
import java.util.HashMap;
import java.util.Map;
public class GuiSectionManager
{
private static final Map<String, Boolean> STATES = new HashMap<String, Boolean>();
public static boolean isCollapsed(String id)
{
Boolean state = STATES.get(id);
if (state == null)
{
state = true; // default value
STATES.put(id, state);
}
return state;
}
public static void setCollapsed(String id, boolean collapsed)
{
STATES.put(id, collapsed);
}
/**
* This method only adds a state to the Map if the id isn't present
* @param id
* @param collapsed
*/
public static void setDefaultState(String id, boolean collapsed)
{
if (!STATES.containsKey(id))
{
STATES.put(id, collapsed);
}
}
}
| 931 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormLightingSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormLightingSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.utils.GuiGradientEditor;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentAppearanceLighting;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentAppearanceTinting;
import mchorse.blockbuster.client.particles.components.appearance.Tint;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiColorElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiLabel;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.math.Constant;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.math.molang.expressions.MolangValue;
import mchorse.mclib.utils.Color;
import net.minecraft.client.Minecraft;
public class GuiSnowstormLightingSection extends GuiSnowstormSection
{
public GuiCirculateElement mode;
public GuiColorElement color;
public GuiTextElement r;
public GuiTextElement g;
public GuiTextElement b;
public GuiTextElement a;
public GuiTextElement interpolant;
public GuiTrackpadElement range;
public GuiToggleElement lighting;
public GuiGradientEditor gradientEditor;
public GuiColorElement gradientColor;
public GuiElement gradientElements;
public GuiElement first;
public GuiElement second;
/** Solid, Expression, Gradient */
protected final Tint[] tints = new Tint[3];
protected BedrockComponentAppearanceTinting component;
public GuiSnowstormLightingSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.mode = new GuiCirculateElement(mc, (b) ->
{
this.component.color = this.tints[b.getValue()];
this.updateElements();
this.parent.dirty();
});
this.mode.addLabel(IKey.lang("blockbuster.gui.snowstorm.lighting.solid"));
this.mode.addLabel(IKey.lang("blockbuster.gui.snowstorm.lighting.expression"));
this.mode.addLabel(IKey.lang("blockbuster.gui.snowstorm.lighting.gradient"));
this.color = new GuiColorElement(mc, (color) ->
{
Tint.Solid solid = this.getSolid();
Color original = this.color.picker.color;
solid.r = this.set(solid.r, original.r);
solid.g = this.set(solid.g, original.g);
solid.b = this.set(solid.b, original.b);
solid.a = this.set(solid.a, original.a);
this.parent.dirty();
});
this.color.picker.editAlpha();
this.r = new GuiTextElement(mc, 10000, (str) ->
{
Tint.Solid solid = this.getSolid();
solid.r = this.parse(str, this.r, solid.r);
});
this.r.tooltip(IKey.lang("blockbuster.gui.snowstorm.lighting.red"));
this.g = new GuiTextElement(mc, 10000, (str) ->
{
Tint.Solid solid = this.getSolid();
solid.g = this.parse(str, this.r, solid.g);
});
this.g.tooltip(IKey.lang("blockbuster.gui.snowstorm.lighting.green"));
this.b = new GuiTextElement(mc, 10000, (str) ->
{
Tint.Solid solid = this.getSolid();
solid.b = this.parse(str, this.r, solid.b);
});
this.b.tooltip(IKey.lang("blockbuster.gui.snowstorm.lighting.blue"));
this.a = new GuiTextElement(mc, 10000, (str) ->
{
Tint.Solid solid = this.getSolid();
solid.a = this.parse(str, this.r, solid.a);
});
this.a.tooltip(IKey.lang("blockbuster.gui.snowstorm.lighting.alpha"));
this.lighting = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.lighting.lighting"), (b) -> this.parent.dirty());
this.lighting.tooltip(IKey.lang("blockbuster.gui.snowstorm.lighting.lighting_tooltip"));
GuiLabel label = Elements.label(IKey.lang("blockbuster.gui.snowstorm.mode"), 20).anchor(0, 0.5F);
this.interpolant = new GuiTextElement(mc, 10000, (str) ->
{
Tint.Gradient gradient = this.getGradient();
gradient.interpolant = this.parse(str, this.interpolant, gradient.interpolant);
this.parent.dirty();
});
this.interpolant.tooltip(IKey.lang("blockbuster.gui.snowstorm.lighting.interpolant_tooltip"));
this.range = new GuiTrackpadElement(mc, (value) ->
{
double threshold = 0.0000000001;
Tint.Gradient gradient = this.getGradient();
gradient.range = (value.floatValue() >= -threshold && value.floatValue() <= threshold) ? 1 : value.floatValue();
this.parent.dirty();
});
this.range.tooltip(IKey.lang("blockbuster.gui.snowstorm.lighting.range_tooltip"));
this.gradientColor = new GuiColorElement(mc, this::setGradientColor);
this.gradientColor.picker.editAlpha();
this.gradientEditor = new GuiGradientEditor(mc, this, this.gradientColor);
this.gradientElements = new GuiElement(mc);
this.gradientElements.flex().column(4).stretch().vertical().height(4);
this.gradientElements.add(this.gradientEditor, this.gradientColor, this.interpolant, this.range);
this.first = Elements.row(mc, 5, 0, 20, this.r, this.g);
this.second = Elements.row(mc, 5, 0, 20, this.b, this.a);
this.fields.add(this.lighting);
this.fields.add(Elements.row(mc, 5, 0, 20, label, this.mode));
}
protected void setGradientColor(int color)
{
this.gradientEditor.setColor(color);
}
protected MolangExpression set(MolangExpression expression, float value)
{
if (expression == MolangParser.ZERO || expression == MolangParser.ONE)
{
return new MolangValue(null, new Constant(value));
}
if (!(expression instanceof MolangValue))
{
expression = new MolangValue(null, new Constant(0));
}
if (expression instanceof MolangValue)
{
MolangValue v = (MolangValue) expression;
if (!(v.value instanceof Constant))
{
v.value = new Constant(0);
}
if (v.value instanceof Constant)
{
((Constant) v.value).set(value);
}
}
return expression;
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.lighting.title";
}
protected Tint.Solid getSolid()
{
return (Tint.Solid) this.component.color;
}
protected Tint.Gradient getGradient()
{
return (Tint.Gradient) this.component.color;
}
@Override
public void beforeSave(BedrockScheme scheme)
{
if (this.lighting.isToggled())
{
scheme.getOrCreate(BedrockComponentAppearanceLighting.class);
}
else
{
scheme.remove(BedrockComponentAppearanceLighting.class);
}
}
@Override
public void setScheme(BedrockScheme scheme)
{
super.setScheme(scheme);
this.component = scheme.getOrCreateExact(BedrockComponentAppearanceTinting.class);
this.lighting.toggled(scheme.get(BedrockComponentAppearanceLighting.class) != null);
this.setTintsCache();
this.fillData();
}
protected void setTintsCache()
{
this.tints[0] = new Tint.Solid();
this.tints[1] = new Tint.Solid();
this.tints[2] = new Tint.Gradient();
}
protected void fillData()
{
if (this.component.color instanceof Tint.Solid)
{
Tint.Solid solid = this.getSolid();
if (solid.isConstant())
{
this.tints[0] = solid;
this.color.picker.color.set((float) solid.r.get(), (float) solid.g.get(), (float) solid.b.get(), (float) solid.a.get());
this.mode.setValue(0);
}
else
{
this.tints[1] = solid;
this.set(this.r, solid.r);
this.set(this.g, solid.g);
this.set(this.b, solid.b);
this.set(this.a, solid.a);
this.mode.setValue(1);
}
}
else if (this.component.color instanceof Tint.Gradient)
{
Tint.Gradient gradient = this.getGradient();
this.tints[2] = gradient;
this.set(this.interpolant, gradient.interpolant);
this.range.setValue(gradient.range);
this.gradientEditor.setGradient(gradient);
this.mode.setValue(2);
}
this.updateElements();
}
public void updateElements()
{
this.gradientElements.removeFromParent();
this.color.removeFromParent();
this.color.picker.removeFromParent();
this.first.removeFromParent();
this.second.removeFromParent();
if (this.mode.getValue() == 0)
{
Tint.Solid solid = this.getSolid();
this.color.picker.color.set((float) solid.r.get(), (float) solid.g.get(), (float) solid.b.get(), (float) solid.a.get());
this.fields.add(this.color);
}
else if (this.mode.getValue() == 1)
{
Tint.Solid solid = this.getSolid();
this.set(this.r, solid.r);
this.set(this.g, solid.g);
this.set(this.b, solid.b);
this.set(this.a, solid.a);
this.fields.add(this.first);
this.fields.add(this.second);
}
else if (this.mode.getValue() == 2)
{
Tint.Gradient gradient = this.getGradient();
this.set(this.interpolant, gradient.interpolant);
this.range.setValue(gradient.range);
this.gradientEditor.setGradient(gradient);
this.fields.add(this.gradientElements);
}
this.resizeParent();
}
} | 10,579 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormComponentSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormComponentSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.BedrockComponentBase;
import net.minecraft.client.Minecraft;
public abstract class GuiSnowstormComponentSection <T extends BedrockComponentBase> extends GuiSnowstormSection
{
protected T component;
public GuiSnowstormComponentSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
}
@Override
public void setScheme(BedrockScheme scheme)
{
super.setScheme(scheme);
this.component = this.getComponent(scheme);
this.fillData();
}
protected abstract T getComponent(BedrockScheme scheme);
protected void fillData()
{}
} | 875 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormSpaceSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormSpaceSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.meta.BedrockComponentLocalSpace;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.math.Operation;
import net.minecraft.client.Minecraft;
public class GuiSnowstormSpaceSection extends GuiSnowstormComponentSection<BedrockComponentLocalSpace>
{
public GuiToggleElement position;
public GuiToggleElement rotation;
public GuiToggleElement scale;
public GuiToggleElement scaleBillboard;
public GuiElement scaleColumns;
public GuiToggleElement direction; //local direction for physical accurate systems
public GuiToggleElement acceleration;
public GuiToggleElement gravity;
public GuiTrackpadElement linearVelocity;
public GuiTrackpadElement angularVelocity;
public GuiElement objectVelocity;
public GuiSnowstormSpaceSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.position = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.space.position"), (b) ->
{
this.component.position = b.isToggled();
this.parent.dirty();
});
this.position.tooltip(IKey.lang("blockbuster.gui.snowstorm.space.position_tooltip"));
this.rotation = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.space.rotation"), (b) ->
{
this.component.rotation = b.isToggled();
this.parent.dirty();
});
this.rotation.tooltip(IKey.lang("blockbuster.gui.snowstorm.space.rotation_tooltip"));
this.scale = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.space.scale"), (b) ->
{
this.component.scale = b.isToggled();
this.parent.dirty();
updateButtons();
});
this.scale.tooltip(IKey.lang("blockbuster.gui.snowstorm.space.scale_tooltip"));
this.scaleBillboard = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.space.scale_billboard"), (b) ->
{
this.component.scaleBillboard = b.isToggled();
this.parent.dirty();
});
this.scaleBillboard.tooltip(IKey.lang("blockbuster.gui.snowstorm.space.scale_billboard_tooltip"));
this.direction = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.space.direction"), (b) ->
{
this.component.direction = b.isToggled();
this.parent.dirty();
});
this.direction.tooltip(IKey.lang("blockbuster.gui.snowstorm.space.direction_tooltip"));
this.acceleration = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.space.acceleration"), (b) ->
{
this.component.acceleration = b.isToggled();
this.parent.dirty();
});
this.acceleration.tooltip(IKey.lang("blockbuster.gui.snowstorm.space.acceleration_tooltip"));
this.gravity = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.space.gravity"), (b) ->
{
this.component.gravity = b.isToggled();
this.parent.dirty();
});
this.objectVelocity = new GuiElement(mc);
this.scaleColumns = new GuiElement(mc);
this.scaleColumns.flex().column(4).stretch().vertical().height(2);
this.objectVelocity.flex().column(4).stretch().vertical().height(4);
this.linearVelocity = new GuiTrackpadElement(mc, (value) ->
{
this.component.linearVelocity = value.floatValue();
this.parent.dirty();
});
this.linearVelocity.tooltip(IKey.lang("blockbuster.gui.snowstorm.space.linear_velocity_tooltip"));
this.objectVelocity.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.space.object_velocity_title")).marginTop(12), Elements.label(IKey.lang("blockbuster.gui.snowstorm.space.linear_velocity")).marginTop(12), this.linearVelocity);
this.angularVelocity = new GuiTrackpadElement(mc, (value) ->
{
this.component.angularVelocity = value.floatValue();
this.parent.dirty();
});
this.angularVelocity.tooltip(IKey.lang("blockbuster.gui.snowstorm.space.angular_velocity_tooltip"));
this.objectVelocity.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.space.angular_velocity")).marginTop(12), this.angularVelocity);
this.scaleColumns.add(this.scale);
this.scaleColumns.add(this.scaleBillboard);
this.fields.add(this.position, this.rotation, this.scaleColumns, this.direction, this.acceleration, this.gravity, this.objectVelocity);
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.space.title";
}
@Override
protected BedrockComponentLocalSpace getComponent(BedrockScheme scheme)
{
return scheme.getOrCreate(BedrockComponentLocalSpace.class);
}
@Override
protected void fillData()
{
this.position.toggled(this.component.position);
this.rotation.toggled(this.component.rotation);
this.scale.toggled(this.component.scale);
this.scaleBillboard.toggled(this.component.scaleBillboard);
this.direction.toggled(this.component.direction);
this.acceleration.toggled(this.component.acceleration);
this.gravity.toggled(this.component.gravity);
this.linearVelocity.setValue(this.component.linearVelocity);
this.angularVelocity.setValue(this.component.angularVelocity);
updateButtons();
}
private void updateButtons()
{
/*this.scaleBillboard.removeFromParent();
if (this.scale.isToggled())
{
this.scaleColumns.add(this.scaleBillboard);
}
this.resizeParent();*/
}
} | 6,206 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormInitializationSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormInitializationSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.meta.BedrockComponentInitialization;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
public class GuiSnowstormInitializationSection extends GuiSnowstormComponentSection<BedrockComponentInitialization>
{
public GuiTextElement create;
public GuiTextElement update;
public GuiTextElement updateParticle;
public GuiSnowstormInitializationSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.create = new GuiTextElement(mc, 10000, (str) -> this.component.creation = this.parse(str, this.create, this.component.creation));
this.create.tooltip(IKey.lang("blockbuster.gui.snowstorm.initialization.create"));
this.update = new GuiTextElement(mc, 10000, (str) -> this.component.update = this.parse(str, this.update, this.component.update));
this.update.tooltip(IKey.lang("blockbuster.gui.snowstorm.initialization.update"));
this.updateParticle = new GuiTextElement(mc, 10000, (str) -> this.component.particleUpdate = this.parse(str, this.updateParticle, this.component.particleUpdate));
this.updateParticle.tooltip(IKey.lang("blockbuster.gui.snowstorm.initialization.particle_update_expression"));
this.fields.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.initialization.emitter_expression_title")).marginTop(12), this.create, this.update);
this.fields.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.initialization.particle_expression_title")).marginTop(12), this.updateParticle);
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.initialization.title";
}
@Override
protected BedrockComponentInitialization getComponent(BedrockScheme scheme)
{
return this.scheme.getOrCreate(BedrockComponentInitialization.class);
}
@Override
protected void fillData()
{
this.set(this.create, this.component.creation);
this.set(this.update, this.component.update);
this.set(this.updateParticle, this.component.particleUpdate);
}
} | 2,485 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormLifetimeSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormLifetimeSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.components.lifetime.BedrockComponentLifetime;
import mchorse.blockbuster.client.particles.components.lifetime.BedrockComponentLifetimeExpression;
import mchorse.blockbuster.client.particles.components.lifetime.BedrockComponentLifetimeLooping;
import mchorse.blockbuster.client.particles.components.lifetime.BedrockComponentLifetimeOnce;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.tooltips.LabelTooltip;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
public class GuiSnowstormLifetimeSection extends GuiSnowstormModeSection<BedrockComponentLifetime>
{
public GuiTextElement active;
public GuiTextElement expiration;
public GuiSnowstormLifetimeSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.active = new GuiTextElement(mc, 10000, (str) -> this.component.activeTime = this.parse(str, this.active, this.component.activeTime));
this.active.tooltip(IKey.lang(""));
this.expiration = new GuiTextElement(mc, 10000, (str) ->
{
if (this.component instanceof BedrockComponentLifetimeLooping)
{
BedrockComponentLifetimeLooping component = (BedrockComponentLifetimeLooping) this.component;
component.sleepTime = this.parse(str, this.expiration, component.sleepTime);
}
else
{
BedrockComponentLifetimeExpression component = (BedrockComponentLifetimeExpression) this.component;
component.expiration = this.parse(str, this.expiration, component.expiration);
}
this.parent.dirty();
});
this.expiration.tooltip(IKey.lang(""));
this.fields.add(this.active);
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.lifetime.title";
}
@Override
protected void fillModes(GuiCirculateElement button)
{
button.addLabel(IKey.lang("blockbuster.gui.snowstorm.lifetime.expression"));
button.addLabel(IKey.lang("blockbuster.gui.snowstorm.lifetime.looping"));
button.addLabel(IKey.lang("blockbuster.gui.snowstorm.lifetime.once"));
}
@Override
protected void restoreInfo(BedrockComponentLifetime component, BedrockComponentLifetime old)
{
component.activeTime = old.activeTime;
}
@Override
protected Class<BedrockComponentLifetime> getBaseClass()
{
return BedrockComponentLifetime.class;
}
@Override
protected Class getDefaultClass()
{
return BedrockComponentLifetimeLooping.class;
}
@Override
protected Class getModeClass(int value)
{
if (value == 0)
{
return BedrockComponentLifetimeExpression.class;
}
else if (value == 1)
{
return BedrockComponentLifetimeLooping.class;
}
return BedrockComponentLifetimeOnce.class;
}
@Override
protected void fillData()
{
super.fillData();
boolean once = this.component instanceof BedrockComponentLifetimeOnce;
this.expiration.setVisible(!once);
if (this.component instanceof BedrockComponentLifetimeExpression)
{
this.set(this.expiration, ((BedrockComponentLifetimeExpression) this.component).expiration);
((LabelTooltip) this.expiration.tooltip).label.set("blockbuster.gui.snowstorm.lifetime.expiration_expression");
((LabelTooltip) this.active.tooltip).label.set("blockbuster.gui.snowstorm.lifetime.active_expression");
}
else if (this.component instanceof BedrockComponentLifetimeLooping)
{
this.set(this.expiration, ((BedrockComponentLifetimeLooping) this.component).sleepTime);
((LabelTooltip) this.expiration.tooltip).label.set("blockbuster.gui.snowstorm.lifetime.sleep_time");
((LabelTooltip) this.active.tooltip).label.set("blockbuster.gui.snowstorm.lifetime.active_looping");
}
else
{
((LabelTooltip) this.active.tooltip).label.set("blockbuster.gui.snowstorm.lifetime.active_once");
}
this.set(this.active, this.component.activeTime);
this.expiration.removeFromParent();
if (!once)
{
this.fields.add(this.expiration);
}
this.resizeParent();
}
} | 4,735 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormCollisionSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormCollisionSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.motion.BedrockComponentMotionCollision;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiContext;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.math.Operation;
import mchorse.mclib.math.molang.MolangParser;
import net.minecraft.client.Minecraft;
public class GuiSnowstormCollisionSection extends GuiSnowstormComponentSection<BedrockComponentMotionCollision>
{
public GuiTextElement condition;
public GuiToggleElement realisticCollision;
public GuiToggleElement entityCollision;
public GuiToggleElement momentum;
public GuiToggleElement realisticCollisionDrag;
public GuiTrackpadElement collisionRotationDrag;
public GuiTrackpadElement drag;
public GuiTrackpadElement bounciness;
public GuiTrackpadElement randomBounciness; //randomize the direction vector
public GuiToggleElement preserveEnergy;
public GuiTrackpadElement randomDamp;
public GuiTrackpadElement damp;
public GuiTrackpadElement splitParticle; //split particle into n particles on collision
public GuiTrackpadElement splitParticleSpeedThreshold;
public GuiTrackpadElement radius;
public GuiToggleElement expire;
public GuiTextElement expirationDelay;
public GuiElement controlToggleElements;
public GuiElement randomBouncinessRow;
private boolean wasPresent;
private boolean updateButtons;
public GuiSnowstormCollisionSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.condition = new GuiTextElement(mc, 10000, (str) ->
{
this.component.enabled = str.isEmpty() ? MolangParser.ONE : this.parse(str, this.condition, this.component.enabled);
this.parent.dirty();
});
this.condition.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.condition_tooltip"));
this.realisticCollision = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.collision.realistic_collision"), (b) ->
{
this.component.realisticCollision = b.isToggled();
this.parent.dirty();
});
this.entityCollision = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.collision.entity_collision"), (b) ->
{
this.component.entityCollision = b.isToggled();
this.parent.dirty();
this.updateButtons();
});
this.momentum = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.collision.momentum"), (b) ->
{
this.component.momentum = b.isToggled();
this.parent.dirty();
});
this.realisticCollisionDrag = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.collision.realistic_collision_drag"), (b) ->
{
this.component.realisticCollisionDrag = b.isToggled();
this.parent.dirty();
});
this.realisticCollisionDrag.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.realistic_collision_drag_tooltip"));
this.drag = new GuiTrackpadElement(mc, (value) ->
{
this.component.collisionDrag = value.floatValue();
this.parent.dirty();
});
this.drag.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.drag"));
this.collisionRotationDrag = new GuiTrackpadElement(mc, (value) ->
{
this.component.rotationCollisionDrag = value.floatValue();
this.parent.dirty();
});
this.collisionRotationDrag.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.rotation_drag"));
this.bounciness = new GuiTrackpadElement(mc, (value) ->
{
this.component.bounciness = value.floatValue();
this.parent.dirty();
this.updateButtons = true;
});
this.bounciness.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.bounciness"));
this.randomBounciness = new GuiTrackpadElement(mc, (value) ->
{
this.component.randomBounciness = (float) Math.abs(value);
this.parent.dirty();
this.updateButtons = true;
});
this.randomBounciness.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.random_direction"));
this.preserveEnergy = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.collision.preserve_energy"), (b) -> this.parent.dirty());
this.preserveEnergy.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.preserve_energy_tooltip"));
this.damp = new GuiTrackpadElement(mc, (value) ->
{
this.component.damp = value.floatValue();
this.parent.dirty();
});
this.damp.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.damping.strength"));
this.damp.limit(0, 1);
this.randomDamp = new GuiTrackpadElement(mc, (value) ->
{
this.component.randomDamp = (float) Math.abs(value);
this.parent.dirty();
});
this.randomDamp.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.damping.randomness"));
this.randomDamp.limit(0, 1);
this.splitParticleSpeedThreshold = new GuiTrackpadElement(mc, (value) ->
{
this.component.splitParticleSpeedThreshold = value.floatValue();
this.parent.dirty();
});
this.splitParticleSpeedThreshold.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.split_particle.speed_threshold"));
this.splitParticle = new GuiTrackpadElement(mc, (value) ->
{
this.component.splitParticleCount = (int)Math.abs(value);
this.parent.dirty();
});
this.splitParticle.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.split_particle.count"));
this.splitParticle.limit(0, 99).integer();
this.radius = new GuiTrackpadElement(mc, (value) ->
{
this.component.radius = value.floatValue();
this.parent.dirty();
});
this.radius.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.radius"));
this.expire = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.collision.expire"), (b) ->
{
this.component.expireOnImpact = b.isToggled();
this.parent.dirty();
});
this.expirationDelay = new GuiTextElement(mc, 10000, (value) ->
{
this.component.expirationDelay = this.parse(value, this.expirationDelay, this.component.expirationDelay);
this.parent.dirty();
});
this.expirationDelay.tooltip(IKey.lang("blockbuster.gui.snowstorm.collision.expiration_delay"));
this.controlToggleElements = new GuiElement(mc);
this.controlToggleElements.flex().column(4).stretch().vertical().height(4);
this.controlToggleElements.add(this.condition, this.realisticCollision, this.entityCollision);
this.randomBouncinessRow = new GuiElement(mc);
this.randomBouncinessRow.flex().column(2).stretch().vertical().height(2);
this.randomBouncinessRow.add(this.randomBounciness);
this.fields.add(this.controlToggleElements, this.realisticCollisionDrag, this.drag, this.collisionRotationDrag, this.bounciness, this.randomBouncinessRow , this.radius, this.expire, this.expirationDelay);
this.fields.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.collision.damping.title")).marginTop(12), this.damp, this.randomDamp);
this.fields.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.collision.split_particle.title")).marginTop(12), this.splitParticle, this.splitParticleSpeedThreshold);
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.collision.title";
}
@Override
public void beforeSave(BedrockScheme scheme)
{
this.component.preserveEnergy = this.preserveEnergy.isToggled();
}
@Override
protected BedrockComponentMotionCollision getComponent(BedrockScheme scheme)
{
this.wasPresent = this.scheme.get(BedrockComponentMotionCollision.class) != null;
return scheme.getOrCreate(BedrockComponentMotionCollision.class);
}
@Override
protected void fillData()
{
this.set(this.condition, this.component.enabled);
this.realisticCollision.toggled(this.component.realisticCollision);
this.entityCollision.toggled(this.component.entityCollision);
this.momentum.toggled(this.component.momentum);
this.realisticCollisionDrag.toggled(this.component.realisticCollisionDrag);
this.drag.setValue(this.component.collisionDrag);
this.bounciness.setValue(this.component.bounciness);
this.randomBounciness.setValue(this.component.randomBounciness);
this.preserveEnergy.toggled(this.component.preserveEnergy);
this.damp.setValue(this.component.damp);
this.randomDamp.setValue(this.component.randomDamp);
this.splitParticle.setValue(this.component.splitParticleCount);
this.splitParticleSpeedThreshold.setValue(this.component.splitParticleSpeedThreshold);
this.radius.setValue(this.component.radius);
this.expire.toggled(this.component.expireOnImpact);
this.collisionRotationDrag.setValue(this.component.rotationCollisionDrag);
this.set(this.expirationDelay, this.component.expirationDelay);
this.updateButtons();
}
private void updateButtons()
{
this.preserveEnergy.removeFromParent();
this.momentum.removeFromParent();
if (this.entityCollision.isToggled())
{
this.controlToggleElements.add(this.momentum);
}
if (!Operation.equals(this.randomBounciness.value, 0) && Operation.equals(this.bounciness.value, 0))
{
this.randomBouncinessRow.add(this.preserveEnergy);
}
this.resizeParent();
}
@Override
public void draw(GuiContext context)
{
super.draw(context);
if (this.updateButtons)
{
this.updateButtons();
this.updateButtons = false;
}
}
}
| 10,870 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormCollisionLightingSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormCollisionLightingSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentCollisionAppearance;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentCollisionTinting;
import mchorse.blockbuster.client.particles.components.appearance.Tint;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiColorElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiLabel;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.math.Constant;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import mchorse.mclib.math.molang.expressions.MolangValue;
import mchorse.mclib.utils.Color;
import net.minecraft.client.Minecraft;
public class GuiSnowstormCollisionLightingSection extends GuiSnowstormLightingSection
{
public GuiToggleElement enabled;
private BedrockComponentCollisionAppearance appearanceComponent;
public GuiSnowstormCollisionLightingSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.enabled = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.collision.enabled"), (b) -> this.parent.dirty());
this.lighting.callback = (b) ->
{
this.appearanceComponent.lit = !b.isToggled();
this.parent.dirty();
};
this.fields.addBefore(this.lighting, this.enabled);
}
private BedrockComponentCollisionTinting getComponent()
{
return (BedrockComponentCollisionTinting) this.component;
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.collision.lighting.title";
}
@Override
public void beforeSave(BedrockScheme scheme)
{
this.getComponent().enabled = this.enabled.isToggled() ? MolangParser.ONE : MolangParser.ZERO;
}
@Override
public void setScheme(BedrockScheme scheme)
{
this.scheme = scheme; //cant call super as it would set the wrong component
this.component = scheme.getOrCreate(BedrockComponentCollisionTinting.class);
this.appearanceComponent = scheme.getOrCreate(BedrockComponentCollisionAppearance.class);
this.lighting.toggled(!this.appearanceComponent.lit);
this.enabled.toggled(MolangExpression.isOne(this.getComponent().enabled));
this.setTintsCache();
this.fillData();
}
}
| 3,031 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormGeneralSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormGeneralSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSectionManager;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.BedrockMaterial;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentAppearanceBillboard;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTexturePicker;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import org.lwjgl.opengl.GL11;
public class GuiSnowstormGeneralSection extends GuiSnowstormSection
{
public GuiTextElement identifier;
public GuiButtonElement pick;
public GuiCirculateElement material;
public GuiCirculateElement play;
public GuiTexturePicker texture;
public GuiSnowstormGeneralSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.identifier = new GuiTextElement(mc, 100, (str) ->
{
this.scheme.identifier = str;
this.parent.dirty();
});
this.identifier.tooltip(IKey.lang("blockbuster.gui.snowstorm.general.identifier"));
this.pick = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.snowstorm.general.pick"), (b) ->
{
GuiElement container = this.getParentContainer();
this.texture.fill(this.scheme.texture);
this.texture.flex().relative(container).wh(1F, 1F);
this.texture.resize();
container.add(this.texture);
});
this.material = new GuiCirculateElement(mc, (b) ->
{
this.scheme.material = BedrockMaterial.values()[this.material.getValue()];
this.parent.dirty();
});
this.material.addLabel(IKey.lang("blockbuster.gui.snowstorm.general.particles_opaque"));
this.material.addLabel(IKey.lang("blockbuster.gui.snowstorm.general.particles_alpha"));
this.material.addLabel(IKey.lang("blockbuster.gui.snowstorm.general.particles_blend"));
this.material.addLabel(IKey.lang("blockbuster.gui.snowstorm.general.particles_additive"));
this.texture = new GuiTexturePicker(mc, (rl) ->
{
if (rl == null)
{
rl = BedrockScheme.DEFAULT_TEXTURE;
}
this.setTextureSize(rl);
this.scheme.texture = rl;
this.parent.dirty();
});
this.play = new GuiCirculateElement(mc, (b) ->
{
this.parent.renderer.playing = this.play.getValue() == 0;
});
this.play.addLabel(IKey.lang("blockbuster.gui.snowstorm.general.play_playing"));
this.play.addLabel(IKey.lang("blockbuster.gui.snowstorm.general.play_paused"));
this.fields.add(this.identifier, Elements.row(mc, 5, 0, 20, this.pick, this.material), this.play);
}
@Override
protected void collapseState()
{
GuiSectionManager.setDefaultState(this.getClass().getSimpleName(), false);
super.collapseState();
}
private void setTextureSize(ResourceLocation rl)
{
BedrockComponentAppearanceBillboard component = this.scheme.get(BedrockComponentAppearanceBillboard.class);
if (component == null)
{
return;
}
this.mc.renderEngine.bindTexture(rl);
component.textureWidth = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
component.textureHeight = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.general.title";
}
@Override
public void setScheme(BedrockScheme scheme)
{
super.setScheme(scheme);
this.identifier.setText(scheme.identifier);
this.material.setValue(scheme.material.ordinal());
this.play.setValue(0);
}
}
| 4,445 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormCollisionAppearanceSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormCollisionAppearanceSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.BedrockMaterial;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentCollisionAppearance;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiButtonElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTexturePicker;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiLabel;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import mchorse.mclib.math.molang.MolangParser;
import mchorse.mclib.math.molang.expressions.MolangExpression;
import net.minecraft.client.Minecraft;
import net.minecraft.util.ResourceLocation;
import org.apache.commons.lang3.ArrayUtils;
import org.lwjgl.opengl.GL11;
public class GuiSnowstormCollisionAppearanceSection extends GuiSnowstormComponentSection<BedrockComponentCollisionAppearance>
{
/* inheriting this throughout the structure would make things less copy and paste */
public static final String GUI_PATH = "blockbuster.gui.snowstorm.appearance";
public GuiToggleElement enabled;
public GuiButtonElement pick;
public GuiCirculateElement material;
public GuiTexturePicker texture;
public GuiCirculateElement mode;
public GuiLabel modeLabel;
public GuiCirculateElement facingMode;
public GuiLabel facingModeLabel;
public GuiTextElement sizeW;
public GuiTextElement sizeH;
public GuiTextElement uvX;
public GuiTextElement uvY;
public GuiTextElement uvW;
public GuiTextElement uvH;
public GuiElement flipbook;
public GuiTrackpadElement stepX;
public GuiTrackpadElement stepY;
public GuiTrackpadElement fps;
public GuiTextElement max;
public GuiToggleElement stretch;
public GuiToggleElement loop;
public GuiSnowstormCollisionAppearanceSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.enabled = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.collision.enabled"), (b) -> this.parent.dirty());
this.pick = new GuiButtonElement(mc, IKey.lang("blockbuster.gui.snowstorm.general.pick"), (b) ->
{
GuiElement container = this.getParentContainer();
this.texture.fill(this.component.texture);
this.texture.flex().relative(container).wh(1F, 1F);
this.texture.resize();
container.add(this.texture);
});
this.material = new GuiCirculateElement(mc, (b) ->
{
this.component.material = BedrockMaterial.values()[this.material.getValue()];
this.parent.dirty();
});
this.material.addLabel(IKey.lang("blockbuster.gui.snowstorm.general.particles_opaque"));
this.material.addLabel(IKey.lang("blockbuster.gui.snowstorm.general.particles_alpha"));
this.material.addLabel(IKey.lang("blockbuster.gui.snowstorm.general.particles_blend"));
this.material.addLabel(IKey.lang("blockbuster.gui.snowstorm.general.particles_additive"));
this.texture = new GuiTexturePicker(mc, (rl) ->
{
if (rl == null)
{
rl = BedrockScheme.DEFAULT_TEXTURE;
}
this.setTextureSize(rl);
this.component.texture = rl;
this.parent.dirty();
});
this.mode = new GuiCirculateElement(mc, (b) ->
{
this.component.flipbook = this.mode.getValue() == 1;
this.updateElements();
this.parent.dirty();
});
this.mode.addLabel(IKey.lang(GUI_PATH +".regular"));
this.mode.addLabel(IKey.lang(GUI_PATH +".animated"));
this.modeLabel = Elements.label(IKey.lang("blockbuster.gui.snowstorm.mode"), 20).anchor(0, 0.5F);
this.facingMode = new GuiCirculateElement(mc, (b) ->
{
this.component.facing = GuiSnowstormAppearanceSection.SORTED_FACING_MODES[this.facingMode.getValue()];
this.parent.dirty();
});
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.direction_x"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.direction_y"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.direction_z"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.lookat_xyz"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.lookat_y"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.rotate_xyz"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.rotate_y"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.emitter_xy"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.emitter_xz"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.emitter_yz"));
this.facingModeLabel = Elements.label(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.label"), 20).anchor(0, 0.5F);
this.sizeW = new GuiTextElement(mc, 10000, (str) -> this.component.sizeW = this.parse(str, this.sizeW, this.component.sizeW));
this.sizeW.tooltip(IKey.lang(GUI_PATH +".width"));
this.sizeH = new GuiTextElement(mc, 10000, (str) -> this.component.sizeH = this.parse(str, this.sizeH, this.component.sizeH));
this.sizeH.tooltip(IKey.lang(GUI_PATH +".height"));
this.uvX = new GuiTextElement(mc, 10000, (str) -> this.component.uvX = this.parse(str, this.uvX, this.component.uvX));
this.uvX.tooltip(IKey.lang(GUI_PATH +".uv_x"));
this.uvY = new GuiTextElement(mc, 10000, (str) -> this.component.uvY = this.parse(str, this.uvY, this.component.uvY));
this.uvY.tooltip(IKey.lang(GUI_PATH +".uv_y"));
this.uvW = new GuiTextElement(mc, 10000, (str) -> this.component.uvW = this.parse(str, this.uvW, this.component.uvW));
this.uvW.tooltip(IKey.lang(GUI_PATH +".uv_w"));
this.uvH = new GuiTextElement(mc, 10000, (str) -> this.component.uvH = this.parse(str, this.uvH, this.component.uvH));
this.uvH.tooltip(IKey.lang(GUI_PATH +".uv_h"));
this.stepX = new GuiTrackpadElement(mc, (value) ->
{
this.component.stepX = value.floatValue();
this.parent.dirty();
});
this.stepX.tooltip(IKey.lang(GUI_PATH +".step_x"));
this.stepY = new GuiTrackpadElement(mc, (value) ->
{
this.component.stepY = value.floatValue();
this.parent.dirty();
});
this.stepY.tooltip(IKey.lang(GUI_PATH +".step_y"));
this.fps = new GuiTrackpadElement(mc, (value) ->
{
this.component.fps = value.floatValue();
this.parent.dirty();
});
this.fps.tooltip(IKey.lang(GUI_PATH +".fps"));
this.max = new GuiTextElement(mc, 10000, (str) -> this.component.maxFrame = this.parse(str, this.max, this.component.maxFrame));
this.max.tooltip(IKey.lang(GUI_PATH +".max"));
this.stretch = new GuiToggleElement(mc, IKey.lang(GUI_PATH +".stretch"), (b) ->
{
this.component.stretchFPS = b.isToggled();
this.parent.dirty();
});
this.stretch.tooltip(IKey.lang(GUI_PATH +".stretch_tooltip"));
this.loop = new GuiToggleElement(mc, IKey.lang(GUI_PATH +".loop"), (b) ->
{
this.component.loop = b.isToggled();
this.parent.dirty();
});
this.loop.tooltip(IKey.lang(GUI_PATH +".loop_tooltip"));
this.flipbook = new GuiElement(mc);
this.flipbook.flex().column(5).vertical().stretch();
this.flipbook.add(Elements.label(IKey.lang(GUI_PATH +".animated")).marginTop(12));
this.flipbook.add(Elements.row(mc, 5, 0, 20, this.stepX, this.stepY));
this.flipbook.add(Elements.row(mc, 5, 0, 20, this.fps, this.max));
this.flipbook.add(Elements.row(mc, 5, 0, 20, this.stretch, this.loop));
this.fields.add(this.enabled);
this.fields.add(Elements.row(mc, 5, 0, 20, this.pick, this.material));
this.fields.add(Elements.row(mc, 5, 0, 20, this.modeLabel, this.mode));
this.fields.add(Elements.row(mc, 5, 0, 20, this.facingModeLabel, this.facingMode));
this.fields.add(Elements.label(IKey.lang(GUI_PATH +".size")).marginTop(12));
this.fields.add(this.sizeW, this.sizeH);
this.fields.add(Elements.label(IKey.lang(GUI_PATH +".mapping")).marginTop(12));
this.fields.add(this.uvX, this.uvY, this.uvW, this.uvH);
}
private void setTextureSize(ResourceLocation rl)
{
BedrockComponentCollisionAppearance component = this.scheme.get(BedrockComponentCollisionAppearance.class);
if (component == null)
{
return;
}
this.mc.renderEngine.bindTexture(rl);
component.textureWidth = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_WIDTH);
component.textureHeight = GL11.glGetTexLevelParameteri(GL11.GL_TEXTURE_2D, 0, GL11.GL_TEXTURE_HEIGHT);
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.collision.appearance.title";
}
@Override
public void setScheme(BedrockScheme scheme)
{
super.setScheme(scheme);
this.material.setValue(this.component.material.ordinal());
}
@Override
public void beforeSave(BedrockScheme scheme)
{
this.component.enabled = this.enabled.isToggled() ? MolangParser.ONE : MolangParser.ZERO;
}
@Override
protected BedrockComponentCollisionAppearance getComponent(BedrockScheme scheme) {
return scheme.getOrCreate(BedrockComponentCollisionAppearance.class);
}
private void updateElements()
{
this.flipbook.removeFromParent();
if (this.component.flipbook)
{
this.fields.add(this.flipbook);
}
this.resizeParent();
}
@Override
protected void fillData()
{
super.fillData();
this.enabled.toggled(MolangExpression.isOne(component.enabled));
this.mode.setValue(this.component.flipbook ? 1 : 0);
this.facingMode.setValue(ArrayUtils.indexOf(GuiSnowstormAppearanceSection.SORTED_FACING_MODES, this.component.facing));
this.set(this.sizeW, this.component.sizeW);
this.set(this.sizeH, this.component.sizeH);
this.set(this.uvX, this.component.uvX);
this.set(this.uvY, this.component.uvY);
this.set(this.uvW, this.component.uvW);
this.set(this.uvH, this.component.uvH);
this.stepX.setValue(this.component.stepX);
this.stepY.setValue(this.component.stepY);
this.fps.setValue(this.component.fps);
this.set(this.max, this.component.maxFrame);
this.stretch.toggled(this.component.stretchFPS);
this.loop.toggled(this.component.loop);
this.updateElements();
}
}
| 11,778 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormExpirationSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormExpirationSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.expiration.BedrockComponentExpireBlocks;
import mchorse.blockbuster.client.particles.components.expiration.BedrockComponentExpireInBlocks;
import mchorse.blockbuster.client.particles.components.expiration.BedrockComponentExpireNotInBlocks;
import mchorse.blockbuster.client.particles.components.expiration.BedrockComponentKillPlane;
import mchorse.blockbuster.client.particles.components.expiration.BedrockComponentParticleLifetime;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.IGuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiIconElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiSlotElement;
import mchorse.mclib.client.gui.framework.elements.context.GuiSimpleContextMenu;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiLabel;
import mchorse.mclib.client.gui.framework.tooltips.LabelTooltip;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.Icons;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.block.Block;
import net.minecraft.client.Minecraft;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemBlock;
import net.minecraft.item.ItemStack;
public class GuiSnowstormExpirationSection extends GuiSnowstormSection
{
public GuiCirculateElement mode;
public GuiTextElement expression;
public GuiTrackpadElement a;
public GuiTrackpadElement b;
public GuiTrackpadElement c;
public GuiTrackpadElement d;
public GuiBlocksSection inBlocksSection;
public GuiBlocksSection notInBlocksSection;
private BedrockComponentParticleLifetime lifetime;
private BedrockComponentKillPlane plane;
private BedrockComponentExpireInBlocks inBlocks;
private BedrockComponentExpireNotInBlocks notInBlocks;
public GuiSnowstormExpirationSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.mode = new GuiCirculateElement(mc, (b) ->
{
this.lifetime.max = this.mode.getValue() == 1;
this.updateTooltip();
this.parent.dirty();
});
this.mode.addLabel(IKey.lang("blockbuster.gui.snowstorm.expiration.expression"));
this.mode.addLabel(IKey.lang("blockbuster.gui.snowstorm.expiration.max"));
this.expression = new GuiTextElement(mc, 10000, (str) -> this.lifetime.expression = this.parse(str, this.expression, this.lifetime.expression));
this.expression.tooltip(IKey.lang(""));
this.a = new GuiTrackpadElement(mc, (value) ->
{
this.plane.a = value.floatValue();
this.parent.dirty();
});
this.a.tooltip(IKey.str("Ax"));
this.b = new GuiTrackpadElement(mc, (value) ->
{
this.plane.b = value.floatValue();
this.parent.dirty();
});
this.b.tooltip(IKey.str("By"));
this.c = new GuiTrackpadElement(mc, (value) ->
{
this.plane.c = value.floatValue();
this.parent.dirty();
});
this.c.tooltip(IKey.str("Cz"));
this.d = new GuiTrackpadElement(mc, (value) ->
{
this.plane.d = value.floatValue();
this.parent.dirty();
});
this.d.tooltip(IKey.str("D"));
this.inBlocksSection = new GuiBlocksSection(mc, IKey.lang("blockbuster.gui.snowstorm.expiration.in_blocks"), this);
this.notInBlocksSection = new GuiBlocksSection(mc, IKey.lang("blockbuster.gui.snowstorm.expiration.not_in_blocks"), this);
this.fields.add(Elements.row(mc, 5, 0, 20, Elements.label(IKey.lang("blockbuster.gui.snowstorm.mode"), 20).anchor(0, 0.5F), this.mode));
this.fields.add(this.expression);
this.fields.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.expiration.kill_plane")).marginTop(12)
.tooltip(IKey.lang("blockbuster.gui.snowstorm.expiration.kill_plane_tooltip")));
this.fields.add(Elements.row(mc, 5, 0, 20, this.a, this.b));
this.fields.add(Elements.row(mc, 5, 0, 20, this.c, this.d));
this.fields.add(this.inBlocksSection, this.notInBlocksSection);
}
private void updateTooltip()
{
((LabelTooltip) this.expression.tooltip).label.set(this.lifetime.max ? "blockbuster.gui.snowstorm.expiration.max_tooltip" : "blockbuster.gui.snowstorm.expiration.expression_tooltip");
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.expiration.title";
}
@Override
public void setScheme(BedrockScheme scheme)
{
super.setScheme(scheme);
this.lifetime = scheme.getOrCreate(BedrockComponentParticleLifetime.class);
this.plane = scheme.getOrCreate(BedrockComponentKillPlane.class);
this.inBlocks = scheme.getOrCreate(BedrockComponentExpireInBlocks.class);
this.notInBlocks = scheme.getOrCreate(BedrockComponentExpireNotInBlocks.class);
this.mode.setValue(this.lifetime.max ? 1 : 0);
this.set(this.expression, this.lifetime.expression);
this.updateTooltip();
this.a.setValue(this.plane.a);
this.b.setValue(this.plane.b);
this.c.setValue(this.plane.c);
this.d.setValue(this.plane.d);
this.inBlocksSection.setComponent(this.inBlocks);
this.notInBlocksSection.setComponent(this.notInBlocks);
}
@Override
public void beforeSave(BedrockScheme scheme)
{
this.compileBlocks(this.inBlocks, this.inBlocksSection);
this.compileBlocks(this.notInBlocks, this.notInBlocksSection);
}
private void compileBlocks(BedrockComponentExpireBlocks component, GuiBlocksSection section)
{
component.blocks.clear();
for (IGuiElement child : section.blocks.getChildren())
{
if (child instanceof GuiSlotElement)
{
GuiSlotElement slot = (GuiSlotElement) child;
if (slot.getStack().getItem() instanceof ItemBlock)
{
component.blocks.add(((ItemBlock) slot.getStack().getItem()).getBlock());
}
else if (slot.getStack().isEmpty())
{
component.blocks.add(Blocks.AIR);
}
}
}
}
/**
* Blocks module
*/
public static class GuiBlocksSection extends GuiElement
{
public GuiElement blocks;
private GuiSnowstormExpirationSection parent;
private BedrockComponentExpireBlocks component;
public GuiBlocksSection(Minecraft mc, IKey title, GuiSnowstormExpirationSection parent)
{
super(mc);
this.parent = parent;
GuiIconElement add = new GuiIconElement(mc, Icons.ADD, (b) ->
{
this.addBlock(Blocks.AIR);
this.parent.resizeParent();
});
GuiLabel label = Elements.label(title).anchor(0, 0.5F);
GuiElement row = Elements.row(mc, 5, 0, 20, label, add);
this.blocks = new GuiElement(mc);
add.flex().wh(10, 16);
label.flex().h(0);
row.flex().row(5).preferred(0);
this.blocks.flex().grid(7).items(6).resizes(true);
this.flex().column(5).vertical().stretch();
this.add(row, this.blocks);
}
public void setComponent(BedrockComponentExpireBlocks component)
{
this.component = component;
this.blocks.removeAll();
for (Block block : this.component.blocks)
{
this.addBlock(block);
}
}
public void addBlock(Block block)
{
GuiSlotElement slotElement = new GuiSlotElement(this.mc, 0, null);
slotElement.callback = (stack) ->
{
if (!(stack.getItem() instanceof ItemBlock))
{
slotElement.setStack(ItemStack.EMPTY);
}
};
slotElement.setStack(new ItemStack(block, 1));
slotElement.context(() -> new GuiSimpleContextMenu(this.mc).action(Icons.REMOVE, IKey.lang("Remove block"), () ->
{
slotElement.removeFromParent();
this.parent.resizeParent();
}));
this.blocks.add(slotElement);
}
}
} | 8,914 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
GuiSnowstormAppearanceSection.java | /FileExtraction/Java_unseen/mchorse_blockbuster/src/main/java/mchorse/blockbuster/client/gui/dashboard/panels/snowstorm/sections/GuiSnowstormAppearanceSection.java | package mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.sections;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSectionManager;
import mchorse.blockbuster.client.gui.dashboard.panels.snowstorm.GuiSnowstorm;
import mchorse.blockbuster.client.particles.BedrockScheme;
import mchorse.blockbuster.client.particles.components.appearance.BedrockComponentAppearanceBillboard;
import mchorse.blockbuster.client.particles.components.appearance.CameraFacing;
import mchorse.mclib.client.gui.framework.elements.GuiElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiCirculateElement;
import mchorse.mclib.client.gui.framework.elements.buttons.GuiToggleElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTextElement;
import mchorse.mclib.client.gui.framework.elements.input.GuiTrackpadElement;
import mchorse.mclib.client.gui.framework.elements.utils.GuiLabel;
import mchorse.mclib.client.gui.utils.Elements;
import mchorse.mclib.client.gui.utils.keys.IKey;
import net.minecraft.client.Minecraft;
import org.apache.commons.lang3.ArrayUtils;
public class GuiSnowstormAppearanceSection extends GuiSnowstormComponentSection<BedrockComponentAppearanceBillboard>
{
public static final CameraFacing[] SORTED_FACING_MODES = {CameraFacing.DIRECTION_X, CameraFacing.DIRECTION_Y, CameraFacing.DIRECTION_Z, CameraFacing.LOOKAT_XYZ, CameraFacing.LOOKAT_Y, CameraFacing.LOOKAT_DIRECTION, CameraFacing.ROTATE_XYZ, CameraFacing.ROTATE_Y, CameraFacing.EMITTER_XY, CameraFacing.EMITTER_XZ, CameraFacing.EMITTER_YZ};
public GuiCirculateElement mode;
public GuiLabel modeLabel;
public GuiCirculateElement facingMode;
public GuiLabel facingModeLabel;
public GuiTextElement sizeW;
public GuiTextElement sizeH;
public GuiTextElement uvX;
public GuiTextElement uvY;
public GuiTextElement uvW;
public GuiTextElement uvH;
public GuiElement modeRow;
public GuiElement directionContainer;
public GuiCirculateElement directionMode;
public GuiTrackpadElement speedThreshold;
public GuiTextElement directionX;
public GuiTextElement directionY;
public GuiTextElement directionZ;
public GuiElement flipbook;
public GuiTrackpadElement stepX;
public GuiTrackpadElement stepY;
public GuiTrackpadElement fps;
public GuiTextElement max;
public GuiToggleElement stretch;
public GuiToggleElement loop;
public GuiSnowstormAppearanceSection(Minecraft mc, GuiSnowstorm parent)
{
super(mc, parent);
this.mode = new GuiCirculateElement(mc, (b) ->
{
this.component.flipbook = this.mode.getValue() == 1;
this.updateElements();
this.parent.dirty();
});
this.mode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.regular"));
this.mode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.animated"));
this.modeLabel = Elements.label(IKey.lang("blockbuster.gui.snowstorm.mode"), 20).anchor(0, 0.5F);
this.facingMode = new GuiCirculateElement(mc, (b) ->
{
this.component.facing = SORTED_FACING_MODES[this.facingMode.getValue()];
this.updateElements();
this.parent.dirty();
});
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.direction_x"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.direction_y"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.direction_z"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.lookat_xyz"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.lookat_y"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.lookat_direction"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.rotate_xyz"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.rotate_y"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.emitter_xy"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.emitter_xz"));
this.facingMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.emitter_yz"));
this.facingModeLabel = Elements.label(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.label"), 20).anchor(0, 0.5F);
this.directionContainer = new GuiElement(mc);
this.directionContainer.flex().column(5).vertical().stretch();
this.directionMode = new GuiCirculateElement(mc, (b) -> {
this.component.customDirection = b.getValue() == 1;
this.updateElements();
this.parent.dirty();
});
this.directionMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.direction_mode.motion"));
this.directionMode.addLabel(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.direction_mode.custom"));
this.directionX = new GuiTextElement(mc, 10000, (str) -> {
this.component.directionX = this.parse(str, this.directionX, this.component.directionX);
});
this.directionX.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.direction_mode.direction_x_tooltip"));
this.directionY = new GuiTextElement(mc, 10000, (str) -> {
this.component.directionY = this.parse(str, this.directionY, this.component.directionY);
});
this.directionX.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.direction_mode.direction_y_tooltip"));
this.directionZ = new GuiTextElement(mc, 10000, (str) -> {
this.component.directionZ = this.parse(str, this.directionZ, this.component.directionZ);
});
this.directionX.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.direction_mode.direction_z_tooltip"));
this.speedThreshold = new GuiTrackpadElement(mc, (value) -> {
this.component.directionSpeedThreshhold = value.floatValue();
this.parent.dirty();
});
this.speedThreshold.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.camera_facing.direction_mode.speed_threshold_tooltip"));
this.directionContainer.add(this.directionMode, this.speedThreshold);
this.sizeW = new GuiTextElement(mc, 10000, (str) -> this.component.sizeW = this.parse(str, this.sizeW, this.component.sizeW));
this.sizeW.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.width"));
this.sizeH = new GuiTextElement(mc, 10000, (str) -> this.component.sizeH = this.parse(str, this.sizeH, this.component.sizeH));
this.sizeH.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.height"));
this.uvX = new GuiTextElement(mc, 10000, (str) -> this.component.uvX = this.parse(str, this.uvX, this.component.uvX));
this.uvX.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.uv_x"));
this.uvY = new GuiTextElement(mc, 10000, (str) -> this.component.uvY = this.parse(str, this.uvY, this.component.uvY));
this.uvY.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.uv_y"));
this.uvW = new GuiTextElement(mc, 10000, (str) -> this.component.uvW = this.parse(str, this.uvW, this.component.uvW));
this.uvW.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.uv_w"));
this.uvH = new GuiTextElement(mc, 10000, (str) -> this.component.uvH = this.parse(str, this.uvH, this.component.uvH));
this.uvH.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.uv_h"));
this.stepX = new GuiTrackpadElement(mc, (value) ->
{
this.component.stepX = value.floatValue();
this.parent.dirty();
});
this.stepX.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.step_x"));
this.stepY = new GuiTrackpadElement(mc, (value) ->
{
this.component.stepY = value.floatValue();
this.parent.dirty();
});
this.stepY.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.step_y"));
this.fps = new GuiTrackpadElement(mc, (value) ->
{
this.component.fps = value.floatValue();
this.parent.dirty();
});
this.fps.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.fps"));
this.max = new GuiTextElement(mc, 10000, (str) -> this.component.maxFrame = this.parse(str, this.max, this.component.maxFrame));
this.max.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.max"));
this.stretch = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.appearance.stretch"), (b) ->
{
this.component.stretchFPS = b.isToggled();
this.parent.dirty();
});
this.stretch.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.stretch_tooltip"));
this.loop = new GuiToggleElement(mc, IKey.lang("blockbuster.gui.snowstorm.appearance.loop"), (b) ->
{
this.component.loop = b.isToggled();
this.parent.dirty();
});
this.loop.tooltip(IKey.lang("blockbuster.gui.snowstorm.appearance.loop_tooltip"));
this.modeRow = Elements.row(mc, 5, 0, 20, this.facingModeLabel, this.facingMode);
this.flipbook = new GuiElement(mc);
this.flipbook.flex().column(5).vertical().stretch();
this.flipbook.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.appearance.animated")).marginTop(12));
this.flipbook.add(Elements.row(mc, 5, 0, 20, this.stepX, this.stepY));
this.flipbook.add(Elements.row(mc, 5, 0, 20, this.fps, this.max));
this.flipbook.add(Elements.row(mc, 5, 0, 20, this.stretch, this.loop));
this.fields.add(Elements.row(mc, 5, 0, 20, this.modeLabel, this.mode));
this.fields.add(this.modeRow);
this.fields.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.appearance.size")).marginTop(12));
this.fields.add(this.sizeW, this.sizeH);
this.fields.add(Elements.label(IKey.lang("blockbuster.gui.snowstorm.appearance.mapping")).marginTop(12));
this.fields.add(this.uvX, this.uvY, this.uvW, this.uvH);
}
@Override
protected void collapseState()
{
GuiSectionManager.setDefaultState(this.getClass().getSimpleName(), false);
super.collapseState();
}
private void updateElements()
{
this.directionContainer.removeFromParent();
if (this.component.facing.isDirection)
{
this.fields.addAfter(this.modeRow, this.directionContainer);
this.speedThreshold.removeFromParent();
this.directionX.removeFromParent();
this.directionY.removeFromParent();
this.directionZ.removeFromParent();
if (this.component.customDirection)
{
this.directionContainer.add(this.directionX, this.directionY, this.directionZ);
}
else
{
this.directionContainer.add(this.speedThreshold);
}
}
else
{
this.directionContainer.removeFromParent();
}
this.flipbook.removeFromParent();
if (this.component.flipbook)
{
this.fields.add(this.flipbook);
}
this.resizeParent();
}
@Override
public String getTitle()
{
return "blockbuster.gui.snowstorm.appearance.title";
}
@Override
protected BedrockComponentAppearanceBillboard getComponent(BedrockScheme scheme)
{
return scheme.getOrCreateExact(BedrockComponentAppearanceBillboard.class);
}
@Override
protected void fillData()
{
super.fillData();
this.mode.setValue(this.component.flipbook ? 1 : 0);
this.facingMode.setValue(ArrayUtils.indexOf(SORTED_FACING_MODES, this.component.facing));
this.set(this.sizeW, this.component.sizeW);
this.set(this.sizeH, this.component.sizeH);
this.set(this.uvX, this.component.uvX);
this.set(this.uvY, this.component.uvY);
this.set(this.uvW, this.component.uvW);
this.set(this.uvH, this.component.uvH);
this.set(this.directionX, this.component.directionX);
this.set(this.directionY, this.component.directionY);
this.set(this.directionZ, this.component.directionZ);
this.speedThreshold.setValue(this.component.directionSpeedThreshhold);
this.directionMode.setValue(this.component.customDirection ? 1 : 0);
this.stepX.setValue(this.component.stepX);
this.stepY.setValue(this.component.stepY);
this.fps.setValue(this.component.fps);
this.set(this.max, this.component.maxFrame);
this.stretch.toggled(this.component.stretchFPS);
this.loop.toggled(this.component.loop);
this.updateElements();
}
}
| 13,177 | Java | .java | mchorse/blockbuster | 159 | 39 | 10 | 2016-06-17T21:52:40Z | 2024-05-08T20:37:12Z |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.